github.com/onflow/flow-go@v0.33.17/storage/badger/epoch_statuses.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 EpochStatuses struct {
    14  	db    *badger.DB
    15  	cache *Cache[flow.Identifier, *flow.EpochStatus]
    16  }
    17  
    18  // NewEpochStatuses ...
    19  func NewEpochStatuses(collector module.CacheMetrics, db *badger.DB) *EpochStatuses {
    20  
    21  	store := func(blockID flow.Identifier, status *flow.EpochStatus) func(*transaction.Tx) error {
    22  		return transaction.WithTx(operation.InsertEpochStatus(blockID, status))
    23  	}
    24  
    25  	retrieve := func(blockID flow.Identifier) func(*badger.Txn) (*flow.EpochStatus, error) {
    26  		return func(tx *badger.Txn) (*flow.EpochStatus, error) {
    27  			var status flow.EpochStatus
    28  			err := operation.RetrieveEpochStatus(blockID, &status)(tx)
    29  			return &status, err
    30  		}
    31  	}
    32  
    33  	es := &EpochStatuses{
    34  		db: db,
    35  		cache: newCache[flow.Identifier, *flow.EpochStatus](collector, metrics.ResourceEpochStatus,
    36  			withLimit[flow.Identifier, *flow.EpochStatus](4*flow.DefaultTransactionExpiry),
    37  			withStore(store),
    38  			withRetrieve(retrieve)),
    39  	}
    40  
    41  	return es
    42  }
    43  
    44  func (es *EpochStatuses) StoreTx(blockID flow.Identifier, status *flow.EpochStatus) func(tx *transaction.Tx) error {
    45  	return es.cache.PutTx(blockID, status)
    46  }
    47  
    48  func (es *EpochStatuses) retrieveTx(blockID flow.Identifier) func(tx *badger.Txn) (*flow.EpochStatus, error) {
    49  	return func(tx *badger.Txn) (*flow.EpochStatus, error) {
    50  		val, err := es.cache.Get(blockID)(tx)
    51  		if err != nil {
    52  			return nil, err
    53  		}
    54  		return val, nil
    55  	}
    56  }
    57  
    58  // ByBlockID will return the epoch status for the given block
    59  // Error returns:
    60  // * storage.ErrNotFound if EpochStatus for the block does not exist
    61  func (es *EpochStatuses) ByBlockID(blockID flow.Identifier) (*flow.EpochStatus, error) {
    62  	tx := es.db.NewTransaction(false)
    63  	defer tx.Discard()
    64  	return es.retrieveTx(blockID)(tx)
    65  }