-
Notifications
You must be signed in to change notification settings - Fork 179
/
guarantees.go
69 lines (57 loc) · 2.01 KB
/
guarantees.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
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/badger/operation"
"github.com/onflow/flow-go/storage/badger/transaction"
)
// Guarantees implements persistent storage for collection guarantees.
type Guarantees struct {
db *badger.DB
cache *Cache
}
func NewGuarantees(collector module.CacheMetrics, db *badger.DB, cacheSize uint) *Guarantees {
store := func(key interface{}, val interface{}) func(*transaction.Tx) error {
collID := key.(flow.Identifier)
guarantee := val.(*flow.CollectionGuarantee)
return transaction.WithTx(operation.SkipDuplicates(operation.InsertGuarantee(collID, guarantee)))
}
retrieve := func(key interface{}) func(*badger.Txn) (interface{}, error) {
collID := key.(flow.Identifier)
var guarantee flow.CollectionGuarantee
return func(tx *badger.Txn) (interface{}, error) {
err := operation.RetrieveGuarantee(collID, &guarantee)(tx)
return &guarantee, err
}
}
g := &Guarantees{
db: db,
cache: newCache(collector, metrics.ResourceGuarantee,
withLimit(cacheSize),
withStore(store),
withRetrieve(retrieve)),
}
return g
}
func (g *Guarantees) storeTx(guarantee *flow.CollectionGuarantee) func(*transaction.Tx) error {
return g.cache.PutTx(guarantee.ID(), guarantee)
}
func (g *Guarantees) retrieveTx(collID flow.Identifier) func(*badger.Txn) (*flow.CollectionGuarantee, error) {
return func(tx *badger.Txn) (*flow.CollectionGuarantee, error) {
val, err := g.cache.Get(collID)(tx)
if err != nil {
return nil, err
}
return val.(*flow.CollectionGuarantee), nil
}
}
func (g *Guarantees) Store(guarantee *flow.CollectionGuarantee) error {
return operation.RetryOnConflictTx(g.db, transaction.Update, g.storeTx(guarantee))
}
func (g *Guarantees) ByCollectionID(collID flow.Identifier) (*flow.CollectionGuarantee, error) {
tx := g.db.NewTransaction(false)
defer tx.Discard()
return g.retrieveTx(collID)(tx)
}