-
Notifications
You must be signed in to change notification settings - Fork 672
/
tx_state.go
112 lines (91 loc) · 2.41 KB
/
tx_state.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package avm
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/cache/metercacher"
"github.com/ava-labs/avalanchego/codec"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
)
const (
txCacheSize = 8192
)
var _ TxState = &txState{}
// TxState is a thin wrapper around a database to provide, caching,
// serialization, and de-serialization of transactions.
type TxState interface {
// Tx attempts to load a transaction from storage.
GetTx(txID ids.ID) (*Tx, error)
// PutTx saves the provided transaction to storage.
PutTx(txID ids.ID, tx *Tx) error
// DeleteTx removes the provided transaction from storage.
DeleteTx(txID ids.ID) error
}
type txState struct {
codec codec.Manager
// Caches TxID -> *Tx. If the *Tx is nil, that means the tx is not in
// storage.
txCache cache.Cacher
txDB database.Database
}
func NewTxState(db database.Database, codec codec.Manager) TxState {
return &txState{
codec: codec,
txCache: &cache.LRU{
Size: txCacheSize,
},
txDB: db,
}
}
func NewMeteredTxState(db database.Database, codec codec.Manager, namespace string, metrics prometheus.Registerer) (TxState, error) {
cache, err := metercacher.New(
fmt.Sprintf("%s_tx_cache", namespace),
metrics,
&cache.LRU{Size: txCacheSize},
)
return &txState{
codec: codec,
txCache: cache,
txDB: db,
}, err
}
func (s *txState) GetTx(txID ids.ID) (*Tx, error) {
if txIntf, found := s.txCache.Get(txID); found {
if txIntf == nil {
return nil, database.ErrNotFound
}
return txIntf.(*Tx), nil
}
txBytes, err := s.txDB.Get(txID[:])
if err == database.ErrNotFound {
s.txCache.Put(txID, nil)
return nil, database.ErrNotFound
}
if err != nil {
return nil, err
}
// The key was in the database
tx := &Tx{}
cv, err := s.codec.Unmarshal(txBytes, tx)
if err != nil {
return nil, err
}
unsignedBytes, err := s.codec.Marshal(cv, &tx.UnsignedTx)
if err != nil {
return nil, err
}
tx.Initialize(unsignedBytes, txBytes)
s.txCache.Put(txID, tx)
return tx, nil
}
func (s *txState) PutTx(txID ids.ID, tx *Tx) error {
s.txCache.Put(txID, tx)
return s.txDB.Put(txID[:], tx.Bytes())
}
func (s *txState) DeleteTx(txID ids.ID) error {
s.txCache.Put(txID, nil)
return s.txDB.Delete(txID[:])
}