github.com/onflow/flow-go@v0.33.17/storage/badger/epoch_setups.go (about)

     1  package badger
     2  
     3  import (
     4  	"github.com/dgraph-io/badger/v2"
     5  
     6  	"github.com/onflow/flow-go/model/flow"
     7  	"github.com/onflow/flow-go/module"
     8  	"github.com/onflow/flow-go/module/metrics"
     9  	"github.com/onflow/flow-go/storage/badger/operation"
    10  	"github.com/onflow/flow-go/storage/badger/transaction"
    11  )
    12  
    13  type EpochSetups struct {
    14  	db    *badger.DB
    15  	cache *Cache[flow.Identifier, *flow.EpochSetup]
    16  }
    17  
    18  // NewEpochSetups instantiates a new EpochSetups storage.
    19  func NewEpochSetups(collector module.CacheMetrics, db *badger.DB) *EpochSetups {
    20  
    21  	store := func(id flow.Identifier, setup *flow.EpochSetup) func(*transaction.Tx) error {
    22  		return transaction.WithTx(operation.SkipDuplicates(operation.InsertEpochSetup(id, setup)))
    23  	}
    24  
    25  	retrieve := func(id flow.Identifier) func(*badger.Txn) (*flow.EpochSetup, error) {
    26  		return func(tx *badger.Txn) (*flow.EpochSetup, error) {
    27  			var setup flow.EpochSetup
    28  			err := operation.RetrieveEpochSetup(id, &setup)(tx)
    29  			return &setup, err
    30  		}
    31  	}
    32  
    33  	es := &EpochSetups{
    34  		db: db,
    35  		cache: newCache[flow.Identifier, *flow.EpochSetup](collector, metrics.ResourceEpochSetup,
    36  			withLimit[flow.Identifier, *flow.EpochSetup](4*flow.DefaultTransactionExpiry),
    37  			withStore(store),
    38  			withRetrieve(retrieve)),
    39  	}
    40  
    41  	return es
    42  }
    43  
    44  func (es *EpochSetups) StoreTx(setup *flow.EpochSetup) func(tx *transaction.Tx) error {
    45  	return es.cache.PutTx(setup.ID(), setup)
    46  }
    47  
    48  func (es *EpochSetups) retrieveTx(setupID flow.Identifier) func(tx *badger.Txn) (*flow.EpochSetup, error) {
    49  	return func(tx *badger.Txn) (*flow.EpochSetup, error) {
    50  		val, err := es.cache.Get(setupID)(tx)
    51  		if err != nil {
    52  			return nil, err
    53  		}
    54  		return val, nil
    55  	}
    56  }
    57  
    58  // ByID will return the EpochSetup event by its ID.
    59  // Error returns:
    60  // * storage.ErrNotFound if no EpochSetup with the ID exists
    61  func (es *EpochSetups) ByID(setupID flow.Identifier) (*flow.EpochSetup, error) {
    62  	tx := es.db.NewTransaction(false)
    63  	defer tx.Discard()
    64  	return es.retrieveTx(setupID)(tx)
    65  }