github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/storage/badger/epoch_setups.go (about) 1 package badger 2 3 import ( 4 "fmt" 5 6 "github.com/dgraph-io/badger/v2" 7 8 "github.com/onflow/flow-go/model/flow" 9 "github.com/onflow/flow-go/module" 10 "github.com/onflow/flow-go/module/metrics" 11 "github.com/onflow/flow-go/storage/badger/operation" 12 "github.com/onflow/flow-go/storage/badger/transaction" 13 ) 14 15 type EpochSetups struct { 16 db *badger.DB 17 cache *Cache[flow.Identifier, *flow.EpochSetup] 18 } 19 20 // NewEpochSetups instantiates a new EpochSetups storage. 21 func NewEpochSetups(collector module.CacheMetrics, db *badger.DB) *EpochSetups { 22 23 store := func(id flow.Identifier, setup *flow.EpochSetup) func(*transaction.Tx) error { 24 return transaction.WithTx(operation.SkipDuplicates(operation.InsertEpochSetup(id, setup))) 25 } 26 27 retrieve := func(id flow.Identifier) func(*badger.Txn) (*flow.EpochSetup, error) { 28 return func(tx *badger.Txn) (*flow.EpochSetup, error) { 29 var setup flow.EpochSetup 30 err := operation.RetrieveEpochSetup(id, &setup)(tx) 31 return &setup, err 32 } 33 } 34 35 es := &EpochSetups{ 36 db: db, 37 cache: newCache[flow.Identifier, *flow.EpochSetup](collector, metrics.ResourceEpochSetup, 38 withLimit[flow.Identifier, *flow.EpochSetup](4*flow.DefaultTransactionExpiry), 39 withStore(store), 40 withRetrieve(retrieve)), 41 } 42 43 return es 44 } 45 46 func (es *EpochSetups) StoreTx(setup *flow.EpochSetup) func(tx *transaction.Tx) error { 47 return es.cache.PutTx(setup.ID(), setup) 48 } 49 50 func (es *EpochSetups) retrieveTx(setupID flow.Identifier) func(tx *badger.Txn) (*flow.EpochSetup, error) { 51 return func(tx *badger.Txn) (*flow.EpochSetup, error) { 52 val, err := es.cache.Get(setupID)(tx) 53 if err != nil { 54 return nil, fmt.Errorf("could not retrieve EpochSetup event with id %x: %w", setupID, err) 55 } 56 return val, nil 57 } 58 } 59 60 // ByID will return the EpochSetup event by its ID. 61 // Error returns: 62 // * storage.ErrNotFound if no EpochSetup with the ID exists 63 func (es *EpochSetups) ByID(setupID flow.Identifier) (*flow.EpochSetup, error) { 64 tx := es.db.NewTransaction(false) 65 defer tx.Discard() 66 return es.retrieveTx(setupID)(tx) 67 }