github.com/koko1123/flow-go-1@v0.29.6/storage/badger/cluster_payloads.go (about) 1 package badger 2 3 import ( 4 "github.com/dgraph-io/badger/v3" 5 6 "github.com/koko1123/flow-go-1/model/cluster" 7 "github.com/koko1123/flow-go-1/model/flow" 8 "github.com/koko1123/flow-go-1/module" 9 "github.com/koko1123/flow-go-1/module/metrics" 10 "github.com/koko1123/flow-go-1/storage/badger/operation" 11 "github.com/koko1123/flow-go-1/storage/badger/procedure" 12 "github.com/koko1123/flow-go-1/storage/badger/transaction" 13 ) 14 15 // ClusterPayloads implements storage of block payloads for collection node 16 // cluster consensus. 17 type ClusterPayloads struct { 18 db *badger.DB 19 cache *Cache 20 } 21 22 func NewClusterPayloads(cacheMetrics module.CacheMetrics, db *badger.DB) *ClusterPayloads { 23 24 store := func(key interface{}, val interface{}) func(*transaction.Tx) error { 25 blockID := key.(flow.Identifier) 26 payload := val.(*cluster.Payload) 27 return transaction.WithTx(procedure.InsertClusterPayload(blockID, payload)) 28 } 29 30 retrieve := func(key interface{}) func(tx *badger.Txn) (interface{}, error) { 31 blockID := key.(flow.Identifier) 32 var payload cluster.Payload 33 return func(tx *badger.Txn) (interface{}, error) { 34 err := procedure.RetrieveClusterPayload(blockID, &payload)(tx) 35 return &payload, err 36 } 37 } 38 39 cp := &ClusterPayloads{ 40 db: db, 41 cache: newCache(cacheMetrics, metrics.ResourceClusterPayload, 42 withLimit(flow.DefaultTransactionExpiry*4), 43 withStore(store), 44 withRetrieve(retrieve)), 45 } 46 47 return cp 48 } 49 50 func (cp *ClusterPayloads) storeTx(blockID flow.Identifier, payload *cluster.Payload) func(*transaction.Tx) error { 51 return cp.cache.PutTx(blockID, payload) 52 } 53 func (cp *ClusterPayloads) retrieveTx(blockID flow.Identifier) func(*badger.Txn) (*cluster.Payload, error) { 54 return func(tx *badger.Txn) (*cluster.Payload, error) { 55 val, err := cp.cache.Get(blockID)(tx) 56 if err != nil { 57 return nil, err 58 } 59 return val.(*cluster.Payload), nil 60 } 61 } 62 63 func (cp *ClusterPayloads) Store(blockID flow.Identifier, payload *cluster.Payload) error { 64 return operation.RetryOnConflictTx(cp.db, transaction.Update, cp.storeTx(blockID, payload)) 65 } 66 67 func (cp *ClusterPayloads) ByBlockID(blockID flow.Identifier) (*cluster.Payload, error) { 68 tx := cp.db.NewTransaction(false) 69 defer tx.Discard() 70 return cp.retrieveTx(blockID)(tx) 71 }