-
Notifications
You must be signed in to change notification settings - Fork 679
/
memtable.go
358 lines (290 loc) · 8.14 KB
/
memtable.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
// _ _
// __ _____ __ ___ ___ __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
// \ V V / __/ (_| |\ V /| | (_| | || __/
// \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
// Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
//
// CONTACT: hello@weaviate.io
//
package lsmkv
import (
"path/filepath"
"sync"
"time"
"github.com/pkg/errors"
"github.com/weaviate/weaviate/adapters/repos/db/roaringset"
"github.com/weaviate/weaviate/entities/lsmkv"
)
type Memtable struct {
sync.RWMutex
key *binarySearchTree
keyMulti *binarySearchTreeMulti
keyMap *binarySearchTreeMap
primaryIndex *binarySearchTree
roaringSet *roaringset.BinarySearchTree
commitlog *commitLogger
size uint64
path string
strategy string
secondaryIndices uint16
secondaryToPrimary []map[string][]byte
// stores time memtable got dirty to determine when flush is needed
dirtyAt time.Time
createdAt time.Time
metrics *memtableMetrics
}
func newMemtable(path string, strategy string,
secondaryIndices uint16, cl *commitLogger, metrics *Metrics,
) (*Memtable, error) {
m := &Memtable{
key: &binarySearchTree{},
keyMulti: &binarySearchTreeMulti{},
keyMap: &binarySearchTreeMap{},
primaryIndex: &binarySearchTree{}, // todo, sort upfront
roaringSet: &roaringset.BinarySearchTree{},
commitlog: cl,
path: path,
strategy: strategy,
secondaryIndices: secondaryIndices,
dirtyAt: time.Time{},
createdAt: time.Now(),
metrics: newMemtableMetrics(metrics, filepath.Dir(path), strategy),
}
if m.secondaryIndices > 0 {
m.secondaryToPrimary = make([]map[string][]byte, m.secondaryIndices)
for i := range m.secondaryToPrimary {
m.secondaryToPrimary[i] = map[string][]byte{}
}
}
m.metrics.size(m.size)
return m, nil
}
func (m *Memtable) get(key []byte) ([]byte, error) {
start := time.Now()
defer m.metrics.get(start.UnixNano())
if m.strategy != StrategyReplace {
return nil, errors.Errorf("get only possible with strategy 'replace'")
}
m.RLock()
defer m.RUnlock()
v, err := m.key.get(key)
if err != nil {
return nil, err
}
return v, nil
}
func (m *Memtable) getBySecondary(pos int, key []byte) ([]byte, error) {
start := time.Now()
defer m.metrics.getBySecondary(start.UnixNano())
if m.strategy != StrategyReplace {
return nil, errors.Errorf("get only possible with strategy 'replace'")
}
m.RLock()
defer m.RUnlock()
primary := m.secondaryToPrimary[pos][string(key)]
if primary == nil {
return nil, lsmkv.NotFound
}
v, err := m.key.get(primary)
if err != nil {
return nil, err
}
return v, nil
}
func (m *Memtable) put(key, value []byte, opts ...SecondaryKeyOption) error {
start := time.Now()
defer m.metrics.put(start.UnixNano())
if m.strategy != StrategyReplace {
return errors.Errorf("put only possible with strategy 'replace'")
}
m.Lock()
defer m.Unlock()
var secondaryKeys [][]byte
if m.secondaryIndices > 0 {
secondaryKeys = make([][]byte, m.secondaryIndices)
for _, opt := range opts {
if err := opt(secondaryKeys); err != nil {
return err
}
}
}
if err := m.commitlog.put(segmentReplaceNode{
primaryKey: key,
value: value,
secondaryIndexCount: m.secondaryIndices,
secondaryKeys: secondaryKeys,
tombstone: false,
}); err != nil {
return errors.Wrap(err, "write into commit log")
}
netAdditions, previousKeys := m.key.insert(key, value, secondaryKeys)
for i, sec := range previousKeys {
m.secondaryToPrimary[i][string(sec)] = nil
}
for i, sec := range secondaryKeys {
m.secondaryToPrimary[i][string(sec)] = key
}
m.size += uint64(netAdditions)
m.metrics.size(m.size)
m.updateDirtyAt()
return nil
}
func (m *Memtable) setTombstone(key []byte, opts ...SecondaryKeyOption) error {
start := time.Now()
defer m.metrics.setTombstone(start.UnixNano())
if m.strategy != "replace" {
return errors.Errorf("setTombstone only possible with strategy 'replace'")
}
m.Lock()
defer m.Unlock()
var secondaryKeys [][]byte
if m.secondaryIndices > 0 {
secondaryKeys = make([][]byte, m.secondaryIndices)
for _, opt := range opts {
if err := opt(secondaryKeys); err != nil {
return err
}
}
}
if err := m.commitlog.put(segmentReplaceNode{
primaryKey: key,
value: nil,
secondaryIndexCount: m.secondaryIndices,
secondaryKeys: secondaryKeys,
tombstone: true,
}); err != nil {
return errors.Wrap(err, "write into commit log")
}
m.key.setTombstone(key, secondaryKeys)
m.size += uint64(len(key)) + 1 // 1 byte for tombstone
m.metrics.size(m.size)
m.updateDirtyAt()
return nil
}
func (m *Memtable) getCollection(key []byte) ([]value, error) {
start := time.Now()
defer m.metrics.getCollection(start.UnixNano())
if m.strategy != StrategySetCollection && m.strategy != StrategyMapCollection {
return nil, errors.Errorf("getCollection only possible with strategies %q, %q",
StrategySetCollection, StrategyMapCollection)
}
m.RLock()
defer m.RUnlock()
v, err := m.keyMulti.get(key)
if err != nil {
return nil, err
}
return v, nil
}
func (m *Memtable) getMap(key []byte) ([]MapPair, error) {
start := time.Now()
defer m.metrics.getMap(start.UnixNano())
if m.strategy != StrategyMapCollection {
return nil, errors.Errorf("getCollection only possible with strategy %q",
StrategyMapCollection)
}
m.RLock()
defer m.RUnlock()
v, err := m.keyMap.get(key)
if err != nil {
return nil, err
}
return v, nil
}
func (m *Memtable) append(key []byte, values []value) error {
start := time.Now()
defer m.metrics.append(start.UnixNano())
if m.strategy != StrategySetCollection && m.strategy != StrategyMapCollection {
return errors.Errorf("append only possible with strategies %q, %q",
StrategySetCollection, StrategyMapCollection)
}
m.Lock()
defer m.Unlock()
if err := m.commitlog.append(segmentCollectionNode{
primaryKey: key,
values: values,
}); err != nil {
return errors.Wrap(err, "write into commit log")
}
m.keyMulti.insert(key, values)
m.size += uint64(len(key))
for _, value := range values {
m.size += uint64(len(value.value))
}
m.metrics.size(m.size)
m.updateDirtyAt()
return nil
}
func (m *Memtable) appendMapSorted(key []byte, pair MapPair) error {
start := time.Now()
defer m.metrics.appendMapSorted(start.UnixNano())
if m.strategy != StrategyMapCollection {
return errors.Errorf("append only possible with strategy %q",
StrategyMapCollection)
}
m.Lock()
defer m.Unlock()
valuesForCommitLog, err := pair.Bytes()
if err != nil {
return err
}
if err := m.commitlog.append(segmentCollectionNode{
primaryKey: key,
values: []value{
{
value: valuesForCommitLog,
tombstone: pair.Tombstone,
},
},
}); err != nil {
return errors.Wrap(err, "write into commit log")
}
m.keyMap.insert(key, pair)
m.size += uint64(len(key) + len(valuesForCommitLog))
m.metrics.size(m.size)
m.updateDirtyAt()
return nil
}
func (m *Memtable) Size() uint64 {
m.RLock()
defer m.RUnlock()
return m.size
}
func (m *Memtable) ActiveDuration() time.Duration {
m.RLock()
defer m.RUnlock()
return time.Since(m.createdAt)
}
func (m *Memtable) updateDirtyAt() {
if m.dirtyAt.IsZero() {
m.dirtyAt = time.Now()
}
}
// returns time memtable got dirty (1st write occurred)
// (0 if clean)
func (m *Memtable) DirtyDuration() time.Duration {
m.RLock()
defer m.RUnlock()
if m.dirtyAt.IsZero() {
return 0
}
return time.Since(m.dirtyAt)
}
func (m *Memtable) countStats() *countStats {
m.RLock()
defer m.RUnlock()
return m.key.countStats()
}
// the WAL uses a buffer and isn't written until the buffer size is crossed or
// this function explicitly called. This allows to safge unnecessary disk
// writes in larger operations, such as batches. It is sufficient to call write
// on the WAL just once. This does not make a batch atomic, but it guarantees
// that the WAL is written before a successful response is returned to the
// user.
func (m *Memtable) writeWAL() error {
m.Lock()
defer m.Unlock()
return m.commitlog.flushBuffers()
}