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.

352 lines
12 KiB

  1. # ADR 065: Custom Event Indexing
  2. - [ADR 065: Custom Event Indexing](#adr-065-custom-event-indexing)
  3. - [Changelog](#changelog)
  4. - [Status](#status)
  5. - [Context](#context)
  6. - [Alternative Approaches](#alternative-approaches)
  7. - [Decision](#decision)
  8. - [Detailed Design](#detailed-design)
  9. - [EventSink](#eventsink)
  10. - [Supported Sinks](#supported-sinks)
  11. - [`KVEventSink`](#kveventsink)
  12. - [`PSQLEventSink`](#psqleventsink)
  13. - [Configuration](#configuration)
  14. - [Future Improvements](#future-improvements)
  15. - [Consequences](#consequences)
  16. - [Positive](#positive)
  17. - [Negative](#negative)
  18. - [Neutral](#neutral)
  19. - [References](#references)
  20. ## Changelog
  21. - April 1, 2021: Initial Draft (@alexanderbez)
  22. ## Status
  23. Accepted
  24. ## Context
  25. Currently, Tendermint Core supports block and transaction event indexing through
  26. the `tx_index.indexer` configuration. Events are captured in transactions and
  27. are indexed via a `TxIndexer` type. Events are captured in blocks, specifically
  28. from `BeginBlock` and `EndBlock` application responses, and are indexed via a
  29. `BlockIndexer` type. Both of these types are managed by a single `IndexerService`
  30. which is responsible for consuming events and sending those events off to be
  31. indexed by the respective type.
  32. In addition to indexing, Tendermint Core also supports the ability to query for
  33. both indexed transaction and block events via Tendermint's RPC layer. The ability
  34. to query for these indexed events facilitates a great multitude of upstream client
  35. and application capabilities, e.g. block explorers, IBC relayers, and auxiliary
  36. data availability and indexing services.
  37. Currently, Tendermint only supports indexing via a `kv` indexer, which is supported
  38. by an underlying embedded key/value store database. The `kv` indexer implements
  39. its own indexing and query mechanisms. While the former is somewhat trivial,
  40. providing a rich and flexible query layer is not as trivial and has caused many
  41. issues and UX concerns for upstream clients and applications.
  42. The fragile nature of the proprietary `kv` query engine and the potential
  43. performance and scaling issues that arise when a large number of consumers are
  44. introduced, motivate the need for a more robust and flexible indexing and query
  45. solution.
  46. ## Alternative Approaches
  47. With regards to alternative approaches to a more robust solution, the only serious
  48. contender that was considered was to transition to using [SQLite](https://www.sqlite.org/index.html).
  49. While the approach would work, it locks us into a specific query language and
  50. storage layer, so in some ways it's only a bit better than our current approach.
  51. In addition, the implementation would require the introduction of CGO into the
  52. Tendermint Core stack, whereas right now CGO is only introduced depending on
  53. the database used.
  54. ## Decision
  55. We will adopt a similar approach to that of the Cosmos SDK's `KVStore` state
  56. listening described in [ADR-038](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-038-state-listening.md).
  57. Namely, we will perform the following:
  58. - Introduce a new interface, `EventSink`, that all data sinks must implement.
  59. - Augment the existing `tx_index.indexer` configuration to now accept a series
  60. of one or more indexer types, i.e sinks.
  61. - Combine the current `TxIndexer` and `BlockIndexer` into a single `KVEventSink`
  62. that implements the `EventSink` interface.
  63. - Introduce an additional `EventSink` that is backed by [PostgreSQL](https://www.postgresql.org/).
  64. - Implement the necessary schemas to support both block and transaction event
  65. indexing.
  66. - Update `IndexerService` to use a series of `EventSinks`.
  67. - Proxy queries to the relevant sink's native query layer.
  68. - Update all relevant RPC methods.
  69. ## Detailed Design
  70. ### EventSink
  71. We introduce the `EventSink` interface type that all supported sinks must implement.
  72. The interface is defined as follows:
  73. ```go
  74. type EventSink interface {
  75. IndexBlockEvents(types.EventDataNewBlockHeader) error
  76. IndexTxEvents(*abci.TxResult) error
  77. SearchBlockEvents(context.Context, *query.Query) ([]int64, error)
  78. SearchTxEvents(context.Context, *query.Query) ([]*abci.TxResult, error)
  79. GetTxByHash([]byte) (*abci.TxResult, error)
  80. HasBlock(int64) (bool, error)
  81. }
  82. ```
  83. The `IndexerService` will accept a list of one or more `EventSink` types. During
  84. the `OnStart` method it will call the appropriate APIs on each `EventSink` to
  85. index both block and transaction events.
  86. ### Supported Sinks
  87. We will initially support two `EventSink` types out of the box.
  88. #### `KVEventSink`
  89. This type of `EventSink` is a combination of the `TxIndexer` and `BlockIndexer`
  90. indexers, both of which are backed by a single embedded key/value database.
  91. A bulk of the existing business logic will remain the same, but the existing APIs
  92. mapped to the new `EventSink` API. Both types will be removed in favor of a single
  93. `KVEventSink` type.
  94. The `KVEventSink` will be the only `EventSink` enabled by default, so from a UX
  95. perspective, operators should not notice a difference apart from a configuration
  96. change.
  97. We omit `EventSink` implementation details as it should be fairly straightforward
  98. to map the existing business logic to the new APIs.
  99. #### `PSQLEventSink`
  100. This type of `EventSink` indexes block and transaction events into a [PostgreSQL](https://www.postgresql.org/).
  101. database. We define and automatically migrate the following schema when the
  102. `IndexerService` starts.
  103. ```sql
  104. -- Table Definition ----------------------------------------------
  105. CREATE TYPE IF NOT EXISTS block_event_type AS ENUM ('begin_block', 'end_block');
  106. CREATE TABLE IF NOT EXISTS block_events (
  107. id SERIAL PRIMARY KEY,
  108. key VARCHAR NOT NULL,
  109. value VARCHAR NOT NULL,
  110. height INTEGER NOT NULL,
  111. type block_event_type
  112. );
  113. CREATE TABLE IF NOT EXISTS tx_results {
  114. id SERIAL PRIMARY KEY,
  115. tx_result BYTEA NOT NULL
  116. }
  117. CREATE TABLE IF NOT EXISTS tx_events (
  118. id SERIAL PRIMARY KEY,
  119. key VARCHAR NOT NULL,
  120. value VARCHAR NOT NULL,
  121. height INTEGER NOT NULL,
  122. hash VARCHAR NOT NULL,
  123. FOREIGN KEY (tx_result_id) REFERENCES tx_results(id) ON DELETE CASCADE
  124. );
  125. -- Indices -------------------------------------------------------
  126. CREATE INDEX idx_block_events_key_value ON block_events(key, value);
  127. CREATE INDEX idx_tx_events_key_value ON tx_events(key, value);
  128. CREATE INDEX idx_tx_events_hash ON tx_events(hash);
  129. ```
  130. The `PSQLEventSink` will implement the `EventSink` interface as follows
  131. (some details omitted for brevity):
  132. ```go
  133. func NewPSQLEventSink(connStr string) (*PSQLEventSink, error) {
  134. db, err := sql.Open("postgres", connStr)
  135. if err != nil {
  136. return nil, err
  137. }
  138. // ...
  139. }
  140. func (es *PSQLEventSink) IndexBlockEvents(h types.EventDataNewBlockHeader) error {
  141. sqlStmt := sq.Insert("block_events").Columns("key", "value", "height", "type")
  142. // index the reserved block height index
  143. sqlStmt = sqlStmt.Values(types.BlockHeightKey, h.Header.Height, h.Header.Height, "")
  144. for _, event := range h.ResultBeginBlock.Events {
  145. // only index events with a non-empty type
  146. if len(event.Type) == 0 {
  147. continue
  148. }
  149. for _, attr := range event.Attributes {
  150. if len(attr.Key) == 0 {
  151. continue
  152. }
  153. // index iff the event specified index:true and it's not a reserved event
  154. compositeKey := fmt.Sprintf("%s.%s", event.Type, string(attr.Key))
  155. if compositeKey == types.BlockHeightKey {
  156. return fmt.Errorf("event type and attribute key \"%s\" is reserved; please use a different key", compositeKey)
  157. }
  158. if attr.GetIndex() {
  159. sqlStmt = sqlStmt.Values(compositeKey, string(attr.Value), h.Header.Height, BlockEventTypeBeginBlock)
  160. }
  161. }
  162. }
  163. // index end_block events...
  164. // execute sqlStmt db query...
  165. }
  166. func (es *PSQLEventSink) IndexTxEvents(txr *abci.TxResult) error {
  167. sqlStmtEvents := sq.Insert("tx_events").Columns("key", "value", "height", "hash", "tx_result_id")
  168. sqlStmtTxResult := sq.Insert("tx_results").Columns("tx_result")
  169. // store the tx result
  170. txBz, err := proto.Marshal(txr)
  171. if err != nil {
  172. return err
  173. }
  174. sqlStmtTxResult = sqlStmtTxResult.Values(txBz)
  175. // execute sqlStmtTxResult db query...
  176. // index the reserved height and hash indices
  177. hash := types.Tx(txr.Tx).Hash()
  178. sqlStmtEvents = sqlStmtEvents.Values(types.TxHashKey, hash, txr.Height, hash, txrID)
  179. sqlStmtEvents = sqlStmtEvents.Values(types.TxHeightKey, txr.Height, txr.Height, hash, txrID)
  180. for _, event := range result.Result.Events {
  181. // only index events with a non-empty type
  182. if len(event.Type) == 0 {
  183. continue
  184. }
  185. for _, attr := range event.Attributes {
  186. if len(attr.Key) == 0 {
  187. continue
  188. }
  189. // index if `index: true` is set
  190. compositeTag := fmt.Sprintf("%s.%s", event.Type, string(attr.Key))
  191. // ensure event does not conflict with a reserved prefix key
  192. if compositeTag == types.TxHashKey || compositeTag == types.TxHeightKey {
  193. return fmt.Errorf("event type and attribute key \"%s\" is reserved; please use a different key", compositeTag)
  194. }
  195. if attr.GetIndex() {
  196. sqlStmtEvents = sqlStmtEvents.Values(compositeKey, string(attr.Value), txr.Height, hash, txrID)
  197. }
  198. }
  199. }
  200. // execute sqlStmtEvents db query...
  201. }
  202. func (es *PSQLEventSink) SearchBlockEvents(ctx context.Context, q *query.Query) ([]int64, error) {
  203. sqlStmt = sq.Select("height").Distinct().From("block_events").Where(q.String())
  204. // execute sqlStmt db query and scan into integer rows...
  205. }
  206. func (es *PSQLEventSink) SearchTxEvents(ctx context.Context, q *query.Query) ([]*abci.TxResult, error) {
  207. sqlStmt = sq.Select("tx_result_id").Distinct().From("tx_events").Where(q.String())
  208. // execute sqlStmt db query and scan into integer rows...
  209. // query tx_results records and scan into binary slice rows...
  210. // decode each row into a TxResult...
  211. }
  212. ```
  213. ### Configuration
  214. The current `tx_index.indexer` configuration would be changed to accept a list
  215. of supported `EventSink` types instead of a single value.
  216. Example:
  217. ```toml
  218. [tx_index]
  219. indexer = [
  220. "kv",
  221. "psql"
  222. ]
  223. ```
  224. If the `indexer` list contains the `null` indexer, then no indexers will be used
  225. regardless of what other values may exist.
  226. Additional configuration parameters might be required depending on what event
  227. sinks are supplied to `tx_index.indexer`. The `psql` will require an additional
  228. connection configuration.
  229. ```toml
  230. [tx_index]
  231. indexer = [
  232. "kv",
  233. "psql"
  234. ]
  235. pqsql_conn = "postgresql://<user>:<password>@<host>:<port>/<db>?<opts>"
  236. ```
  237. Any invalid or misconfigured `tx_index` configuration should yield an error as
  238. early as possible.
  239. ## Future Improvements
  240. Although not technically required to maintain feature parity with the current
  241. existing Tendermint indexer, it would be beneficial for operators to have a method
  242. of performing a "re-index". Specifically, Tendermint operators could invoke an
  243. RPC method that allows the Tendermint node to perform a re-indexing of all block
  244. and transaction events between two given heights, H<sub>1</sub> and H<sub>2</sub>,
  245. so long as the block store contains the blocks and transaction results for all
  246. the heights specified in a given range.
  247. ## Consequences
  248. ### Positive
  249. - A more robust and flexible indexing and query engine for indexing and search
  250. block and transaction events.
  251. - The ability to not have to support a custom indexing and query engine beyond
  252. the legacy `kv` type.
  253. - The ability to offload/proxy indexing and querying to the underling sink.
  254. - Scalability and reliability that essentially comes "for free" from the underlying
  255. sink, if it supports it.
  256. ### Negative
  257. - The need to support multiple and potentially a growing set of custom `EventSink`
  258. types.
  259. ### Neutral
  260. ## References
  261. - [Cosmos SDK ADR-038](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-038-state-listening.md)
  262. - [PostgreSQL](https://www.postgresql.org/)
  263. - [SQLite](https://www.sqlite.org/index.html)