-
Notifications
You must be signed in to change notification settings - Fork 10
/
batch.go
369 lines (333 loc) · 9.37 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
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
367
368
369
/*
* Copyright 2020 Saffat Technologies, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unitdb
import (
"encoding/binary"
"fmt"
"sync"
"github.com/unit-io/bpool"
"github.com/unit-io/unitdb/hash"
"github.com/unit-io/unitdb/message"
"github.com/unit-io/unitdb/uid"
)
func (index batchIndex) message(data []byte) (id, topic []byte) {
return data[:idSize], data[idSize : idSize+index.topicSize]
}
// SetOptions sets batch options
func (b *Batch) SetOptions(opts *BatchOptions) {
b.opts = opts
}
type (
batchInfo struct {
entryCount int
}
batchIndex struct {
delFlag bool
key uint32 // key is local id unique in batch and used to remove duplicate values from a topic in the batch before writing records into DB
topicSize uint16
offset int64
expiresAt uint32
}
// Batch is a write batch.
Batch struct {
batchID uid.LID
opts *BatchOptions
managed bool
grouped bool
order int8
batchInfo
buffer *bpool.Buffer
size int64
db *DB
index []batchIndex
pendingWrites []batchIndex
// commitComplete is used to signal if batch commit is complete and batch is fully written to write ahead log
commitW sync.WaitGroup
commitComplete chan struct{}
}
)
// Put adds entry to batch for given topic->key/value.
// Client must provide Topic to the BatchOptions.
// It is safe to modify the contents of the argument after Put returns but not
// before.
func (b *Batch) Put(topic, payload []byte) error {
return b.PutEntry(NewEntry(topic).WithPayload(payload).WithContract(b.opts.Contract))
}
// PutEntry appends entries to a bacth for given topic->key/value pair.
// It is safe to modify the contents of the argument after Put returns but not
// before.
func (b *Batch) PutEntry(e *Entry) error {
switch {
case len(e.Topic) == 0:
return errTopicEmpty
case len(e.Topic) > maxTopicLength:
return errTopicTooLarge
case len(e.Payload) == 0:
return errValueEmpty
case len(e.Payload) > maxValueLength:
return errValueTooLarge
}
if e.Contract == 0 {
e.Contract = message.MasterContract
}
topic, ttl, err := b.db.parseTopic(e)
if err != nil {
return err
}
topic.AddContract(e.Contract)
e.topic.data = topic.Marshal()
e.topic.size = uint16(len(e.topic.data))
e.contract = message.Contract(topic.Parts)
e.encryption = b.opts.Encryption
if err := b.db.setEntry(e, ttl); err != nil {
return err
}
var key uint32
if !b.opts.AllowDuplicates {
key = hash.WithSalt(e.val, topic.GetHashCode())
}
// Encryption.
if e.encryption {
e.val = b.db.mac.Encrypt(nil, e.val)
}
data, err := b.db.packEntry(e)
if err != nil {
return err
}
var scratch [4]byte
binary.LittleEndian.PutUint32(scratch[0:4], uint32(len(data)+4))
if _, err := b.buffer.Write(scratch[:]); err != nil {
return err
}
if _, err := b.buffer.Write(data); err != nil {
return err
}
b.index = append(b.index, batchIndex{delFlag: false, key: key, topicSize: e.topic.size, offset: b.size, expiresAt: e.ExpiresAt})
b.size += int64(len(data) + 4)
b.entryCount++
return nil
}
// Delete appends delete entry to batch for given key.
// It is safe to modify the contents of the argument after Delete returns but
// not before.
func (b *Batch) Delete(id, topic []byte) error {
return b.DeleteEntry(NewEntry(topic).WithID(id))
}
// DeleteEntry appends entry for deletion to a batch for given key.
// It is safe to modify the contents of the argument after Delete returns but
// not before.
func (b *Batch) DeleteEntry(e *Entry) error {
switch {
case b.opts.Immutable:
return errImmutable
case len(e.ID) == 0:
return errMsgIDEmpty
case len(e.Topic) == 0:
return errTopicEmpty
case len(e.Topic) > maxTopicLength:
return errTopicTooLarge
}
topic, _, err := b.db.parseTopic(e)
if err != nil {
return err
}
if e.Contract == 0 {
e.Contract = message.MasterContract
}
topic.AddContract(e.Contract)
e.topic.data = topic.Marshal()
e.topic.size = uint16(len(e.topic.data))
e.contract = message.Contract(topic.Parts)
id := message.ID(e.ID)
id.AddContract(e.contract)
e.id = id
e.seq = id.Seq()
key := topic.GetHashCode()
data, err := b.db.packEntry(e)
if err != nil {
return err
}
var scratch [4]byte
binary.LittleEndian.PutUint32(scratch[0:4], uint32(len(data)+4))
if _, err := b.buffer.Write(scratch[:]); err != nil {
return err
}
if _, err := b.buffer.Write(data); err != nil {
return err
}
b.index = append(b.index, batchIndex{delFlag: true, key: key, topicSize: e.topic.size, offset: b.size})
b.size += int64(len(data) + 4)
b.entryCount++
return nil
}
func (b *Batch) writeInternal(fn func(i int, topicHash uint64, memseq uint64, data []byte) error) error {
if err := b.db.ok(); err != nil {
return err
} // // CPU profiling by default
// defer profile.Start().Stop()
// start := time.Now()
// defer logger.Debug().Str("context", "batch.writeInternal").Dur("duration", time.Since(start)).Msg("")
buf := b.buffer.Bytes()
topics := make(map[uint64]*message.Topic)
for i, index := range b.pendingWrites {
dataLen := binary.LittleEndian.Uint32(buf[index.offset : index.offset+4])
data := buf[index.offset+4 : index.offset+int64(dataLen)]
id, rawTopic := index.message(data[entrySize:])
ID := message.ID(id)
seq := ID.Seq()
contract := ID.Contract()
if _, ok := topics[contract]; !ok {
t := new(message.Topic)
t.Unmarshal(rawTopic)
topics[contract] = t
if ok := b.db.trie.add(topic{hash: t.GetHash(contract)}, t.Parts, t.Depth); !ok {
return errBadRequest
}
}
topic := topics[contract]
topicHash := topic.GetHash(contract)
if index.delFlag {
/// Test filter block for presence
if !b.db.filter.Test(seq) {
return nil
}
b.db.delete(contract, seq)
continue
}
b.db.timeWindow.add(topicHash, winEntry{seq: seq, expiresAt: index.expiresAt})
memseq := b.db.cacheID ^ seq
if err := fn(i, topicHash, memseq, data); err != nil {
return err
}
}
return nil
}
// Write starts writing entries into DB. It returns an error if batch write fails.
func (b *Batch) Write() error {
// The write happen synchronously.
b.db.writeLockC <- struct{}{}
defer func() {
<-b.db.writeLockC
}()
b.uniq()
if b.grouped {
// append batch to batchgroup
b.db.batchQueue <- b
return nil
}
err := b.writeInternal(func(i int, topicHash uint64, memseq uint64, data []byte) error {
return b.db.mem.Set(topicHash, memseq, data)
})
if err != nil {
return err
}
return nil
}
// Commit commits changes to the DB. In batch operation commit is managed and client is not allowed to call Commit.
// On Commit complete batch operation signal to the cliend if the batch is fully commmited to DB.
func (b *Batch) Commit() error {
_assert(!b.managed, "managed tx commit not allowed")
if len(b.pendingWrites) == 0 || b.buffer.Size() == 0 {
b.Abort()
return nil
}
defer func() {
close(b.commitComplete)
}()
if err := b.db.commit(b.Len(), b.buffer); err != nil {
logger.Error().Err(err).Str("context", "commit").Msgf("Error committing batch")
}
return nil
}
//Abort abort is a batch cleanup operation on batch complete
func (b *Batch) Abort() {
_assert(!b.managed, "managed tx abort not allowed")
b.Reset()
b.db.bufPool.Put(b.buffer)
b.db = nil
}
// Reset resets the batch.
func (b *Batch) Reset() {
b.entryCount = 0
b.size = 0
b.index = b.index[:0]
b.pendingWrites = b.pendingWrites[:0]
// b.buffer.Reset()
}
func (b *Batch) uniq() []batchIndex {
if b.opts.AllowDuplicates {
b.pendingWrites = append(make([]batchIndex, 0, len(b.index)), b.index...)
return b.pendingWrites
}
type indices struct {
idx int
newidx int
}
uniqueSet := make(map[uint32]indices, len(b.index))
i := 0
for idx := len(b.index) - 1; idx >= 0; idx-- {
if _, ok := uniqueSet[b.index[idx].key]; !ok {
uniqueSet[b.index[idx].key] = indices{idx, i}
i++
}
}
b.pendingWrites = make([]batchIndex, len(uniqueSet))
for _, i := range uniqueSet {
b.pendingWrites[len(uniqueSet)-i.newidx-1] = b.index[i.idx]
}
return b.pendingWrites
}
func (b *Batch) append(new *Batch) {
if new.Len() == 0 {
return
}
off := b.size
for _, idx := range new.index {
idx.offset = idx.offset + int64(off)
b.index = append(b.index, idx)
}
b.size += new.size
b.buffer.Write(new.buffer.Bytes())
}
// _assert will panic with a given formatted message if the given condition is false.
func _assert(condition bool, msg string, v ...interface{}) {
if !condition {
panic(fmt.Sprintf("assertion failed: "+msg, v...))
}
}
// Len returns number of records in the batch.
func (b *Batch) Len() int {
return len(b.pendingWrites)
}
// setManaged sets batch managed.
func (b *Batch) setManaged() {
b.managed = true
}
// unsetManaged sets batch unmanaged.
func (b *Batch) unsetManaged() {
b.managed = false
}
// setGrouped set grouping of multiple batches.
func (b *Batch) setGrouped(g *BatchGroup) {
b.grouped = true
}
// unsetGrouped unset grouping.
func (b *Batch) unsetGrouped() {
b.grouped = false
}
func (b *Batch) setOrder(order int8) {
b.order = order
}