github.com/koko1123/flow-go-1@v0.29.6/storage/badger/guarantees.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  // Guarantees implements persistent storage for collection guarantees.
    14  type Guarantees struct {
    15  	db    *badger.DB
    16  	cache *Cache
    17  }
    18  
    19  func NewGuarantees(collector module.CacheMetrics, db *badger.DB, cacheSize uint) *Guarantees {
    20  
    21  	store := func(key interface{}, val interface{}) func(*transaction.Tx) error {
    22  		collID := key.(flow.Identifier)
    23  		guarantee := val.(*flow.CollectionGuarantee)
    24  		return transaction.WithTx(operation.SkipDuplicates(operation.InsertGuarantee(collID, guarantee)))
    25  	}
    26  
    27  	retrieve := func(key interface{}) func(*badger.Txn) (interface{}, error) {
    28  		collID := key.(flow.Identifier)
    29  		var guarantee flow.CollectionGuarantee
    30  		return func(tx *badger.Txn) (interface{}, error) {
    31  			err := operation.RetrieveGuarantee(collID, &guarantee)(tx)
    32  			return &guarantee, err
    33  		}
    34  	}
    35  
    36  	g := &Guarantees{
    37  		db: db,
    38  		cache: newCache(collector, metrics.ResourceGuarantee,
    39  			withLimit(cacheSize),
    40  			withStore(store),
    41  			withRetrieve(retrieve)),
    42  	}
    43  
    44  	return g
    45  }
    46  
    47  func (g *Guarantees) storeTx(guarantee *flow.CollectionGuarantee) func(*transaction.Tx) error {
    48  	return g.cache.PutTx(guarantee.ID(), guarantee)
    49  }
    50  
    51  func (g *Guarantees) retrieveTx(collID flow.Identifier) func(*badger.Txn) (*flow.CollectionGuarantee, error) {
    52  	return func(tx *badger.Txn) (*flow.CollectionGuarantee, error) {
    53  		val, err := g.cache.Get(collID)(tx)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  		return val.(*flow.CollectionGuarantee), nil
    58  	}
    59  }
    60  
    61  func (g *Guarantees) Store(guarantee *flow.CollectionGuarantee) error {
    62  	return operation.RetryOnConflictTx(g.db, transaction.Update, g.storeTx(guarantee))
    63  }
    64  
    65  func (g *Guarantees) ByCollectionID(collID flow.Identifier) (*flow.CollectionGuarantee, error) {
    66  	tx := g.db.NewTransaction(false)
    67  	defer tx.Discard()
    68  	return g.retrieveTx(collID)(tx)
    69  }