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.

346 lines
10 KiB

  1. package psql
  2. import (
  3. "context"
  4. "database/sql"
  5. "flag"
  6. "fmt"
  7. "log"
  8. "os"
  9. "os/signal"
  10. "testing"
  11. "time"
  12. "github.com/adlio/schema"
  13. "github.com/gogo/protobuf/proto"
  14. "github.com/ory/dockertest"
  15. "github.com/ory/dockertest/docker"
  16. "github.com/stretchr/testify/assert"
  17. "github.com/stretchr/testify/require"
  18. abci "github.com/tendermint/tendermint/abci/types"
  19. "github.com/tendermint/tendermint/internal/state/indexer"
  20. "github.com/tendermint/tendermint/types"
  21. // Register the Postgres database driver.
  22. _ "github.com/lib/pq"
  23. )
  24. // Verify that the type satisfies the EventSink interface.
  25. var _ indexer.EventSink = (*EventSink)(nil)
  26. var (
  27. doPauseAtExit = flag.Bool("pause-at-exit", false,
  28. "If true, pause the test until interrupted at shutdown, to allow debugging")
  29. // A hook that test cases can call to obtain the shared database instance
  30. // used for testing the sink. This is initialized in TestMain (see below).
  31. testDB func() *sql.DB
  32. )
  33. const (
  34. user = "postgres"
  35. password = "secret"
  36. port = "5432"
  37. dsn = "postgres://%s:%s@localhost:%s/%s?sslmode=disable"
  38. dbName = "postgres"
  39. chainID = "test-chainID"
  40. viewBlockEvents = "block_events"
  41. viewTxEvents = "tx_events"
  42. )
  43. func TestMain(m *testing.M) {
  44. flag.Parse()
  45. // Set up docker and start a container running PostgreSQL.
  46. pool, err := dockertest.NewPool(os.Getenv("DOCKER_URL"))
  47. if err != nil {
  48. log.Fatalf("Creating docker pool: %v", err)
  49. }
  50. resource, err := pool.RunWithOptions(&dockertest.RunOptions{
  51. Repository: "postgres",
  52. Tag: "13",
  53. Env: []string{
  54. "POSTGRES_USER=" + user,
  55. "POSTGRES_PASSWORD=" + password,
  56. "POSTGRES_DB=" + dbName,
  57. "listen_addresses = '*'",
  58. },
  59. ExposedPorts: []string{port},
  60. }, func(config *docker.HostConfig) {
  61. // set AutoRemove to true so that stopped container goes away by itself
  62. config.AutoRemove = true
  63. config.RestartPolicy = docker.RestartPolicy{
  64. Name: "no",
  65. }
  66. })
  67. if err != nil {
  68. log.Fatalf("Starting docker pool: %v", err)
  69. }
  70. if *doPauseAtExit {
  71. log.Print("Pause at exit is enabled, containers will not expire")
  72. } else {
  73. const expireSeconds = 60
  74. _ = resource.Expire(expireSeconds)
  75. log.Printf("Container expiration set to %d seconds", expireSeconds)
  76. }
  77. // Connect to the database, clear any leftover data, and install the
  78. // indexing schema.
  79. conn := fmt.Sprintf(dsn, user, password, resource.GetPort(port+"/tcp"), dbName)
  80. var db *sql.DB
  81. if err := pool.Retry(func() error {
  82. sink, err := NewEventSink(conn, chainID)
  83. if err != nil {
  84. return err
  85. }
  86. db = sink.DB() // set global for test use
  87. return db.Ping()
  88. }); err != nil {
  89. log.Fatalf("Connecting to database: %v", err)
  90. }
  91. if err := resetDatabase(db); err != nil {
  92. log.Fatalf("Flushing database: %v", err)
  93. }
  94. sm, err := readSchema()
  95. if err != nil {
  96. log.Fatalf("Reading schema: %v", err)
  97. } else if err := schema.NewMigrator().Apply(db, sm); err != nil {
  98. log.Fatalf("Applying schema: %v", err)
  99. }
  100. // Set up the hook for tests to get the shared database handle.
  101. testDB = func() *sql.DB { return db }
  102. // Run the selected test cases.
  103. code := m.Run()
  104. // Clean up and shut down the database container.
  105. if *doPauseAtExit {
  106. log.Print("Testing complete, pausing for inspection. Send SIGINT to resume teardown")
  107. waitForInterrupt()
  108. log.Print("(resuming)")
  109. }
  110. log.Print("Shutting down database")
  111. if err := pool.Purge(resource); err != nil {
  112. log.Printf("WARNING: Purging pool failed: %v", err)
  113. }
  114. if err := db.Close(); err != nil {
  115. log.Printf("WARNING: Closing database failed: %v", err)
  116. }
  117. os.Exit(code)
  118. }
  119. func TestType(t *testing.T) {
  120. psqlSink := &EventSink{store: testDB(), chainID: chainID}
  121. assert.Equal(t, indexer.PSQL, psqlSink.Type())
  122. }
  123. func TestIndexing(t *testing.T) {
  124. ctx, cancel := context.WithCancel(context.Background())
  125. defer cancel()
  126. t.Run("IndexBlockEvents", func(t *testing.T) {
  127. indexer := &EventSink{store: testDB(), chainID: chainID}
  128. require.NoError(t, indexer.IndexBlockEvents(newTestBlockHeader()))
  129. verifyBlock(t, 1)
  130. verifyBlock(t, 2)
  131. verifyNotImplemented(t, "hasBlock", func() (bool, error) { return indexer.HasBlock(1) })
  132. verifyNotImplemented(t, "hasBlock", func() (bool, error) { return indexer.HasBlock(2) })
  133. verifyNotImplemented(t, "block search", func() (bool, error) {
  134. v, err := indexer.SearchBlockEvents(ctx, nil)
  135. return v != nil, err
  136. })
  137. require.NoError(t, verifyTimeStamp(tableBlocks))
  138. // Attempting to reindex the same events should gracefully succeed.
  139. require.NoError(t, indexer.IndexBlockEvents(newTestBlockHeader()))
  140. })
  141. t.Run("IndexTxEvents", func(t *testing.T) {
  142. indexer := &EventSink{store: testDB(), chainID: chainID}
  143. txResult := txResultWithEvents([]abci.Event{
  144. makeIndexedEvent("account.number", "1"),
  145. makeIndexedEvent("account.owner", "Ivan"),
  146. makeIndexedEvent("account.owner", "Yulieta"),
  147. {Type: "", Attributes: []abci.EventAttribute{{Key: "not_allowed", Value: "Vlad", Index: true}}},
  148. })
  149. require.NoError(t, indexer.IndexTxEvents([]*abci.TxResult{txResult}))
  150. txr, err := loadTxResult(types.Tx(txResult.Tx).Hash())
  151. require.NoError(t, err)
  152. assert.Equal(t, txResult, txr)
  153. require.NoError(t, verifyTimeStamp(tableTxResults))
  154. require.NoError(t, verifyTimeStamp(viewTxEvents))
  155. verifyNotImplemented(t, "getTxByHash", func() (bool, error) {
  156. txr, err := indexer.GetTxByHash(types.Tx(txResult.Tx).Hash())
  157. return txr != nil, err
  158. })
  159. verifyNotImplemented(t, "tx search", func() (bool, error) {
  160. txr, err := indexer.SearchTxEvents(ctx, nil)
  161. return txr != nil, err
  162. })
  163. // try to insert the duplicate tx events.
  164. err = indexer.IndexTxEvents([]*abci.TxResult{txResult})
  165. require.NoError(t, err)
  166. })
  167. }
  168. func TestStop(t *testing.T) {
  169. indexer := &EventSink{store: testDB()}
  170. require.NoError(t, indexer.Stop())
  171. }
  172. // newTestBlockHeader constructs a fresh copy of a block header containing
  173. // known test values to exercise the indexer.
  174. func newTestBlockHeader() types.EventDataNewBlockHeader {
  175. return types.EventDataNewBlockHeader{
  176. Header: types.Header{Height: 1},
  177. ResultBeginBlock: abci.ResponseBeginBlock{
  178. Events: []abci.Event{
  179. makeIndexedEvent("begin_event.proposer", "FCAA001"),
  180. makeIndexedEvent("thingy.whatzit", "O.O"),
  181. },
  182. },
  183. ResultEndBlock: abci.ResponseEndBlock{
  184. Events: []abci.Event{
  185. makeIndexedEvent("end_event.foo", "100"),
  186. makeIndexedEvent("thingy.whatzit", "-.O"),
  187. },
  188. },
  189. }
  190. }
  191. // readSchema loads the indexing database schema file
  192. func readSchema() ([]*schema.Migration, error) {
  193. const filename = "schema.sql"
  194. contents, err := os.ReadFile(filename)
  195. if err != nil {
  196. return nil, fmt.Errorf("failed to read sql file from '%s': %w", filename, err)
  197. }
  198. return []*schema.Migration{{
  199. ID: time.Now().Local().String() + " db schema",
  200. Script: string(contents),
  201. }}, nil
  202. }
  203. // resetDB drops all the data from the test database.
  204. func resetDatabase(db *sql.DB) error {
  205. _, err := db.Exec(`DROP TABLE IF EXISTS blocks,tx_results,events,attributes CASCADE;`)
  206. if err != nil {
  207. return fmt.Errorf("dropping tables: %v", err)
  208. }
  209. _, err = db.Exec(`DROP VIEW IF EXISTS event_attributes,block_events,tx_events CASCADE;`)
  210. if err != nil {
  211. return fmt.Errorf("dropping views: %v", err)
  212. }
  213. return nil
  214. }
  215. // txResultWithEvents constructs a fresh transaction result with fixed values
  216. // for testing, that includes the specified events.
  217. func txResultWithEvents(events []abci.Event) *abci.TxResult {
  218. return &abci.TxResult{
  219. Height: 1,
  220. Index: 0,
  221. Tx: types.Tx("HELLO WORLD"),
  222. Result: abci.ResponseDeliverTx{
  223. Data: []byte{0},
  224. Code: abci.CodeTypeOK,
  225. Log: "",
  226. Events: events,
  227. },
  228. }
  229. }
  230. func loadTxResult(hash []byte) (*abci.TxResult, error) {
  231. hashString := fmt.Sprintf("%X", hash)
  232. var resultData []byte
  233. if err := testDB().QueryRow(`
  234. SELECT tx_result FROM `+tableTxResults+` WHERE tx_hash = $1;
  235. `, hashString).Scan(&resultData); err != nil {
  236. return nil, fmt.Errorf("lookup transaction for hash %q failed: %v", hashString, err)
  237. }
  238. txr := new(abci.TxResult)
  239. if err := proto.Unmarshal(resultData, txr); err != nil {
  240. return nil, fmt.Errorf("unmarshaling txr: %v", err)
  241. }
  242. return txr, nil
  243. }
  244. func verifyTimeStamp(tableName string) error {
  245. return testDB().QueryRow(fmt.Sprintf(`
  246. SELECT DISTINCT %[1]s.created_at
  247. FROM %[1]s
  248. WHERE %[1]s.created_at >= $1;
  249. `, tableName), time.Now().Add(-2*time.Second)).Err()
  250. }
  251. func verifyBlock(t *testing.T, height int64) {
  252. // Check that the blocks table contains an entry for this height.
  253. if err := testDB().QueryRow(`
  254. SELECT height FROM `+tableBlocks+` WHERE height = $1;
  255. `, height).Err(); err == sql.ErrNoRows {
  256. t.Errorf("No block found for height=%d", height)
  257. } else if err != nil {
  258. t.Fatalf("Database query failed: %v", err)
  259. }
  260. // Verify the presence of begin_block and end_block events.
  261. if err := testDB().QueryRow(`
  262. SELECT type, height, chain_id FROM `+viewBlockEvents+`
  263. WHERE height = $1 AND type = $2 AND chain_id = $3;
  264. `, height, types.EventTypeBeginBlock, chainID).Err(); err == sql.ErrNoRows {
  265. t.Errorf("No %q event found for height=%d", types.EventTypeBeginBlock, height)
  266. } else if err != nil {
  267. t.Fatalf("Database query failed: %v", err)
  268. }
  269. if err := testDB().QueryRow(`
  270. SELECT type, height, chain_id FROM `+viewBlockEvents+`
  271. WHERE height = $1 AND type = $2 AND chain_id = $3;
  272. `, height, types.EventTypeEndBlock, chainID).Err(); err == sql.ErrNoRows {
  273. t.Errorf("No %q event found for height=%d", types.EventTypeEndBlock, height)
  274. } else if err != nil {
  275. t.Fatalf("Database query failed: %v", err)
  276. }
  277. }
  278. // verifyNotImplemented calls f and verifies that it returns both a
  279. // false-valued flag and a non-nil error whose string matching the expected
  280. // "not supported" message with label prefixed.
  281. func verifyNotImplemented(t *testing.T, label string, f func() (bool, error)) {
  282. t.Helper()
  283. t.Logf("Verifying that %q reports it is not implemented", label)
  284. want := label + " is not supported via the postgres event sink"
  285. ok, err := f()
  286. assert.False(t, ok)
  287. require.NotNil(t, err)
  288. assert.Equal(t, want, err.Error())
  289. }
  290. // waitForInterrupt blocks until a SIGINT is received by the process.
  291. func waitForInterrupt() {
  292. ch := make(chan os.Signal, 1)
  293. signal.Notify(ch, os.Interrupt)
  294. <-ch
  295. }