You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

254 lines
8.4 KiB

  1. // Package psql implements an event sink backed by a PostgreSQL database.
  2. package psql
  3. import (
  4. "context"
  5. "database/sql"
  6. "errors"
  7. "fmt"
  8. "strings"
  9. "time"
  10. "github.com/gogo/protobuf/proto"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. "github.com/tendermint/tendermint/libs/pubsub/query"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. const (
  16. tableBlocks = "blocks"
  17. tableTxResults = "tx_results"
  18. tableEvents = "events"
  19. tableAttributes = "attributes"
  20. driverName = "postgres"
  21. )
  22. // EventSink is an indexer backend providing the tx/block index services. This
  23. // implementation stores records in a PostgreSQL database using the schema
  24. // defined in state/indexer/sink/psql/schema.sql.
  25. type EventSink struct {
  26. store *sql.DB
  27. chainID string
  28. }
  29. // NewEventSink constructs an event sink associated with the PostgreSQL
  30. // database specified by connStr. Events written to the sink are attributed to
  31. // the specified chainID.
  32. func NewEventSink(connStr, chainID string) (*EventSink, error) {
  33. db, err := sql.Open(driverName, connStr)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return &EventSink{
  38. store: db,
  39. chainID: chainID,
  40. }, nil
  41. }
  42. // DB returns the underlying Postgres connection used by the sink.
  43. // This is exported to support testing.
  44. func (es *EventSink) DB() *sql.DB { return es.store }
  45. // runInTransaction executes query in a fresh database transaction.
  46. // If query reports an error, the transaction is rolled back and the
  47. // error from query is reported to the caller.
  48. // Otherwise, the result of committing the transaction is returned.
  49. func runInTransaction(db *sql.DB, query func(*sql.Tx) error) error {
  50. dbtx, err := db.Begin()
  51. if err != nil {
  52. return err
  53. }
  54. if err := query(dbtx); err != nil {
  55. _ = dbtx.Rollback() // report the initial error, not the rollback
  56. return err
  57. }
  58. return dbtx.Commit()
  59. }
  60. // queryWithID executes the specified SQL query with the given arguments,
  61. // expecting a single-row, single-column result containing an ID. If the query
  62. // succeeds, the ID from the result is returned.
  63. func queryWithID(tx *sql.Tx, query string, args ...interface{}) (uint32, error) {
  64. var id uint32
  65. if err := tx.QueryRow(query, args...).Scan(&id); err != nil {
  66. return 0, err
  67. }
  68. return id, nil
  69. }
  70. // insertEvents inserts a slice of events and any indexed attributes of those
  71. // events into the database associated with dbtx.
  72. //
  73. // If txID > 0, the event is attributed to the Tendermint transaction with that
  74. // ID; otherwise it is recorded as a block event.
  75. func insertEvents(dbtx *sql.Tx, blockID, txID uint32, evts []abci.Event) error {
  76. // Populate the transaction ID field iff one is defined (> 0).
  77. var txIDArg interface{}
  78. if txID > 0 {
  79. txIDArg = txID
  80. }
  81. // Add each event to the events table, and retrieve its row ID to use when
  82. // adding any attributes the event provides.
  83. for _, evt := range evts {
  84. // Skip events with an empty type.
  85. if evt.Type == "" {
  86. continue
  87. }
  88. eid, err := queryWithID(dbtx, `
  89. INSERT INTO `+tableEvents+` (block_id, tx_id, type) VALUES ($1, $2, $3)
  90. RETURNING rowid;
  91. `, blockID, txIDArg, evt.Type)
  92. if err != nil {
  93. return err
  94. }
  95. // Add any attributes flagged for indexing.
  96. for _, attr := range evt.Attributes {
  97. if !attr.Index {
  98. continue
  99. }
  100. compositeKey := evt.Type + "." + string(attr.Key)
  101. if _, err := dbtx.Exec(`
  102. INSERT INTO `+tableAttributes+` (event_id, key, composite_key, value)
  103. VALUES ($1, $2, $3, $4);
  104. `, eid, attr.Key, compositeKey, attr.Value); err != nil {
  105. return err
  106. }
  107. }
  108. }
  109. return nil
  110. }
  111. // makeIndexedEvent constructs an event from the specified composite key and
  112. // value. If the key has the form "type.name", the event will have a single
  113. // attribute with that name and the value; otherwise the event will have only
  114. // a type and no attributes.
  115. func makeIndexedEvent(compositeKey, value string) abci.Event {
  116. i := strings.Index(compositeKey, ".")
  117. if i < 0 {
  118. return abci.Event{Type: compositeKey}
  119. }
  120. return abci.Event{Type: compositeKey[:i], Attributes: []abci.EventAttribute{
  121. {Key: []byte(compositeKey[i+1:]), Value: []byte(value), Index: true},
  122. }}
  123. }
  124. // IndexBlockEvents indexes the specified block header, part of the
  125. // indexer.EventSink interface.
  126. func (es *EventSink) IndexBlockEvents(h types.EventDataNewBlockHeader) error {
  127. ts := time.Now().UTC()
  128. return runInTransaction(es.store, func(dbtx *sql.Tx) error {
  129. // Add the block to the blocks table and report back its row ID for use
  130. // in indexing the events for the block.
  131. blockID, err := queryWithID(dbtx, `
  132. INSERT INTO `+tableBlocks+` (height, chain_id, created_at)
  133. VALUES ($1, $2, $3)
  134. ON CONFLICT DO NOTHING
  135. RETURNING rowid;
  136. `, h.Header.Height, es.chainID, ts)
  137. if err == sql.ErrNoRows {
  138. return nil // we already saw this block; quietly succeed
  139. } else if err != nil {
  140. return fmt.Errorf("indexing block header: %w", err)
  141. }
  142. // Insert the special block meta-event for height.
  143. if err := insertEvents(dbtx, blockID, 0, []abci.Event{
  144. makeIndexedEvent(types.BlockHeightKey, fmt.Sprint(h.Header.Height)),
  145. }); err != nil {
  146. return fmt.Errorf("block meta-events: %w", err)
  147. }
  148. // Insert all the block events. Order is important here,
  149. if err := insertEvents(dbtx, blockID, 0, h.ResultBeginBlock.Events); err != nil {
  150. return fmt.Errorf("begin-block events: %w", err)
  151. }
  152. if err := insertEvents(dbtx, blockID, 0, h.ResultEndBlock.Events); err != nil {
  153. return fmt.Errorf("end-block events: %w", err)
  154. }
  155. return nil
  156. })
  157. }
  158. func (es *EventSink) IndexTxEvents(txrs []*abci.TxResult) error {
  159. ts := time.Now().UTC()
  160. for _, txr := range txrs {
  161. // Encode the result message in protobuf wire format for indexing.
  162. resultData, err := proto.Marshal(txr)
  163. if err != nil {
  164. return fmt.Errorf("marshaling tx_result: %w", err)
  165. }
  166. // Index the hash of the underlying transaction as a hex string.
  167. txHash := fmt.Sprintf("%X", types.Tx(txr.Tx).Hash())
  168. if err := runInTransaction(es.store, func(dbtx *sql.Tx) error {
  169. // Find the block associated with this transaction. The block header
  170. // must have been indexed prior to the transactions belonging to it.
  171. blockID, err := queryWithID(dbtx, `
  172. SELECT rowid FROM `+tableBlocks+` WHERE height = $1 AND chain_id = $2;
  173. `, txr.Height, es.chainID)
  174. if err != nil {
  175. return fmt.Errorf("finding block ID: %w", err)
  176. }
  177. // Insert a record for this tx_result and capture its ID for indexing events.
  178. txID, err := queryWithID(dbtx, `
  179. INSERT INTO `+tableTxResults+` (block_id, index, created_at, tx_hash, tx_result)
  180. VALUES ($1, $2, $3, $4, $5)
  181. ON CONFLICT DO NOTHING
  182. RETURNING rowid;
  183. `, blockID, txr.Index, ts, txHash, resultData)
  184. if err == sql.ErrNoRows {
  185. return nil // we already saw this transaction; quietly succeed
  186. } else if err != nil {
  187. return fmt.Errorf("indexing tx_result: %w", err)
  188. }
  189. // Insert the special transaction meta-events for hash and height.
  190. if err := insertEvents(dbtx, blockID, txID, []abci.Event{
  191. makeIndexedEvent(types.TxHashKey, txHash),
  192. makeIndexedEvent(types.TxHeightKey, fmt.Sprint(txr.Height)),
  193. }); err != nil {
  194. return fmt.Errorf("indexing transaction meta-events: %w", err)
  195. }
  196. // Index any events packaged with the transaction.
  197. if err := insertEvents(dbtx, blockID, txID, txr.Result.Events); err != nil {
  198. return fmt.Errorf("indexing transaction events: %w", err)
  199. }
  200. return nil
  201. }); err != nil {
  202. return err
  203. }
  204. }
  205. return nil
  206. }
  207. // SearchBlockEvents is not implemented by this sink, and reports an error for all queries.
  208. func (es *EventSink) SearchBlockEvents(ctx context.Context, q *query.Query) ([]int64, error) {
  209. return nil, errors.New("block search is not supported via the postgres event sink")
  210. }
  211. // SearchTxEvents is not implemented by this sink, and reports an error for all queries.
  212. func (es *EventSink) SearchTxEvents(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) {
  213. return nil, errors.New("tx search is not supported via the postgres event sink")
  214. }
  215. // GetTxByHash is not implemented by this sink, and reports an error for all queries.
  216. func (es *EventSink) GetTxByHash(hash []byte) (*abci.TxResult, error) {
  217. return nil, errors.New("getTxByHash is not supported via the postgres event sink")
  218. }
  219. // HasBlock is not implemented by this sink, and reports an error for all queries.
  220. func (es *EventSink) HasBlock(h int64) (bool, error) {
  221. return false, errors.New("hasBlock is not supported via the postgres event sink")
  222. }
  223. // Stop closes the underlying PostgreSQL database.
  224. func (es *EventSink) Stop() error { return es.store.Close() }