-
Notifications
You must be signed in to change notification settings - Fork 175
/
commits.go
81 lines (67 loc) · 2.49 KB
/
commits.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
72
73
74
75
76
77
78
79
80
81
package badger
import (
"github.com/dgraph-io/badger/v2"
"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"
"github.com/onflow/flow-go/storage/badger/operation"
"github.com/onflow/flow-go/storage/badger/transaction"
)
type Commits struct {
db *badger.DB
cache *Cache
}
func NewCommits(collector module.CacheMetrics, db *badger.DB) *Commits {
store := func(key interface{}, val interface{}) func(*transaction.Tx) error {
blockID := key.(flow.Identifier)
commit := val.(flow.StateCommitment)
return transaction.WithTx(operation.SkipDuplicates(operation.IndexStateCommitment(blockID, commit)))
}
retrieve := func(key interface{}) func(tx *badger.Txn) (interface{}, error) {
blockID := key.(flow.Identifier)
var commit flow.StateCommitment
return func(tx *badger.Txn) (interface{}, error) {
err := operation.LookupStateCommitment(blockID, &commit)(tx)
return commit, err
}
}
c := &Commits{
db: db,
cache: newCache(collector, metrics.ResourceCommit,
withLimit(1000),
withStore(store),
withRetrieve(retrieve),
),
}
return c
}
func (c *Commits) storeTx(blockID flow.Identifier, commit flow.StateCommitment) func(*transaction.Tx) error {
return c.cache.PutTx(blockID, commit)
}
func (c *Commits) retrieveTx(blockID flow.Identifier) func(tx *badger.Txn) (flow.StateCommitment, error) {
return func(tx *badger.Txn) (flow.StateCommitment, error) {
val, err := c.cache.Get(blockID)(tx)
if err != nil {
return flow.DummyStateCommitment, err
}
return val.(flow.StateCommitment), nil
}
}
func (c *Commits) Store(blockID flow.Identifier, commit flow.StateCommitment) error {
return operation.RetryOnConflictTx(c.db, transaction.Update, c.storeTx(blockID, commit))
}
func (c *Commits) BatchStore(blockID flow.Identifier, commit flow.StateCommitment, batch storage.BatchStorage) error {
// we can't cache while using batches, as it's unknown at this point when, and if
// the batch will be committed. Cache will be populated on read however.
writeBatch := batch.GetWriter()
return operation.BatchIndexStateCommitment(blockID, commit)(writeBatch)
}
func (c *Commits) ByBlockID(blockID flow.Identifier) (flow.StateCommitment, error) {
tx := c.db.NewTransaction(false)
defer tx.Discard()
return c.retrieveTx(blockID)(tx)
}
func (c *Commits) RemoveByBlockID(blockID flow.Identifier) error {
return c.db.Update(operation.SkipNonExist(operation.RemoveStateCommitment(blockID)))
}