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.

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