github.com/koko1123/flow-go-1@v0.29.6/storage/badger/epoch_setups.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  type EpochSetups struct {
    14  	db    *badger.DB
    15  	cache *Cache
    16  }
    17  
    18  // NewEpochSetups instantiates a new EpochSetups storage.
    19  func NewEpochSetups(collector module.CacheMetrics, db *badger.DB) *EpochSetups {
    20  
    21  	store := func(key interface{}, val interface{}) func(*transaction.Tx) error {
    22  		id := key.(flow.Identifier)
    23  		setup := val.(*flow.EpochSetup)
    24  		return transaction.WithTx(operation.SkipDuplicates(operation.InsertEpochSetup(id, setup)))
    25  	}
    26  
    27  	retrieve := func(key interface{}) func(*badger.Txn) (interface{}, error) {
    28  		id := key.(flow.Identifier)
    29  		var setup flow.EpochSetup
    30  		return func(tx *badger.Txn) (interface{}, error) {
    31  			err := operation.RetrieveEpochSetup(id, &setup)(tx)
    32  			return &setup, err
    33  		}
    34  	}
    35  
    36  	es := &EpochSetups{
    37  		db: db,
    38  		cache: newCache(collector, metrics.ResourceEpochSetup,
    39  			withLimit(4*flow.DefaultTransactionExpiry),
    40  			withStore(store),
    41  			withRetrieve(retrieve)),
    42  	}
    43  
    44  	return es
    45  }
    46  
    47  func (es *EpochSetups) StoreTx(setup *flow.EpochSetup) func(tx *transaction.Tx) error {
    48  	return es.cache.PutTx(setup.ID(), setup)
    49  }
    50  
    51  func (es *EpochSetups) retrieveTx(setupID flow.Identifier) func(tx *badger.Txn) (*flow.EpochSetup, error) {
    52  	return func(tx *badger.Txn) (*flow.EpochSetup, error) {
    53  		val, err := es.cache.Get(setupID)(tx)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  		return val.(*flow.EpochSetup), nil
    58  	}
    59  }
    60  
    61  // ByID will return the EpochSetup event by its ID.
    62  // Error returns:
    63  // * storage.ErrNotFound if no EpochSetup with the ID exists
    64  func (es *EpochSetups) ByID(setupID flow.Identifier) (*flow.EpochSetup, error) {
    65  	tx := es.db.NewTransaction(false)
    66  	defer tx.Discard()
    67  	return es.retrieveTx(setupID)(tx)
    68  }