-
Notifications
You must be signed in to change notification settings - Fork 671
/
db.go
366 lines (316 loc) · 8.95 KB
/
db.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package prefixdb
import (
"context"
"sync"
"golang.org/x/exp/slices"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/utils/hashing"
)
const (
defaultBufCap = 256
)
var (
_ database.Database = (*Database)(nil)
_ database.Batch = (*batch)(nil)
_ database.Iterator = (*iterator)(nil)
)
// Database partitions a database into a sub-database by prefixing all keys with
// a unique value.
type Database struct {
// All keys in this db begin with this byte slice
dbPrefix []byte
// Holds unused []byte
bufferPool sync.Pool
// lock needs to be held during Close to guarantee db will not be set to nil
// concurrently with another operation. All other operations can hold RLock.
lock sync.RWMutex
// The underlying storage
db database.Database
closed bool
}
// New returns a new prefixed database
func New(prefix []byte, db database.Database) *Database {
if prefixDB, ok := db.(*Database); ok {
simplePrefix := make([]byte, len(prefixDB.dbPrefix)+len(prefix))
copy(simplePrefix, prefixDB.dbPrefix)
copy(simplePrefix[len(prefixDB.dbPrefix):], prefix)
return NewNested(simplePrefix, prefixDB.db)
}
return NewNested(prefix, db)
}
// NewNested returns a new prefixed database without attempting to compress
// prefixes.
func NewNested(prefix []byte, db database.Database) *Database {
return &Database{
dbPrefix: hashing.ComputeHash256(prefix),
db: db,
bufferPool: sync.Pool{
New: func() interface{} {
return make([]byte, 0, defaultBufCap)
},
},
}
}
// Assumes that it is OK for the argument to db.db.Has
// to be modified after db.db.Has returns
// [key] may be modified after this method returns.
func (db *Database) Has(key []byte) (bool, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return false, database.ErrClosed
}
prefixedKey := db.prefix(key)
has, err := db.db.Has(prefixedKey)
db.bufferPool.Put(prefixedKey)
return has, err
}
// Assumes that it is OK for the argument to db.db.Get
// to be modified after db.db.Get returns.
// [key] may be modified after this method returns.
func (db *Database) Get(key []byte) ([]byte, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return nil, database.ErrClosed
}
prefixedKey := db.prefix(key)
val, err := db.db.Get(prefixedKey)
db.bufferPool.Put(prefixedKey)
return val, err
}
// Assumes that it is OK for the argument to db.db.Put
// to be modified after db.db.Put returns.
// [key] can be modified after this method returns.
// [value] should not be modified.
func (db *Database) Put(key, value []byte) error {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return database.ErrClosed
}
prefixedKey := db.prefix(key)
err := db.db.Put(prefixedKey, value)
db.bufferPool.Put(prefixedKey)
return err
}
// Assumes that it is OK for the argument to db.db.Delete
// to be modified after db.db.Delete returns.
// [key] may be modified after this method returns.
func (db *Database) Delete(key []byte) error {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return database.ErrClosed
}
prefixedKey := db.prefix(key)
err := db.db.Delete(prefixedKey)
db.bufferPool.Put(prefixedKey)
return err
}
func (db *Database) NewBatch() database.Batch {
return &batch{
Batch: db.db.NewBatch(),
db: db,
}
}
func (db *Database) NewIterator() database.Iterator {
return db.NewIteratorWithStartAndPrefix(nil, nil)
}
func (db *Database) NewIteratorWithStart(start []byte) database.Iterator {
return db.NewIteratorWithStartAndPrefix(start, nil)
}
func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {
return db.NewIteratorWithStartAndPrefix(nil, prefix)
}
// Assumes it is safe to modify the arguments to db.db.NewIteratorWithStartAndPrefix after it returns.
// It is safe to modify [start] and [prefix] after this method returns.
func (db *Database) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return &database.IteratorError{
Err: database.ErrClosed,
}
}
prefixedStart := db.prefix(start)
prefixedPrefix := db.prefix(prefix)
it := &iterator{
Iterator: db.db.NewIteratorWithStartAndPrefix(prefixedStart, prefixedPrefix),
db: db,
}
db.bufferPool.Put(prefixedStart)
db.bufferPool.Put(prefixedPrefix)
return it
}
func (db *Database) Compact(start, limit []byte) error {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return database.ErrClosed
}
return db.db.Compact(db.prefix(start), db.prefix(limit))
}
func (db *Database) Close() error {
db.lock.Lock()
defer db.lock.Unlock()
if db.closed {
return database.ErrClosed
}
db.closed = true
return nil
}
func (db *Database) isClosed() bool {
db.lock.RLock()
defer db.lock.RUnlock()
return db.closed
}
func (db *Database) HealthCheck(ctx context.Context) (interface{}, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return nil, database.ErrClosed
}
return db.db.HealthCheck(ctx)
}
// Return a copy of [key], prepended with this db's prefix.
// The returned slice should be put back in the pool
// when it's done being used.
func (db *Database) prefix(key []byte) []byte {
// Get a []byte from the pool
prefixedKey := db.bufferPool.Get().([]byte)
keyLen := len(db.dbPrefix) + len(key)
if cap(prefixedKey) >= keyLen {
// The [] byte we got from the pool is big enough to hold the prefixed key
prefixedKey = prefixedKey[:keyLen]
} else {
// The []byte from the pool wasn't big enough.
// Put it back and allocate a new, bigger one
db.bufferPool.Put(prefixedKey)
prefixedKey = make([]byte, keyLen)
}
copy(prefixedKey, db.dbPrefix)
copy(prefixedKey[len(db.dbPrefix):], key)
return prefixedKey
}
// Batch of database operations
type batch struct {
database.Batch
db *Database
// Each key is prepended with the database's prefix.
// Each byte slice underlying a key should be returned to the pool
// when this batch is reset.
ops []database.BatchOp
}
// Assumes that it is OK for the argument to b.Batch.Put
// to be modified after b.Batch.Put returns
// [key] may be modified after this method returns.
// [value] may be modified after this method returns.
func (b *batch) Put(key, value []byte) error {
prefixedKey := b.db.prefix(key)
copiedValue := slices.Clone(value)
b.ops = append(b.ops, database.BatchOp{
Key: prefixedKey,
Value: copiedValue,
})
return b.Batch.Put(prefixedKey, copiedValue)
}
// Assumes that it is OK for the argument to b.Batch.Delete
// to be modified after b.Batch.Delete returns
// [key] may be modified after this method returns.
func (b *batch) Delete(key []byte) error {
prefixedKey := b.db.prefix(key)
b.ops = append(b.ops, database.BatchOp{
Key: prefixedKey,
Delete: true,
})
return b.Batch.Delete(prefixedKey)
}
// Write flushes any accumulated data to the memory database.
func (b *batch) Write() error {
b.db.lock.RLock()
defer b.db.lock.RUnlock()
if b.db.closed {
return database.ErrClosed
}
return b.Batch.Write()
}
// Reset resets the batch for reuse.
func (b *batch) Reset() {
// Return the byte buffers underneath each key back to the pool.
// Don't return the byte buffers underneath each value back to the pool
// because we assume in batch.Replay that it's not safe to modify the
// value argument to w.Put.
for _, op := range b.ops {
b.db.bufferPool.Put(op.Key)
}
// Clear b.writes
if cap(b.ops) > len(b.ops)*database.MaxExcessCapacityFactor {
b.ops = make([]database.BatchOp, 0, cap(b.ops)/database.CapacityReductionFactor)
} else {
b.ops = b.ops[:0]
}
b.Batch.Reset()
}
// Replay replays the batch contents.
// Assumes it's safe to modify the key argument to w.Delete and w.Put
// after those methods return.
func (b *batch) Replay(w database.KeyValueWriterDeleter) error {
for _, op := range b.ops {
keyWithoutPrefix := op.Key[len(b.db.dbPrefix):]
if op.Delete {
if err := w.Delete(keyWithoutPrefix); err != nil {
return err
}
} else {
if err := w.Put(keyWithoutPrefix, op.Value); err != nil {
return err
}
}
}
return nil
}
type iterator struct {
database.Iterator
db *Database
key, val []byte
err error
}
// Next calls the inner iterators Next() function and strips the keys prefix
func (it *iterator) Next() bool {
if it.db.isClosed() {
it.key = nil
it.val = nil
it.err = database.ErrClosed
return false
}
hasNext := it.Iterator.Next()
if hasNext {
key := it.Iterator.Key()
if prefixLen := len(it.db.dbPrefix); len(key) >= prefixLen {
key = key[prefixLen:]
}
it.key = key
it.val = it.Iterator.Value()
} else {
it.key = nil
it.val = nil
}
return hasNext
}
func (it *iterator) Key() []byte {
return it.key
}
func (it *iterator) Value() []byte {
return it.val
}
// Error returns [database.ErrClosed] if the underlying db was closed
// otherwise it returns the normal iterator error.
func (it *iterator) Error() error {
if it.err != nil {
return it.err
}
return it.Iterator.Error()
}