github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/storage/badger/cluster_payloads.go (about)

     1  package badger
     2  
     3  import (
     4  	"github.com/dgraph-io/badger/v2"
     5  
     6  	"github.com/onflow/flow-go/model/cluster"
     7  	"github.com/onflow/flow-go/model/flow"
     8  	"github.com/onflow/flow-go/module"
     9  	"github.com/onflow/flow-go/module/metrics"
    10  	"github.com/onflow/flow-go/storage/badger/operation"
    11  	"github.com/onflow/flow-go/storage/badger/procedure"
    12  	"github.com/onflow/flow-go/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[flow.Identifier, *cluster.Payload]
    20  }
    21  
    22  func NewClusterPayloads(cacheMetrics module.CacheMetrics, db *badger.DB) *ClusterPayloads {
    23  
    24  	store := func(blockID flow.Identifier, payload *cluster.Payload) func(*transaction.Tx) error {
    25  		return transaction.WithTx(procedure.InsertClusterPayload(blockID, payload))
    26  	}
    27  
    28  	retrieve := func(blockID flow.Identifier) func(tx *badger.Txn) (*cluster.Payload, error) {
    29  		var payload cluster.Payload
    30  		return func(tx *badger.Txn) (*cluster.Payload, error) {
    31  			err := procedure.RetrieveClusterPayload(blockID, &payload)(tx)
    32  			return &payload, err
    33  		}
    34  	}
    35  
    36  	cp := &ClusterPayloads{
    37  		db: db,
    38  		cache: newCache[flow.Identifier, *cluster.Payload](cacheMetrics, metrics.ResourceClusterPayload,
    39  			withLimit[flow.Identifier, *cluster.Payload](flow.DefaultTransactionExpiry*4),
    40  			withStore(store),
    41  			withRetrieve(retrieve)),
    42  	}
    43  
    44  	return cp
    45  }
    46  
    47  func (cp *ClusterPayloads) storeTx(blockID flow.Identifier, payload *cluster.Payload) func(*transaction.Tx) error {
    48  	return cp.cache.PutTx(blockID, payload)
    49  }
    50  
    51  func (cp *ClusterPayloads) retrieveTx(blockID flow.Identifier) func(*badger.Txn) (*cluster.Payload, error) {
    52  	return func(tx *badger.Txn) (*cluster.Payload, error) {
    53  		val, err := cp.cache.Get(blockID)(tx)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  		return val, nil
    58  	}
    59  }
    60  
    61  func (cp *ClusterPayloads) Store(blockID flow.Identifier, payload *cluster.Payload) error {
    62  	return operation.RetryOnConflictTx(cp.db, transaction.Update, cp.storeTx(blockID, payload))
    63  }
    64  
    65  func (cp *ClusterPayloads) ByBlockID(blockID flow.Identifier) (*cluster.Payload, error) {
    66  	tx := cp.db.NewTransaction(false)
    67  	defer tx.Discard()
    68  	return cp.retrieveTx(blockID)(tx)
    69  }