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