github.com/koko1123/flow-go-1@v0.29.6/storage/badger/index.go (about) 1 // (c) 2019 Dapper Labs - ALL RIGHTS RESERVED 2 3 package badger 4 5 import ( 6 "github.com/dgraph-io/badger/v3" 7 8 "github.com/koko1123/flow-go-1/model/flow" 9 "github.com/koko1123/flow-go-1/module" 10 "github.com/koko1123/flow-go-1/module/metrics" 11 "github.com/koko1123/flow-go-1/storage/badger/operation" 12 "github.com/koko1123/flow-go-1/storage/badger/procedure" 13 "github.com/koko1123/flow-go-1/storage/badger/transaction" 14 ) 15 16 // Index implements a simple read-only payload storage around a badger DB. 17 type Index struct { 18 db *badger.DB 19 cache *Cache 20 } 21 22 func NewIndex(collector module.CacheMetrics, db *badger.DB) *Index { 23 24 store := func(key interface{}, val interface{}) func(*transaction.Tx) error { 25 blockID := key.(flow.Identifier) 26 index := val.(*flow.Index) 27 return transaction.WithTx(procedure.InsertIndex(blockID, index)) 28 } 29 30 retrieve := func(key interface{}) func(tx *badger.Txn) (interface{}, error) { 31 blockID := key.(flow.Identifier) 32 var index flow.Index 33 return func(tx *badger.Txn) (interface{}, error) { 34 err := procedure.RetrieveIndex(blockID, &index)(tx) 35 return &index, err 36 } 37 } 38 39 p := &Index{ 40 db: db, 41 cache: newCache(collector, metrics.ResourceIndex, 42 withLimit(flow.DefaultTransactionExpiry+100), 43 withStore(store), 44 withRetrieve(retrieve)), 45 } 46 47 return p 48 } 49 50 func (i *Index) storeTx(blockID flow.Identifier, index *flow.Index) func(*transaction.Tx) error { 51 return i.cache.PutTx(blockID, index) 52 } 53 54 func (i *Index) retrieveTx(blockID flow.Identifier) func(*badger.Txn) (*flow.Index, error) { 55 return func(tx *badger.Txn) (*flow.Index, error) { 56 val, err := i.cache.Get(blockID)(tx) 57 if err != nil { 58 return nil, err 59 } 60 return val.(*flow.Index), nil 61 } 62 } 63 64 func (i *Index) Store(blockID flow.Identifier, index *flow.Index) error { 65 return operation.RetryOnConflictTx(i.db, transaction.Update, i.storeTx(blockID, index)) 66 } 67 68 func (i *Index) ByBlockID(blockID flow.Identifier) (*flow.Index, error) { 69 tx := i.db.NewTransaction(false) 70 defer tx.Discard() 71 return i.retrieveTx(blockID)(tx) 72 }