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