-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatch.go
256 lines (214 loc) · 5.33 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
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
package riverdb
import (
"github.com/246859/river/entry"
"github.com/246859/river/index"
"github.com/246859/river/pkg/str"
"github.com/246859/river/wal"
"github.com/pkg/errors"
"sync"
"sync/atomic"
"time"
)
var ErrBatchClosed = errors.New("batch is closed")
type BatchOption struct {
// size of per batch
Size int64
// call Fsync after per batch has been written
SyncPerBatch bool
// call Fsync after all batch finished, not recommended enabled both SyncPerBatch and SyncOnFlush simultaneously
// if both of SyncPerBatch and SyncOnFlush is false, batch will apply sync rules in db.options
SyncOnFlush bool
}
// Record is a user-oriented struct representing an entry data in db
type Record struct {
K Key
V Value
TTL time.Duration
}
// Batch provides ability to write or delete entries in batch which is update-only,
// it will split given records into several batches, and run a new goroutine for each batch to handle in batchTxn.
// each batch records will be stored in memory temporarily, then they will be written to the database in batch
// finally update db index if commit succeeds.
func (db *DB) Batch(opt BatchOption) (*Batch, error) {
if opt.Size <= 0 {
return nil, errors.New("invalid batch size")
}
return &Batch{
opt: opt,
db: db,
pendingPool: sync.Pool{New: func() any {
return make(map[string]*entry.Entry, opt.Size)
}},
}, nil
}
// Batch operator
type Batch struct {
db *DB
opt BatchOption
mu sync.Mutex
pendingPool sync.Pool
closed bool
effected atomic.Int64
}
func (ba *Batch) Effected() int64 {
return ba.effected.Load()
}
func (ba *Batch) writeAll(rs []Record, et entry.EType) error {
lrs := int64(len(rs))
for lrs > 0 {
// cut records into per batch by BatchOption.Size
var batchRecord []Record
if int64(len(rs)) < ba.opt.Size {
batchRecord = rs[:]
lrs -= int64(len(rs))
rs = rs[:0:0]
} else {
batchRecord = rs[:ba.opt.Size:ba.opt.Size]
rs = rs[ba.opt.Size:]
lrs -= ba.opt.Size
}
var estimatedSize int64
for i, record := range batchRecord {
estimatedSize += wal.EstimateBlockSize(int64(entry.MaxHeaderSize + len(record.K) + len(record.V)))
// if this batch is reach to the max size, cut it.
if estimatedSize >= int64(float64(ba.db.option.MaxSize)*0.92) {
rs = append(batchRecord[i:], rs...)
lrs += int64(len(batchRecord) - i)
batchRecord = batchRecord[:i]
break
}
}
// start a txn
txn, err := ba.db.beginTxn(false)
if err != nil {
return err
}
bt := batchTxn{txn: txn, ba: ba}
// get pending buffer from pool
bt.pendingBuf = ba.pendingPool.Get().(map[string]*entry.Entry)
if err = bt.write(batchRecord, et); err != nil {
_ = bt.rollback()
return err
}
if err = bt.commit(ba.opt.SyncPerBatch); err != nil {
_ = bt.rollback()
return err
}
clear(bt.pendingBuf)
ba.pendingPool.Put(bt.pendingBuf)
}
return nil
}
// WriteAll writes all given records to db in batchTxn
func (ba *Batch) WriteAll(records []Record) error {
if len(records) == 0 {
return nil
}
ba.mu.Lock()
defer ba.mu.Unlock()
if ba.closed {
return ErrBatchClosed
}
return ba.writeAll(records, entry.DataEntryType)
}
// DeleteAll delete all given key matching records from db in batchTxn
func (ba *Batch) DeleteAll(keys []Key) error {
if len(keys) == 0 {
return nil
}
ba.mu.Lock()
defer ba.mu.Unlock()
if ba.closed {
return ErrBatchClosed
}
var rs []Record
for _, key := range keys {
rs = append(rs, Record{K: key})
}
return ba.writeAll(rs, entry.DeletedEntryType)
}
// Flush close Batch, then waiting for the remaining batchTxn to complete,
// and call db.Sync to Flush db finally.
func (ba *Batch) Flush() error {
ba.mu.Lock()
defer ba.mu.Unlock()
ba.closed = true
if ba.opt.SyncOnFlush {
// manually sync
if err := ba.db.Sync(); err != nil {
return err
}
}
return nil
}
// batchTxn wrap Txn to perform batch operations
type batchTxn struct {
txn *Txn
ba *Batch
pendingBuf map[string]*entry.Entry
}
func (b *batchTxn) putAll(ens []*entry.Entry, needSync bool) error {
db := b.txn.db
p := b.txn.pending
all, err := db.writeAll(ens, needSync)
if err != nil {
return err
}
for i, pos := range all {
if err := p.memIndex.Put(index.Hint{ChunkPos: pos, TTL: ens[i].TTL, Key: ens[i].Key, Meta: ens[i].Type}); err != nil {
return err
}
b.txn.trackWrite(ens[i].Key)
}
return nil
}
func (b *batchTxn) write(record []Record, et entry.EType) error {
for _, r := range record {
if r.K == nil {
return ErrNilKey
}
e := &entry.Entry{
Type: et,
Key: r.K,
Value: r.V,
TTL: entry.NewTTL(r.TTL),
TxId: b.txn.id.Int64(),
}
if e.Type == entry.DataEntryType {
if r.TTL == 0 {
e.TTL = 0
} else if r.TTL < 0 {
ttl, err := b.txn.ttl(r.K)
if errors.Is(err, ErrKeyNotFound) {
e.TTL = 0
} else if err == nil {
e.TTL = ttl
} else {
return err
}
}
}
b.pendingBuf[str.BytesToString(r.K)] = e
}
return nil
}
func (b *batchTxn) rollback() error {
return b.txn.rollback()
}
func (b *batchTxn) commit(needSync bool) error {
es := make([]*entry.Entry, 0, len(b.pendingBuf))
for _, e := range b.pendingBuf {
es = append(es, e)
}
if b.ba.closed {
return ErrBatchClosed
}
if err := b.putAll(es, needSync); err != nil {
return err
}
if err := b.txn.commit(); err != nil {
return err
}
b.ba.effected.Add(int64(len(es)))
return nil
}