-
Notifications
You must be signed in to change notification settings - Fork 664
/
batch.go
103 lines (85 loc) · 2.03 KB
/
batch.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package pebbledb
import (
"fmt"
"github.com/cockroachdb/pebble"
"github.com/ava-labs/avalanchego/database"
)
var _ database.Batch = (*batch)(nil)
// Not safe for concurrent use.
type batch struct {
batch *pebble.Batch
db *Database
size int
// True iff [batch] has been written to the database
// since the last time [Reset] was called.
written bool
}
func (db *Database) NewBatch() database.Batch {
return &batch{
db: db,
batch: db.pebbleDB.NewBatch(),
}
}
func (b *batch) Put(key, value []byte) error {
b.size += len(key) + len(value) + pebbleByteOverHead
return b.batch.Set(key, value, pebble.Sync)
}
func (b *batch) Delete(key []byte) error {
b.size += len(key) + pebbleByteOverHead
return b.batch.Delete(key, pebble.Sync)
}
func (b *batch) Size() int {
return b.size
}
// Assumes [b.db.lock] is not held.
func (b *batch) Write() error {
b.db.lock.RLock()
defer b.db.lock.RUnlock()
// Committing to a closed database makes pebble panic
// so make sure [b.db] isn't closed.
if b.db.closed {
return database.ErrClosed
}
if b.written {
// pebble doesn't support writing a batch twice so we have to clone the
// batch before writing it.
newBatch := b.db.pebbleDB.NewBatch()
if err := newBatch.Apply(b.batch, nil); err != nil {
return err
}
b.batch = newBatch
}
b.written = true
return updateError(b.batch.Commit(pebble.Sync))
}
func (b *batch) Reset() {
b.batch.Reset()
b.written = false
b.size = 0
}
func (b *batch) Replay(w database.KeyValueWriterDeleter) error {
reader := b.batch.Reader()
for {
kind, k, v, ok := reader.Next()
if !ok {
return nil
}
switch kind {
case pebble.InternalKeyKindSet:
if err := w.Put(k, v); err != nil {
return err
}
case pebble.InternalKeyKindDelete:
if err := w.Delete(k); err != nil {
return err
}
default:
return fmt.Errorf("%w: %v", errInvalidOperation, kind)
}
}
}
func (b *batch) Inner() database.Batch {
return b
}