-
Notifications
You must be signed in to change notification settings - Fork 338
/
store.go
329 lines (261 loc) · 8.44 KB
/
store.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package batchstore
import (
"encoding/hex"
"errors"
"fmt"
"math/big"
"sync"
"time"
"github.com/ethersphere/bee/pkg/logging"
"github.com/ethersphere/bee/pkg/postage"
"github.com/ethersphere/bee/pkg/storage"
)
const (
batchKeyPrefix = "batchstore_batch_"
valueKeyPrefix = "batchstore_value_"
chainStateKey = "batchstore_chainstate"
reserveStateKey = "batchstore_reservestate"
)
// ErrNotFound signals that the element was not found.
var ErrNotFound = errors.New("batchstore: not found")
type evictFn func(batchID []byte) error
// store implements postage.Storer
type store struct {
mtx sync.Mutex
store storage.StateStorer // State store backend to persist batches.
cs *postage.ChainState // the chain state
rs *reserveState // the reserve state
evictFn evictFn // evict function
metrics metrics // metrics
logger logging.Logger
radiusSetter postage.RadiusSetter // setter for radius notifications
}
// New constructs a new postage batch store.
// It initialises both chain state and reserve state from the persistent state store.
func New(st storage.StateStorer, ev evictFn, logger logging.Logger) (postage.Storer, error) {
cs := &postage.ChainState{}
err := st.Get(chainStateKey, cs)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
return nil, err
}
cs = &postage.ChainState{
Block: 0,
TotalAmount: big.NewInt(0),
CurrentPrice: big.NewInt(0),
}
}
rs := &reserveState{}
err = st.Get(reserveStateKey, rs)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
return nil, err
}
rs = &reserveState{
Radius: 0,
StorageRadius: 0,
}
}
s := &store{
store: st,
cs: cs,
rs: rs,
evictFn: ev,
metrics: newMetrics(),
logger: logger,
}
return s, nil
}
func (s *store) GetReserveState() *postage.ReserveState {
s.mtx.Lock()
defer s.mtx.Unlock()
return &postage.ReserveState{
Radius: s.rs.Radius,
StorageRadius: s.rs.StorageRadius,
}
}
func (s *store) GetChainState() *postage.ChainState {
return s.cs
}
// Get returns a batch from the batchstore with the given ID.
func (s *store) Get(id []byte) (*postage.Batch, error) {
defer func(t time.Time) {
s.metrics.GetDuration.WithLabelValues("true").Observe(time.Since(t).Seconds())
}(time.Now())
s.mtx.Lock()
defer s.mtx.Unlock()
defer func(t time.Time) {
s.metrics.GetDuration.WithLabelValues("false").Observe(time.Since(t).Seconds())
}(time.Now())
return s.get(id)
}
// get returns the postage batch from the statestore.
// Must be called under lock.
func (s *store) get(id []byte) (*postage.Batch, error) {
b := &postage.Batch{}
err := s.store.Get(batchKey(id), b)
if err != nil {
return nil, fmt.Errorf("get batch %s: %w", hex.EncodeToString(id), err)
}
return b, nil
}
// Exists is implementation of postage.Storer interface Exists method.
func (s *store) Exists(id []byte) (bool, error) {
defer func(t time.Time) {
s.metrics.ExistsDuration.WithLabelValues("true").Observe(time.Since(t).Seconds())
}(time.Now())
s.mtx.Lock()
defer s.mtx.Unlock()
defer func(t time.Time) {
s.metrics.ExistsDuration.WithLabelValues("false").Observe(time.Since(t).Seconds())
}(time.Now())
switch err := s.store.Get(batchKey(id), new(postage.Batch)); {
case err == nil:
return true, nil
case errors.Is(err, storage.ErrNotFound):
return false, nil
default:
return false, err
}
}
// Iterate is implementation of postage.Storer interface Iterate method.
func (s *store) Iterate(cb func(*postage.Batch) (bool, error)) error {
s.mtx.Lock()
defer s.mtx.Unlock()
return s.store.Iterate(batchKeyPrefix, func(key, value []byte) (bool, error) {
b := &postage.Batch{}
if err := b.UnmarshalBinary(value); err != nil {
return false, err
}
return cb(b)
})
}
// Save is implementation of postage.Storer interface Save method.
// This method has side effects; it also updates the radius of the node if successful.
func (s *store) Save(batch *postage.Batch) error {
defer func(t time.Time) {
s.metrics.SaveDuration.WithLabelValues("true").Observe(time.Since(t).Seconds())
}(time.Now())
s.mtx.Lock()
defer s.mtx.Unlock()
defer func(t time.Time) {
s.metrics.SaveDuration.WithLabelValues("false").Observe(time.Since(t).Seconds())
}(time.Now())
switch err := s.store.Get(batchKey(batch.ID), new(postage.Batch)); {
case errors.Is(err, storage.ErrNotFound):
batch.StorageRadius = s.rs.StorageRadius
if err := s.store.Put(batchKey(batch.ID), batch); err != nil {
return err
}
if err := s.saveBatch(batch); err != nil {
return err
}
if s.radiusSetter != nil {
s.radiusSetter.SetRadius(s.rs.Radius)
}
return nil
case err == nil:
return fmt.Errorf("batchstore: save batch %s depth %d value %d failed: already exists", hex.EncodeToString(batch.ID), batch.Depth, batch.Value.Int64())
case err != nil:
return fmt.Errorf("batchstore: save batch %s depth %d value %d failed: get batch: %w", hex.EncodeToString(batch.ID), batch.Depth, batch.Value.Int64(), err)
}
s.logger.Debugf("batchstore: saved batch %x depth %d value %d, radius %d, storage radius %d", batch.ID, batch.Depth, batch.Value.Int64(), s.rs.Radius, s.rs.StorageRadius)
return nil
}
// Update is implementation of postage.Storer interface Update method.
// This method has side effects; it also updates the radius of the node if successful.
func (s *store) Update(batch *postage.Batch, value *big.Int, depth uint8) error {
s.mtx.Lock()
defer s.mtx.Unlock()
oldBatch := &postage.Batch{}
s.logger.Debugf("batchstore: update batch %x depth %d value %d", batch.ID, depth, value.Int64())
switch err := s.store.Get(batchKey(batch.ID), oldBatch); {
case errors.Is(err, storage.ErrNotFound):
return ErrNotFound
case err != nil:
return fmt.Errorf("get batch %s: %w", hex.EncodeToString(batch.ID), err)
}
if err := s.store.Delete(valueKey(batch.Value, batch.ID)); err != nil {
return err
}
batch.Value.Set(value)
batch.Depth = depth
batch.StorageRadius = oldBatch.StorageRadius
err := s.store.Put(batchKey(batch.ID), batch)
if err != nil {
return err
}
err = s.saveBatch(batch)
if err != nil {
return err
}
if s.radiusSetter != nil {
s.radiusSetter.SetRadius(s.rs.Radius)
}
return nil
}
// PutChainState is implementation of postage.Storer interface PutChainState method.
// This method has side effects; it purges expired batches and unreserves underfunded
// ones before it stores the chain state in the store.
func (s *store) PutChainState(cs *postage.ChainState) error {
s.mtx.Lock()
defer s.mtx.Unlock()
s.cs = cs
s.logger.Debugf("batchstore: put chain state block %d amount %d price %d", cs.Block, cs.TotalAmount.Int64(), cs.CurrentPrice.Int64())
err := s.cleanup()
if err != nil {
return fmt.Errorf("batchstore: put chain state clean up: %w", err)
}
err = s.computeRadius()
if err != nil {
return fmt.Errorf("batchstore: put chain state adjust radius: %w", err)
}
// this needs to be improved, since we can miss some calls on
// startup. the same goes for the other call to radiusSetter
if s.radiusSetter != nil {
s.radiusSetter.SetRadius(s.rs.Radius)
}
return s.store.Put(chainStateKey, cs)
}
// SetRadiusSetter is implementation of postage.Storer interface SetRadiusSetter method.
func (s *store) SetRadiusSetter(r postage.RadiusSetter) {
s.radiusSetter = r
}
// Reset is implementation of postage.Storer interface Reset method.
func (s *store) Reset() error {
s.mtx.Lock()
defer s.mtx.Unlock()
const prefix = "batchstore_"
if err := s.store.Iterate(prefix, func(k, _ []byte) (bool, error) {
return false, s.store.Delete(string(k))
}); err != nil {
return err
}
s.cs = &postage.ChainState{
Block: 0,
TotalAmount: big.NewInt(0),
CurrentPrice: big.NewInt(0),
}
s.rs = &reserveState{
Radius: 0,
}
return nil
}
// batchKey returns the index key for the batch ID used in the by-ID batch index.
func batchKey(batchID []byte) string {
return batchKeyPrefix + string(batchID)
}
// valueKey returns the index key for the batch ID used in the by-ID batch index.
func valueKey(val *big.Int, batchID []byte) string {
value := make([]byte, 32)
val.FillBytes(value) // zero-extended big-endian byte slice
return valueKeyPrefix + string(value) + string(batchID)
}
// valueKeyToID extracts the batch ID from a value key - used in value-based iteration.
func valueKeyToID(key []byte) []byte {
l := len(key)
return key[l-32 : l]
}