-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger_cache.go
86 lines (74 loc) · 2.03 KB
/
badger_cache.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
82
83
84
85
86
package storage
import (
"github.com/MixinNetwork/mixin/common"
"github.com/MixinNetwork/mixin/config"
"github.com/MixinNetwork/mixin/crypto"
"github.com/dgraph-io/badger"
)
const (
cachePrefixTransactionCache = "TRANSACTIONCACHE"
)
func (s *BadgerStore) CacheListTransactions(hook func(tx *common.VersionedTransaction) error) error {
snapTxn := s.snapshotsDB.NewTransaction(false)
defer snapTxn.Discard()
txn := s.cacheDB.NewTransaction(false)
defer txn.Discard()
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
prefix := []byte(cachePrefixTransactionCache)
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
key := it.Item().Key()[len(prefix):]
key = append([]byte(graphPrefixFinalization), key...)
_, err := snapTxn.Get(key)
if err == nil {
continue
} else if err != badger.ErrKeyNotFound {
return err
}
v, err := it.Item().ValueCopy(nil)
if err != nil {
return err
}
ver, err := common.DecompressUnmarshalVersionedTransaction(v)
if err != nil {
return err
}
err = hook(ver)
if err != nil {
return err
}
}
return nil
}
func (s *BadgerStore) CachePutTransaction(tx *common.VersionedTransaction) error {
txn := s.cacheDB.NewTransaction(true)
defer txn.Discard()
key := cacheTransactionCacheKey(tx.PayloadHash())
val := tx.CompressMarshal()
err := txn.SetWithTTL(key, val, config.CacheTTL)
if err != nil {
return err
}
return txn.Commit()
}
func (s *BadgerStore) CacheGetTransaction(hash crypto.Hash) (*common.VersionedTransaction, error) {
txn := s.cacheDB.NewTransaction(false)
defer txn.Discard()
key := cacheTransactionCacheKey(hash)
item, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
return nil, nil
} else if err != nil {
return nil, err
}
val, err := item.ValueCopy(nil)
if err != nil {
return nil, err
}
return common.DecompressUnmarshalVersionedTransaction(val)
}
func cacheTransactionCacheKey(hash crypto.Hash) []byte {
return append([]byte(cachePrefixTransactionCache), hash[:]...)
}