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