github.com/onflow/flow-go@v0.33.17/storage/badger/epoch_commits.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 EpochCommits struct { 14 db *badger.DB 15 cache *Cache[flow.Identifier, *flow.EpochCommit] 16 } 17 18 func NewEpochCommits(collector module.CacheMetrics, db *badger.DB) *EpochCommits { 19 20 store := func(id flow.Identifier, commit *flow.EpochCommit) func(*transaction.Tx) error { 21 return transaction.WithTx(operation.SkipDuplicates(operation.InsertEpochCommit(id, commit))) 22 } 23 24 retrieve := func(id flow.Identifier) func(*badger.Txn) (*flow.EpochCommit, error) { 25 return func(tx *badger.Txn) (*flow.EpochCommit, error) { 26 var commit flow.EpochCommit 27 err := operation.RetrieveEpochCommit(id, &commit)(tx) 28 return &commit, err 29 } 30 } 31 32 ec := &EpochCommits{ 33 db: db, 34 cache: newCache[flow.Identifier, *flow.EpochCommit](collector, metrics.ResourceEpochCommit, 35 withLimit[flow.Identifier, *flow.EpochCommit](4*flow.DefaultTransactionExpiry), 36 withStore(store), 37 withRetrieve(retrieve)), 38 } 39 40 return ec 41 } 42 43 func (ec *EpochCommits) StoreTx(commit *flow.EpochCommit) func(*transaction.Tx) error { 44 return ec.cache.PutTx(commit.ID(), commit) 45 } 46 47 func (ec *EpochCommits) retrieveTx(commitID flow.Identifier) func(tx *badger.Txn) (*flow.EpochCommit, error) { 48 return func(tx *badger.Txn) (*flow.EpochCommit, error) { 49 val, err := ec.cache.Get(commitID)(tx) 50 if err != nil { 51 return nil, err 52 } 53 return val, nil 54 } 55 } 56 57 // TODO: can we remove this method? Its not contained in the interface. 58 func (ec *EpochCommits) Store(commit *flow.EpochCommit) error { 59 return operation.RetryOnConflictTx(ec.db, transaction.Update, ec.StoreTx(commit)) 60 } 61 62 // ByID will return the EpochCommit event by its ID. 63 // Error returns: 64 // * storage.ErrNotFound if no EpochCommit with the ID exists 65 func (ec *EpochCommits) ByID(commitID flow.Identifier) (*flow.EpochCommit, error) { 66 tx := ec.db.NewTransaction(false) 67 defer tx.Discard() 68 return ec.retrieveTx(commitID)(tx) 69 }