forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
db.go
298 lines (246 loc) · 6.85 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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package pebble
import (
"context"
"encoding/json"
"errors"
"slices"
"sync"
"github.com/cockroachdb/pebble"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/MetalBlockchain/metalgo/database"
"github.com/MetalBlockchain/metalgo/utils/logging"
"github.com/MetalBlockchain/metalgo/utils/set"
"github.com/MetalBlockchain/metalgo/utils/units"
)
const (
Name = "pebble"
// pebbleByteOverHead is the number of bytes of constant overhead that
// should be added to a batch size per operation.
pebbleByteOverHead = 8
defaultCacheSize = 512 * units.MiB
)
var (
_ database.Database = (*Database)(nil)
errInvalidOperation = errors.New("invalid operation")
DefaultConfig = Config{
CacheSize: defaultCacheSize,
BytesPerSync: 512 * units.KiB,
WALBytesPerSync: 0, // Default to no background syncing.
MemTableStopWritesThreshold: 8,
MemTableSize: defaultCacheSize / 4,
MaxOpenFiles: 4096,
MaxConcurrentCompactions: 1,
}
)
type Database struct {
lock sync.RWMutex
pebbleDB *pebble.DB
closed bool
openIterators set.Set[*iter]
}
type Config struct {
CacheSize int64 `json:"cacheSize"`
BytesPerSync int `json:"bytesPerSync"`
WALBytesPerSync int `json:"walBytesPerSync"` // 0 means no background syncing
MemTableStopWritesThreshold int `json:"memTableStopWritesThreshold"`
MemTableSize uint64 `json:"memTableSize"`
MaxOpenFiles int `json:"maxOpenFiles"`
MaxConcurrentCompactions int `json:"maxConcurrentCompactions"`
}
// TODO: Add metrics
func New(file string, configBytes []byte, log logging.Logger, _ string, _ prometheus.Registerer) (database.Database, error) {
cfg := DefaultConfig
if len(configBytes) > 0 {
if err := json.Unmarshal(configBytes, &cfg); err != nil {
return nil, err
}
}
opts := &pebble.Options{
Cache: pebble.NewCache(cfg.CacheSize),
BytesPerSync: cfg.BytesPerSync,
Comparer: pebble.DefaultComparer,
WALBytesPerSync: cfg.WALBytesPerSync,
MemTableStopWritesThreshold: cfg.MemTableStopWritesThreshold,
MemTableSize: cfg.MemTableSize,
MaxOpenFiles: cfg.MaxOpenFiles,
MaxConcurrentCompactions: func() int { return cfg.MaxConcurrentCompactions },
}
opts.Experimental.ReadSamplingMultiplier = -1 // Disable seek compaction
log.Info(
"opening pebble",
zap.Reflect("config", cfg),
)
db, err := pebble.Open(file, opts)
return &Database{
pebbleDB: db,
openIterators: set.Set[*iter]{},
}, err
}
func (db *Database) Close() error {
db.lock.Lock()
defer db.lock.Unlock()
if db.closed {
return database.ErrClosed
}
db.closed = true
for iter := range db.openIterators {
iter.lock.Lock()
iter.release()
iter.lock.Unlock()
}
db.openIterators.Clear()
return updateError(db.pebbleDB.Close())
}
func (db *Database) HealthCheck(_ context.Context) (interface{}, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return nil, database.ErrClosed
}
return nil, nil
}
func (db *Database) Has(key []byte) (bool, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return false, database.ErrClosed
}
_, closer, err := db.pebbleDB.Get(key)
if err == pebble.ErrNotFound {
return false, nil
}
if err != nil {
return false, updateError(err)
}
return true, closer.Close()
}
func (db *Database) Get(key []byte) ([]byte, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return nil, database.ErrClosed
}
data, closer, err := db.pebbleDB.Get(key)
if err != nil {
return nil, updateError(err)
}
return slices.Clone(data), closer.Close()
}
func (db *Database) Put(key []byte, value []byte) error {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return database.ErrClosed
}
return updateError(db.pebbleDB.Set(key, value, pebble.Sync))
}
func (db *Database) Delete(key []byte) error {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return database.ErrClosed
}
return updateError(db.pebbleDB.Delete(key, pebble.Sync))
}
func (db *Database) Compact(start []byte, end []byte) error {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return database.ErrClosed
}
if end == nil {
// The database.Database spec treats a nil [limit] as a key after all
// keys but pebble treats a nil [limit] as a key before all keys in
// Compact. Use the greatest key in the database as the [limit] to get
// the desired behavior.
it, err := db.pebbleDB.NewIter(&pebble.IterOptions{})
if err != nil {
return updateError(err)
}
if !it.Last() {
// The database is empty.
return it.Close()
}
end = slices.Clone(it.Key())
if err := it.Close(); err != nil {
return err
}
}
if pebble.DefaultComparer.Compare(start, end) >= 1 {
// pebble requires [start] < [end]
return nil
}
return updateError(db.pebbleDB.Compact(start, end, true /* parallelize */))
}
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)
}
func (db *Database) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {
db.lock.Lock()
defer db.lock.Unlock()
if db.closed {
return &iter{
db: db,
closed: true,
err: database.ErrClosed,
}
}
it, err := db.pebbleDB.NewIter(keyRange(start, prefix))
if err != nil {
return &iter{
db: db,
closed: true,
err: updateError(err),
}
}
iter := &iter{
db: db,
iter: it,
}
db.openIterators.Add(iter)
return iter
}
// Converts a pebble-specific error to its Avalanche equivalent, if applicable.
func updateError(err error) error {
switch err {
case pebble.ErrClosed:
return database.ErrClosed
case pebble.ErrNotFound:
return database.ErrNotFound
default:
return err
}
}
func keyRange(start, prefix []byte) *pebble.IterOptions {
opt := &pebble.IterOptions{
LowerBound: prefix,
UpperBound: prefixToUpperBound(prefix),
}
if pebble.DefaultComparer.Compare(start, prefix) == 1 {
opt.LowerBound = start
}
return opt
}
// Returns an upper bound that stops after all keys with the given [prefix].
// Assumes the Database uses bytes.Compare for key comparison and not a custom
// comparer.
func prefixToUpperBound(prefix []byte) []byte {
for i := len(prefix) - 1; i >= 0; i-- {
if prefix[i] != 0xFF {
upperBound := make([]byte, i+1)
copy(upperBound, prefix)
upperBound[i]++
return upperBound
}
}
return nil
}