-
Notifications
You must be signed in to change notification settings - Fork 649
/
batch.go
111 lines (91 loc) · 2.21 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
104
105
106
107
108
109
110
111
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package pebble
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 {
// This batch has not been written to the database yet.
if err := updateError(b.batch.Commit(pebble.Sync)); err != nil {
return err
}
b.written = true
return nil
}
// pebble doesn't support writing a batch twice so we have to clone
// [b] and commit the clone.
batchClone := b.db.pebbleDB.NewBatch()
// Copy the batch.
if err := batchClone.Apply(b.batch, nil); err != nil {
return err
}
// Commit the new batch.
return updateError(batchClone.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
}