github.com/koko1123/flow-go-1@v0.29.6/storage/badger/transactions.go (about)

     1  package badger
     2  
     3  import (
     4  	"github.com/dgraph-io/badger/v3"
     5  
     6  	"github.com/koko1123/flow-go-1/model/flow"
     7  	"github.com/koko1123/flow-go-1/module"
     8  	"github.com/koko1123/flow-go-1/module/metrics"
     9  	"github.com/koko1123/flow-go-1/storage/badger/operation"
    10  	"github.com/koko1123/flow-go-1/storage/badger/transaction"
    11  )
    12  
    13  // Transactions ...
    14  type Transactions struct {
    15  	db    *badger.DB
    16  	cache *Cache
    17  }
    18  
    19  // NewTransactions ...
    20  func NewTransactions(cacheMetrics module.CacheMetrics, db *badger.DB) *Transactions {
    21  	store := func(key interface{}, val interface{}) func(*transaction.Tx) error {
    22  		txID := key.(flow.Identifier)
    23  		flowTx := val.(*flow.TransactionBody)
    24  		return transaction.WithTx(operation.SkipDuplicates(operation.InsertTransaction(txID, flowTx)))
    25  	}
    26  
    27  	retrieve := func(key interface{}) func(tx *badger.Txn) (interface{}, error) {
    28  		txID := key.(flow.Identifier)
    29  		var flowTx flow.TransactionBody
    30  		return func(tx *badger.Txn) (interface{}, error) {
    31  			err := operation.RetrieveTransaction(txID, &flowTx)(tx)
    32  			return &flowTx, err
    33  		}
    34  	}
    35  
    36  	t := &Transactions{
    37  		db: db,
    38  		cache: newCache(cacheMetrics, metrics.ResourceTransaction,
    39  			withLimit(flow.DefaultTransactionExpiry+100),
    40  			withStore(store),
    41  			withRetrieve(retrieve)),
    42  	}
    43  
    44  	return t
    45  }
    46  
    47  // Store ...
    48  func (t *Transactions) Store(flowTx *flow.TransactionBody) error {
    49  	return operation.RetryOnConflictTx(t.db, transaction.Update, t.storeTx(flowTx))
    50  }
    51  
    52  // ByID ...
    53  func (t *Transactions) ByID(txID flow.Identifier) (*flow.TransactionBody, error) {
    54  	tx := t.db.NewTransaction(false)
    55  	defer tx.Discard()
    56  	return t.retrieveTx(txID)(tx)
    57  }
    58  
    59  func (t *Transactions) storeTx(flowTx *flow.TransactionBody) func(*transaction.Tx) error {
    60  	return t.cache.PutTx(flowTx.ID(), flowTx)
    61  }
    62  
    63  func (t *Transactions) retrieveTx(txID flow.Identifier) func(*badger.Txn) (*flow.TransactionBody, error) {
    64  	return func(tx *badger.Txn) (*flow.TransactionBody, error) {
    65  		val, err := t.cache.Get(txID)(tx)
    66  		if err != nil {
    67  			return nil, err
    68  		}
    69  		return val.(*flow.TransactionBody), err
    70  	}
    71  }