-
Notifications
You must be signed in to change notification settings - Fork 175
/
seals.go
81 lines (66 loc) · 2.07 KB
/
seals.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
// (c) 2019 Dapper Labs - ALL RIGHTS RESERVED
package badger
import (
"fmt"
"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"
)
type Seals struct {
db *badger.DB
cache *Cache
}
func NewSeals(collector module.CacheMetrics, db *badger.DB) *Seals {
store := func(key interface{}, val interface{}) func(*transaction.Tx) error {
sealID := key.(flow.Identifier)
seal := val.(*flow.Seal)
return transaction.WithTx(operation.SkipDuplicates(operation.InsertSeal(sealID, seal)))
}
retrieve := func(key interface{}) func(*badger.Txn) (interface{}, error) {
sealID := key.(flow.Identifier)
var seal flow.Seal
return func(tx *badger.Txn) (interface{}, error) {
err := operation.RetrieveSeal(sealID, &seal)(tx)
return &seal, err
}
}
s := &Seals{
db: db,
cache: newCache(collector, metrics.ResourceSeal,
withLimit(flow.DefaultTransactionExpiry+100),
withStore(store),
withRetrieve(retrieve)),
}
return s
}
func (s *Seals) storeTx(seal *flow.Seal) func(*transaction.Tx) error {
return s.cache.PutTx(seal.ID(), seal)
}
func (s *Seals) retrieveTx(sealID flow.Identifier) func(*badger.Txn) (*flow.Seal, error) {
return func(tx *badger.Txn) (*flow.Seal, error) {
val, err := s.cache.Get(sealID)(tx)
if err != nil {
return nil, err
}
return val.(*flow.Seal), err
}
}
func (s *Seals) Store(seal *flow.Seal) error {
return operation.RetryOnConflictTx(s.db, transaction.Update, s.storeTx(seal))
}
func (s *Seals) ByID(sealID flow.Identifier) (*flow.Seal, error) {
tx := s.db.NewTransaction(false)
defer tx.Discard()
return s.retrieveTx(sealID)(tx)
}
func (s *Seals) ByBlockID(blockID flow.Identifier) (*flow.Seal, error) {
var sealID flow.Identifier
err := s.db.View(operation.LookupBlockSeal(blockID, &sealID))
if err != nil {
return nil, fmt.Errorf("failed to retrieve seal for fork with head %x: %w", blockID, err)
}
return s.ByID(sealID)
}