github.com/KYVENetwork/cometbft/v38@v38.0.3/state/indexer/sink/psql/psql.go (about)

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