Line data Source code
1 : // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "context"
9 : "encoding/binary"
10 : "fmt"
11 : "io"
12 : "math"
13 : "sort"
14 : "sync"
15 : "sync/atomic"
16 : "time"
17 : "unsafe"
18 :
19 : "github.com/cockroachdb/errors"
20 : "github.com/cockroachdb/pebble/internal/base"
21 : "github.com/cockroachdb/pebble/internal/batchskl"
22 : "github.com/cockroachdb/pebble/internal/humanize"
23 : "github.com/cockroachdb/pebble/internal/keyspan"
24 : "github.com/cockroachdb/pebble/internal/private"
25 : "github.com/cockroachdb/pebble/internal/rangedel"
26 : "github.com/cockroachdb/pebble/internal/rangekey"
27 : "github.com/cockroachdb/pebble/internal/rawalloc"
28 : )
29 :
30 : const (
31 : batchCountOffset = 8
32 : batchHeaderLen = 12
33 : batchInitialSize = 1 << 10 // 1 KB
34 : batchMaxRetainedSize = 1 << 20 // 1 MB
35 : invalidBatchCount = 1<<32 - 1
36 : maxVarintLen32 = 5
37 : )
38 :
39 : // ErrNotIndexed means that a read operation on a batch failed because the
40 : // batch is not indexed and thus doesn't support reads.
41 : var ErrNotIndexed = errors.New("pebble: batch not indexed")
42 :
43 : // ErrInvalidBatch indicates that a batch is invalid or otherwise corrupted.
44 : var ErrInvalidBatch = errors.New("pebble: invalid batch")
45 :
46 : // ErrBatchTooLarge indicates that a batch is invalid or otherwise corrupted.
47 : var ErrBatchTooLarge = errors.Newf("pebble: batch too large: >= %s", humanize.Bytes.Uint64(maxBatchSize))
48 :
49 : // DeferredBatchOp represents a batch operation (eg. set, merge, delete) that is
50 : // being inserted into the batch. Indexing is not performed on the specified key
51 : // until Finish is called, hence the name deferred. This struct lets the caller
52 : // copy or encode keys/values directly into the batch representation instead of
53 : // copying into an intermediary buffer then having pebble.Batch copy off of it.
54 : type DeferredBatchOp struct {
55 : index *batchskl.Skiplist
56 :
57 : // Key and Value point to parts of the binary batch representation where
58 : // keys and values should be encoded/copied into. len(Key) and len(Value)
59 : // bytes must be copied into these slices respectively before calling
60 : // Finish(). Changing where these slices point to is not allowed.
61 : Key, Value []byte
62 : offset uint32
63 : }
64 :
65 : // Finish completes the addition of this batch operation, and adds it to the
66 : // index if necessary. Must be called once (and exactly once) keys/values
67 : // have been filled into Key and Value. Not calling Finish or not
68 : // copying/encoding keys will result in an incomplete index, and calling Finish
69 : // twice may result in a panic.
70 0 : func (d DeferredBatchOp) Finish() error {
71 0 : if d.index != nil {
72 0 : if err := d.index.Add(d.offset); err != nil {
73 0 : return err
74 0 : }
75 : }
76 0 : return nil
77 : }
78 :
79 : // A Batch is a sequence of Sets, Merges, Deletes, DeleteRanges, RangeKeySets,
80 : // RangeKeyUnsets, and/or RangeKeyDeletes that are applied atomically. Batch
81 : // implements the Reader interface, but only an indexed batch supports reading
82 : // (without error) via Get or NewIter. A non-indexed batch will return
83 : // ErrNotIndexed when read from. A batch is not safe for concurrent use, and
84 : // consumers should use a batch per goroutine or provide their own
85 : // synchronization.
86 : //
87 : // # Indexing
88 : //
89 : // Batches can be optionally indexed (see DB.NewIndexedBatch). An indexed batch
90 : // allows iteration via an Iterator (see Batch.NewIter). The iterator provides
91 : // a merged view of the operations in the batch and the underlying
92 : // database. This is implemented by treating the batch as an additional layer
93 : // in the LSM where every entry in the batch is considered newer than any entry
94 : // in the underlying database (batch entries have the InternalKeySeqNumBatch
95 : // bit set). By treating the batch as an additional layer in the LSM, iteration
96 : // supports all batch operations (i.e. Set, Merge, Delete, DeleteRange,
97 : // RangeKeySet, RangeKeyUnset, RangeKeyDelete) with minimal effort.
98 : //
99 : // The same key can be operated on multiple times in a batch, though only the
100 : // latest operation will be visible. For example, Put("a", "b"), Delete("a")
101 : // will cause the key "a" to not be visible in the batch. Put("a", "b"),
102 : // Put("a", "c") will cause a read of "a" to return the value "c".
103 : //
104 : // The batch index is implemented via an skiplist (internal/batchskl). While
105 : // the skiplist implementation is very fast, inserting into an indexed batch is
106 : // significantly slower than inserting into a non-indexed batch. Only use an
107 : // indexed batch if you require reading from it.
108 : //
109 : // # Atomic commit
110 : //
111 : // The operations in a batch are persisted by calling Batch.Commit which is
112 : // equivalent to calling DB.Apply(batch). A batch is committed atomically by
113 : // writing the internal batch representation to the WAL, adding all of the
114 : // batch operations to the memtable associated with the WAL, and then
115 : // incrementing the visible sequence number so that subsequent reads can see
116 : // the effects of the batch operations. If WriteOptions.Sync is true, a call to
117 : // Batch.Commit will guarantee that the batch is persisted to disk before
118 : // returning. See commitPipeline for more on the implementation details.
119 : //
120 : // # Large batches
121 : //
122 : // The size of a batch is limited only by available memory (be aware that
123 : // indexed batches require considerably additional memory for the skiplist
124 : // structure). A given WAL file has a single memtable associated with it (this
125 : // restriction could be removed, but doing so is onerous and complex). And a
126 : // memtable has a fixed size due to the underlying fixed size arena. Note that
127 : // this differs from RocksDB where a memtable can grow arbitrarily large using
128 : // a list of arena chunks. In RocksDB this is accomplished by storing pointers
129 : // in the arena memory, but that isn't possible in Go.
130 : //
131 : // During Batch.Commit, a batch which is larger than a threshold (>
132 : // MemTableSize/2) is wrapped in a flushableBatch and inserted into the queue
133 : // of memtables. A flushableBatch forces WAL to be rotated, but that happens
134 : // anyways when the memtable becomes full so this does not cause significant
135 : // WAL churn. Because the flushableBatch is readable as another layer in the
136 : // LSM, Batch.Commit returns as soon as the flushableBatch has been added to
137 : // the queue of memtables.
138 : //
139 : // Internally, a flushableBatch provides Iterator support by sorting the batch
140 : // contents (the batch is sorted once, when it is added to the memtable
141 : // queue). Sorting the batch contents and insertion of the contents into a
142 : // memtable have the same big-O time, but the constant factor dominates
143 : // here. Sorting is significantly faster and uses significantly less memory.
144 : //
145 : // # Internal representation
146 : //
147 : // The internal batch representation is a contiguous byte buffer with a fixed
148 : // 12-byte header, followed by a series of records.
149 : //
150 : // +-------------+------------+--- ... ---+
151 : // | SeqNum (8B) | Count (4B) | Entries |
152 : // +-------------+------------+--- ... ---+
153 : //
154 : // Each record has a 1-byte kind tag prefix, followed by 1 or 2 length prefixed
155 : // strings (varstring):
156 : //
157 : // +-----------+-----------------+-------------------+
158 : // | Kind (1B) | Key (varstring) | Value (varstring) |
159 : // +-----------+-----------------+-------------------+
160 : //
161 : // A varstring is a varint32 followed by N bytes of data. The Kind tags are
162 : // exactly those specified by InternalKeyKind. The following table shows the
163 : // format for records of each kind:
164 : //
165 : // InternalKeyKindDelete varstring
166 : // InternalKeyKindLogData varstring
167 : // InternalKeyKindIngestSST varstring
168 : // InternalKeyKindSet varstring varstring
169 : // InternalKeyKindMerge varstring varstring
170 : // InternalKeyKindRangeDelete varstring varstring
171 : // InternalKeyKindRangeKeySet varstring varstring
172 : // InternalKeyKindRangeKeyUnset varstring varstring
173 : // InternalKeyKindRangeKeyDelete varstring varstring
174 : //
175 : // The intuitive understanding here are that the arguments to Delete, Set,
176 : // Merge, DeleteRange and RangeKeyDelete are encoded into the batch. The
177 : // RangeKeySet and RangeKeyUnset operations are slightly more complicated,
178 : // encoding their end key, suffix and value [in the case of RangeKeySet] within
179 : // the Value varstring. For more information on the value encoding for
180 : // RangeKeySet and RangeKeyUnset, see the internal/rangekey package.
181 : //
182 : // The internal batch representation is the on disk format for a batch in the
183 : // WAL, and thus stable. New record kinds may be added, but the existing ones
184 : // will not be modified.
185 : type Batch struct {
186 : batchInternal
187 : applied atomic.Bool
188 : }
189 :
190 : // batchInternal contains the set of fields within Batch that are non-atomic and
191 : // capable of being reset using a *b = batchInternal{} struct copy.
192 : type batchInternal struct {
193 : // Data is the wire format of a batch's log entry:
194 : // - 8 bytes for a sequence number of the first batch element,
195 : // or zeroes if the batch has not yet been applied,
196 : // - 4 bytes for the count: the number of elements in the batch,
197 : // or "\xff\xff\xff\xff" if the batch is invalid,
198 : // - count elements, being:
199 : // - one byte for the kind
200 : // - the varint-string user key,
201 : // - the varint-string value (if kind != delete).
202 : // The sequence number and count are stored in little-endian order.
203 : //
204 : // The data field can be (but is not guaranteed to be) nil for new
205 : // batches. Large batches will set the data field to nil when committed as
206 : // the data has been moved to a flushableBatch and inserted into the queue of
207 : // memtables.
208 : data []byte
209 : cmp Compare
210 : formatKey base.FormatKey
211 : abbreviatedKey AbbreviatedKey
212 :
213 : // An upper bound on required space to add this batch to a memtable.
214 : // Note that although batches are limited to 4 GiB in size, that limit
215 : // applies to len(data), not the memtable size. The upper bound on the
216 : // size of a memtable node is larger than the overhead of the batch's log
217 : // encoding, so memTableSize is larger than len(data) and may overflow a
218 : // uint32.
219 : memTableSize uint64
220 :
221 : // The db to which the batch will be committed. Do not change this field
222 : // after the batch has been created as it might invalidate internal state.
223 : // Batch.memTableSize is only refreshed if Batch.db is set. Setting db to
224 : // nil once it has been set implies that the Batch has encountered an error.
225 : db *DB
226 :
227 : // The count of records in the batch. This count will be stored in the batch
228 : // data whenever Repr() is called.
229 : count uint64
230 :
231 : // The count of range deletions in the batch. Updated every time a range
232 : // deletion is added.
233 : countRangeDels uint64
234 :
235 : // The count of range key sets, unsets and deletes in the batch. Updated
236 : // every time a RANGEKEYSET, RANGEKEYUNSET or RANGEKEYDEL key is added.
237 : countRangeKeys uint64
238 :
239 : // A deferredOp struct, stored in the Batch so that a pointer can be returned
240 : // from the *Deferred() methods rather than a value.
241 : deferredOp DeferredBatchOp
242 :
243 : // An optional skiplist keyed by offset into data of the entry.
244 : index *batchskl.Skiplist
245 : rangeDelIndex *batchskl.Skiplist
246 : rangeKeyIndex *batchskl.Skiplist
247 :
248 : // Fragmented range deletion tombstones. Cached the first time a range
249 : // deletion iterator is requested. The cache is invalidated whenever a new
250 : // range deletion is added to the batch. This cache can only be used when
251 : // opening an iterator to read at a batch sequence number >=
252 : // tombstonesSeqNum. This is the case for all new iterators created over a
253 : // batch but it's not the case for all cloned iterators.
254 : tombstones []keyspan.Span
255 : tombstonesSeqNum uint64
256 :
257 : // Fragmented range key spans. Cached the first time a range key iterator is
258 : // requested. The cache is invalidated whenever a new range key
259 : // (RangeKey{Set,Unset,Del}) is added to the batch. This cache can only be
260 : // used when opening an iterator to read at a batch sequence number >=
261 : // tombstonesSeqNum. This is the case for all new iterators created over a
262 : // batch but it's not the case for all cloned iterators.
263 : rangeKeys []keyspan.Span
264 : rangeKeysSeqNum uint64
265 :
266 : // The flushableBatch wrapper if the batch is too large to fit in the
267 : // memtable.
268 : flushable *flushableBatch
269 :
270 : // minimumFormatMajorVersion indicates the format major version required in
271 : // order to commit this batch. If an operation requires a particular format
272 : // major version, it ratchets the batch's minimumFormatMajorVersion. When
273 : // the batch is committed, this is validated against the database's current
274 : // format major version.
275 : minimumFormatMajorVersion FormatMajorVersion
276 :
277 : // Synchronous Apply uses the commit WaitGroup for both publishing the
278 : // seqnum and waiting for the WAL fsync (if needed). Asynchronous
279 : // ApplyNoSyncWait, which implies WriteOptions.Sync is true, uses the commit
280 : // WaitGroup for publishing the seqnum and the fsyncWait WaitGroup for
281 : // waiting for the WAL fsync.
282 : //
283 : // TODO(sumeer): if we find that ApplyNoSyncWait in conjunction with
284 : // SyncWait is causing higher memory usage because of the time duration
285 : // between when the sync is already done, and a goroutine calls SyncWait
286 : // (followed by Batch.Close), we could separate out {fsyncWait, commitErr}
287 : // into a separate struct that is allocated separately (using another
288 : // sync.Pool), and only that struct needs to outlive Batch.Close (which
289 : // could then be called immediately after ApplyNoSyncWait). commitStats
290 : // will also need to be in this separate struct.
291 : commit sync.WaitGroup
292 : fsyncWait sync.WaitGroup
293 :
294 : commitStats BatchCommitStats
295 :
296 : commitErr error
297 :
298 : // Position bools together to reduce the sizeof the struct.
299 :
300 : // ingestedSSTBatch indicates that the batch contains one or more key kinds
301 : // of InternalKeyKindIngestSST. If the batch contains key kinds of IngestSST
302 : // then it will only contain key kinds of IngestSST.
303 : ingestedSSTBatch bool
304 :
305 : // committing is set to true when a batch begins to commit. It's used to
306 : // ensure the batch is not mutated concurrently. It is not an atomic
307 : // deliberately, so as to avoid the overhead on batch mutations. This is
308 : // okay, because under correct usage this field will never be accessed
309 : // concurrently. It's only under incorrect usage the memory accesses of this
310 : // variable may violate memory safety. Since we don't use atomics here,
311 : // false negatives are possible.
312 : committing bool
313 : }
314 :
315 : // BatchCommitStats exposes stats related to committing a batch.
316 : //
317 : // NB: there is no Pebble internal tracing (using LoggerAndTracer) of slow
318 : // batch commits. The caller can use these stats to do their own tracing as
319 : // needed.
320 : type BatchCommitStats struct {
321 : // TotalDuration is the time spent in DB.{Apply,ApplyNoSyncWait} or
322 : // Batch.Commit, plus the time waiting in Batch.SyncWait. If there is a gap
323 : // between calling ApplyNoSyncWait and calling SyncWait, that gap could
324 : // include some duration in which real work was being done for the commit
325 : // and will not be included here. This missing time is considered acceptable
326 : // since the goal of these stats is to understand user-facing latency.
327 : //
328 : // TotalDuration includes time spent in various queues both inside Pebble
329 : // and outside Pebble (I/O queues, goroutine scheduler queue, mutex wait
330 : // etc.). For some of these queues (which we consider important) the wait
331 : // times are included below -- these expose low-level implementation detail
332 : // and are meant for expert diagnosis and subject to change. There may be
333 : // unaccounted time after subtracting those values from TotalDuration.
334 : TotalDuration time.Duration
335 : // SemaphoreWaitDuration is the wait time for semaphores in
336 : // commitPipeline.Commit.
337 : SemaphoreWaitDuration time.Duration
338 : // WALQueueWaitDuration is the wait time for allocating memory blocks in the
339 : // LogWriter (due to the LogWriter not writing fast enough). At the moment
340 : // this is duration is always zero because a single WAL will allow
341 : // allocating memory blocks up to the entire memtable size. In the future,
342 : // we may pipeline WALs and bound the WAL queued blocks separately, so this
343 : // field is preserved for that possibility.
344 : WALQueueWaitDuration time.Duration
345 : // MemTableWriteStallDuration is the wait caused by a write stall due to too
346 : // many memtables (due to not flushing fast enough).
347 : MemTableWriteStallDuration time.Duration
348 : // L0ReadAmpWriteStallDuration is the wait caused by a write stall due to
349 : // high read amplification in L0 (due to not compacting fast enough out of
350 : // L0).
351 : L0ReadAmpWriteStallDuration time.Duration
352 : // WALRotationDuration is the wait time for WAL rotation, which includes
353 : // syncing and closing the old WAL and creating (or reusing) a new one.
354 : WALRotationDuration time.Duration
355 : // CommitWaitDuration is the wait for publishing the seqnum plus the
356 : // duration for the WAL sync (if requested). The former should be tiny and
357 : // one can assume that this is all due to the WAL sync.
358 : CommitWaitDuration time.Duration
359 : }
360 :
361 : var _ Reader = (*Batch)(nil)
362 : var _ Writer = (*Batch)(nil)
363 :
364 : var batchPool = sync.Pool{
365 1 : New: func() interface{} {
366 1 : return &Batch{}
367 1 : },
368 : }
369 :
370 : type indexedBatch struct {
371 : batch Batch
372 : index batchskl.Skiplist
373 : }
374 :
375 : var indexedBatchPool = sync.Pool{
376 1 : New: func() interface{} {
377 1 : return &indexedBatch{}
378 1 : },
379 : }
380 :
381 1 : func newBatch(db *DB) *Batch {
382 1 : b := batchPool.Get().(*Batch)
383 1 : b.db = db
384 1 : return b
385 1 : }
386 :
387 0 : func newBatchWithSize(db *DB, size int) *Batch {
388 0 : b := newBatch(db)
389 0 : if cap(b.data) < size {
390 0 : b.data = rawalloc.New(0, size)
391 0 : }
392 0 : return b
393 : }
394 :
395 1 : func newIndexedBatch(db *DB, comparer *Comparer) *Batch {
396 1 : i := indexedBatchPool.Get().(*indexedBatch)
397 1 : i.batch.cmp = comparer.Compare
398 1 : i.batch.formatKey = comparer.FormatKey
399 1 : i.batch.abbreviatedKey = comparer.AbbreviatedKey
400 1 : i.batch.db = db
401 1 : i.batch.index = &i.index
402 1 : i.batch.index.Init(&i.batch.data, i.batch.cmp, i.batch.abbreviatedKey)
403 1 : return &i.batch
404 1 : }
405 :
406 0 : func newIndexedBatchWithSize(db *DB, comparer *Comparer, size int) *Batch {
407 0 : b := newIndexedBatch(db, comparer)
408 0 : if cap(b.data) < size {
409 0 : b.data = rawalloc.New(0, size)
410 0 : }
411 0 : return b
412 : }
413 :
414 : // nextSeqNum returns the batch "sequence number" that will be given to the next
415 : // key written to the batch. During iteration keys within an indexed batch are
416 : // given a sequence number consisting of their offset within the batch combined
417 : // with the base.InternalKeySeqNumBatch bit. These sequence numbers are only
418 : // used during iteration, and the keys are assigned ordinary sequence numbers
419 : // when the batch is committed.
420 1 : func (b *Batch) nextSeqNum() uint64 {
421 1 : return uint64(len(b.data)) | base.InternalKeySeqNumBatch
422 1 : }
423 :
424 1 : func (b *Batch) release() {
425 1 : if b.db == nil {
426 1 : // The batch was not created using newBatch or newIndexedBatch, or an error
427 1 : // was encountered. We don't try to reuse batches that encountered an error
428 1 : // because they might be stuck somewhere in the system and attempting to
429 1 : // reuse such batches is a recipe for onerous debugging sessions. Instead,
430 1 : // let the GC do its job.
431 1 : return
432 1 : }
433 1 : b.db = nil
434 1 :
435 1 : // NB: This is ugly (it would be cleaner if we could just assign a Batch{}),
436 1 : // but necessary so that we can use atomic.StoreUint32 for the Batch.applied
437 1 : // field. Without using an atomic to clear that field the Go race detector
438 1 : // complains.
439 1 : b.Reset()
440 1 : b.cmp = nil
441 1 : b.formatKey = nil
442 1 : b.abbreviatedKey = nil
443 1 :
444 1 : if b.index == nil {
445 1 : batchPool.Put(b)
446 1 : } else {
447 1 : b.index, b.rangeDelIndex, b.rangeKeyIndex = nil, nil, nil
448 1 : indexedBatchPool.Put((*indexedBatch)(unsafe.Pointer(b)))
449 1 : }
450 : }
451 :
452 1 : func (b *Batch) refreshMemTableSize() {
453 1 : b.memTableSize = 0
454 1 : if len(b.data) < batchHeaderLen {
455 0 : return
456 0 : }
457 :
458 1 : b.countRangeDels = 0
459 1 : b.countRangeKeys = 0
460 1 : b.minimumFormatMajorVersion = 0
461 1 : for r := b.Reader(); ; {
462 1 : kind, key, value, ok := r.Next()
463 1 : if !ok {
464 1 : break
465 : }
466 1 : switch kind {
467 1 : case InternalKeyKindRangeDelete:
468 1 : b.countRangeDels++
469 1 : case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
470 1 : b.countRangeKeys++
471 1 : case InternalKeyKindDeleteSized:
472 1 : if b.minimumFormatMajorVersion < FormatDeleteSizedAndObsolete {
473 1 : b.minimumFormatMajorVersion = FormatDeleteSizedAndObsolete
474 1 : }
475 1 : case InternalKeyKindIngestSST:
476 1 : if b.minimumFormatMajorVersion < FormatFlushableIngest {
477 1 : b.minimumFormatMajorVersion = FormatFlushableIngest
478 1 : }
479 : // This key kind doesn't contribute to the memtable size.
480 1 : continue
481 : }
482 1 : b.memTableSize += memTableEntrySize(len(key), len(value))
483 : }
484 1 : if b.countRangeKeys > 0 && b.minimumFormatMajorVersion < FormatRangeKeys {
485 1 : b.minimumFormatMajorVersion = FormatRangeKeys
486 1 : }
487 : }
488 :
489 : // Apply the operations contained in the batch to the receiver batch.
490 : //
491 : // It is safe to modify the contents of the arguments after Apply returns.
492 1 : func (b *Batch) Apply(batch *Batch, _ *WriteOptions) error {
493 1 : if b.ingestedSSTBatch {
494 0 : panic("pebble: invalid batch application")
495 : }
496 1 : if len(batch.data) == 0 {
497 1 : return nil
498 1 : }
499 1 : if len(batch.data) < batchHeaderLen {
500 0 : return base.CorruptionErrorf("pebble: invalid batch")
501 0 : }
502 :
503 1 : offset := len(b.data)
504 1 : if offset == 0 {
505 1 : b.init(offset)
506 1 : offset = batchHeaderLen
507 1 : }
508 1 : b.data = append(b.data, batch.data[batchHeaderLen:]...)
509 1 :
510 1 : b.setCount(b.Count() + batch.Count())
511 1 :
512 1 : if b.db != nil || b.index != nil {
513 1 : // Only iterate over the new entries if we need to track memTableSize or in
514 1 : // order to update the index.
515 1 : for iter := BatchReader(b.data[offset:]); len(iter) > 0; {
516 1 : offset := uintptr(unsafe.Pointer(&iter[0])) - uintptr(unsafe.Pointer(&b.data[0]))
517 1 : kind, key, value, ok := iter.Next()
518 1 : if !ok {
519 0 : break
520 : }
521 1 : switch kind {
522 0 : case InternalKeyKindRangeDelete:
523 0 : b.countRangeDels++
524 1 : case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
525 1 : b.countRangeKeys++
526 0 : case InternalKeyKindIngestSST:
527 0 : panic("pebble: invalid key kind for batch")
528 : }
529 1 : if b.index != nil {
530 1 : var err error
531 1 : switch kind {
532 0 : case InternalKeyKindRangeDelete:
533 0 : b.tombstones = nil
534 0 : b.tombstonesSeqNum = 0
535 0 : if b.rangeDelIndex == nil {
536 0 : b.rangeDelIndex = batchskl.NewSkiplist(&b.data, b.cmp, b.abbreviatedKey)
537 0 : }
538 0 : err = b.rangeDelIndex.Add(uint32(offset))
539 1 : case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
540 1 : b.rangeKeys = nil
541 1 : b.rangeKeysSeqNum = 0
542 1 : if b.rangeKeyIndex == nil {
543 1 : b.rangeKeyIndex = batchskl.NewSkiplist(&b.data, b.cmp, b.abbreviatedKey)
544 1 : }
545 1 : err = b.rangeKeyIndex.Add(uint32(offset))
546 1 : default:
547 1 : err = b.index.Add(uint32(offset))
548 : }
549 1 : if err != nil {
550 0 : return err
551 0 : }
552 : }
553 1 : b.memTableSize += memTableEntrySize(len(key), len(value))
554 : }
555 : }
556 1 : return nil
557 : }
558 :
559 : // Get gets the value for the given key. It returns ErrNotFound if the Batch
560 : // does not contain the key.
561 : //
562 : // The caller should not modify the contents of the returned slice, but it is
563 : // safe to modify the contents of the argument after Get returns. The returned
564 : // slice will remain valid until the returned Closer is closed. On success, the
565 : // caller MUST call closer.Close() or a memory leak will occur.
566 1 : func (b *Batch) Get(key []byte) ([]byte, io.Closer, error) {
567 1 : if b.index == nil {
568 0 : return nil, nil, ErrNotIndexed
569 0 : }
570 1 : return b.db.getInternal(key, b, nil /* snapshot */)
571 : }
572 :
573 1 : func (b *Batch) prepareDeferredKeyValueRecord(keyLen, valueLen int, kind InternalKeyKind) {
574 1 : if b.committing {
575 0 : panic("pebble: batch already committing")
576 : }
577 1 : if len(b.data) == 0 {
578 1 : b.init(keyLen + valueLen + 2*binary.MaxVarintLen64 + batchHeaderLen)
579 1 : }
580 1 : b.count++
581 1 : b.memTableSize += memTableEntrySize(keyLen, valueLen)
582 1 :
583 1 : pos := len(b.data)
584 1 : b.deferredOp.offset = uint32(pos)
585 1 : b.grow(1 + 2*maxVarintLen32 + keyLen + valueLen)
586 1 : b.data[pos] = byte(kind)
587 1 : pos++
588 1 :
589 1 : {
590 1 : // TODO(peter): Manually inlined version binary.PutUvarint(). This is 20%
591 1 : // faster on BenchmarkBatchSet on go1.13. Remove if go1.14 or future
592 1 : // versions show this to not be a performance win.
593 1 : x := uint32(keyLen)
594 1 : for x >= 0x80 {
595 0 : b.data[pos] = byte(x) | 0x80
596 0 : x >>= 7
597 0 : pos++
598 0 : }
599 1 : b.data[pos] = byte(x)
600 1 : pos++
601 : }
602 :
603 1 : b.deferredOp.Key = b.data[pos : pos+keyLen]
604 1 : pos += keyLen
605 1 :
606 1 : {
607 1 : // TODO(peter): Manually inlined version binary.PutUvarint(). This is 20%
608 1 : // faster on BenchmarkBatchSet on go1.13. Remove if go1.14 or future
609 1 : // versions show this to not be a performance win.
610 1 : x := uint32(valueLen)
611 1 : for x >= 0x80 {
612 0 : b.data[pos] = byte(x) | 0x80
613 0 : x >>= 7
614 0 : pos++
615 0 : }
616 1 : b.data[pos] = byte(x)
617 1 : pos++
618 : }
619 :
620 1 : b.deferredOp.Value = b.data[pos : pos+valueLen]
621 1 : // Shrink data since varints may be shorter than the upper bound.
622 1 : b.data = b.data[:pos+valueLen]
623 : }
624 :
625 1 : func (b *Batch) prepareDeferredKeyRecord(keyLen int, kind InternalKeyKind) {
626 1 : if b.committing {
627 0 : panic("pebble: batch already committing")
628 : }
629 1 : if len(b.data) == 0 {
630 1 : b.init(keyLen + binary.MaxVarintLen64 + batchHeaderLen)
631 1 : }
632 1 : b.count++
633 1 : b.memTableSize += memTableEntrySize(keyLen, 0)
634 1 :
635 1 : pos := len(b.data)
636 1 : b.deferredOp.offset = uint32(pos)
637 1 : b.grow(1 + maxVarintLen32 + keyLen)
638 1 : b.data[pos] = byte(kind)
639 1 : pos++
640 1 :
641 1 : {
642 1 : // TODO(peter): Manually inlined version binary.PutUvarint(). Remove if
643 1 : // go1.13 or future versions show this to not be a performance win. See
644 1 : // BenchmarkBatchSet.
645 1 : x := uint32(keyLen)
646 1 : for x >= 0x80 {
647 0 : b.data[pos] = byte(x) | 0x80
648 0 : x >>= 7
649 0 : pos++
650 0 : }
651 1 : b.data[pos] = byte(x)
652 1 : pos++
653 : }
654 :
655 1 : b.deferredOp.Key = b.data[pos : pos+keyLen]
656 1 : b.deferredOp.Value = nil
657 1 :
658 1 : // Shrink data since varint may be shorter than the upper bound.
659 1 : b.data = b.data[:pos+keyLen]
660 : }
661 :
662 : // AddInternalKey allows the caller to add an internal key of point key kinds to
663 : // a batch. Passing in an internal key of kind RangeKey* or RangeDelete will
664 : // result in a panic. Note that the seqnum in the internal key is effectively
665 : // ignored, even though the Kind is preserved. This is because the batch format
666 : // does not allow for a per-key seqnum to be specified, only a batch-wide one.
667 : //
668 : // Note that non-indexed keys (IngestKeyKind{LogData,IngestSST}) are not
669 : // supported with this method as they require specialized logic.
670 0 : func (b *Batch) AddInternalKey(key *base.InternalKey, value []byte, _ *WriteOptions) error {
671 0 : keyLen := len(key.UserKey)
672 0 : hasValue := false
673 0 : switch key.Kind() {
674 0 : case InternalKeyKindRangeDelete, InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
675 0 : panic("unexpected range delete or range key kind in AddInternalKey")
676 0 : case InternalKeyKindSingleDelete, InternalKeyKindDelete:
677 0 : b.prepareDeferredKeyRecord(len(key.UserKey), key.Kind())
678 0 : default:
679 0 : b.prepareDeferredKeyValueRecord(keyLen, len(value), key.Kind())
680 0 : hasValue = true
681 : }
682 0 : b.deferredOp.index = b.index
683 0 : copy(b.deferredOp.Key, key.UserKey)
684 0 : if hasValue {
685 0 : copy(b.deferredOp.Value, value)
686 0 : }
687 : // TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
688 : // in go1.13 will remove the need for this.
689 0 : if b.index != nil {
690 0 : if err := b.index.Add(b.deferredOp.offset); err != nil {
691 0 : return err
692 0 : }
693 : }
694 0 : return nil
695 : }
696 :
697 : // Set adds an action to the batch that sets the key to map to the value.
698 : //
699 : // It is safe to modify the contents of the arguments after Set returns.
700 1 : func (b *Batch) Set(key, value []byte, _ *WriteOptions) error {
701 1 : deferredOp := b.SetDeferred(len(key), len(value))
702 1 : copy(deferredOp.Key, key)
703 1 : copy(deferredOp.Value, value)
704 1 : // TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
705 1 : // in go1.13 will remove the need for this.
706 1 : if b.index != nil {
707 1 : if err := b.index.Add(deferredOp.offset); err != nil {
708 0 : return err
709 0 : }
710 : }
711 1 : return nil
712 : }
713 :
714 : // SetDeferred is similar to Set in that it adds a set operation to the batch,
715 : // except it only takes in key/value lengths instead of complete slices,
716 : // letting the caller encode into those objects and then call Finish() on the
717 : // returned object.
718 1 : func (b *Batch) SetDeferred(keyLen, valueLen int) *DeferredBatchOp {
719 1 : b.prepareDeferredKeyValueRecord(keyLen, valueLen, InternalKeyKindSet)
720 1 : b.deferredOp.index = b.index
721 1 : return &b.deferredOp
722 1 : }
723 :
724 : // Merge adds an action to the batch that merges the value at key with the new
725 : // value. The details of the merge are dependent upon the configured merge
726 : // operator.
727 : //
728 : // It is safe to modify the contents of the arguments after Merge returns.
729 1 : func (b *Batch) Merge(key, value []byte, _ *WriteOptions) error {
730 1 : deferredOp := b.MergeDeferred(len(key), len(value))
731 1 : copy(deferredOp.Key, key)
732 1 : copy(deferredOp.Value, value)
733 1 : // TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
734 1 : // in go1.13 will remove the need for this.
735 1 : if b.index != nil {
736 1 : if err := b.index.Add(deferredOp.offset); err != nil {
737 0 : return err
738 0 : }
739 : }
740 1 : return nil
741 : }
742 :
743 : // MergeDeferred is similar to Merge in that it adds a merge operation to the
744 : // batch, except it only takes in key/value lengths instead of complete slices,
745 : // letting the caller encode into those objects and then call Finish() on the
746 : // returned object.
747 1 : func (b *Batch) MergeDeferred(keyLen, valueLen int) *DeferredBatchOp {
748 1 : b.prepareDeferredKeyValueRecord(keyLen, valueLen, InternalKeyKindMerge)
749 1 : b.deferredOp.index = b.index
750 1 : return &b.deferredOp
751 1 : }
752 :
753 : // Delete adds an action to the batch that deletes the entry for key.
754 : //
755 : // It is safe to modify the contents of the arguments after Delete returns.
756 1 : func (b *Batch) Delete(key []byte, _ *WriteOptions) error {
757 1 : deferredOp := b.DeleteDeferred(len(key))
758 1 : copy(deferredOp.Key, key)
759 1 : // TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
760 1 : // in go1.13 will remove the need for this.
761 1 : if b.index != nil {
762 1 : if err := b.index.Add(deferredOp.offset); err != nil {
763 0 : return err
764 0 : }
765 : }
766 1 : return nil
767 : }
768 :
769 : // DeleteDeferred is similar to Delete in that it adds a delete operation to
770 : // the batch, except it only takes in key/value lengths instead of complete
771 : // slices, letting the caller encode into those objects and then call Finish()
772 : // on the returned object.
773 1 : func (b *Batch) DeleteDeferred(keyLen int) *DeferredBatchOp {
774 1 : b.prepareDeferredKeyRecord(keyLen, InternalKeyKindDelete)
775 1 : b.deferredOp.index = b.index
776 1 : return &b.deferredOp
777 1 : }
778 :
779 : // DeleteSized behaves identically to Delete, but takes an additional
780 : // argument indicating the size of the value being deleted. DeleteSized
781 : // should be preferred when the caller has the expectation that there exists
782 : // a single internal KV pair for the key (eg, the key has not been
783 : // overwritten recently), and the caller knows the size of its value.
784 : //
785 : // DeleteSized will record the value size within the tombstone and use it to
786 : // inform compaction-picking heuristics which strive to reduce space
787 : // amplification in the LSM. This "calling your shot" mechanic allows the
788 : // storage engine to more accurately estimate and reduce space amplification.
789 : //
790 : // It is safe to modify the contents of the arguments after DeleteSized
791 : // returns.
792 1 : func (b *Batch) DeleteSized(key []byte, deletedValueSize uint32, _ *WriteOptions) error {
793 1 : deferredOp := b.DeleteSizedDeferred(len(key), deletedValueSize)
794 1 : copy(b.deferredOp.Key, key)
795 1 : // TODO(peter): Manually inline DeferredBatchOp.Finish(). Check if in a
796 1 : // later Go release this is unnecessary.
797 1 : if b.index != nil {
798 1 : if err := b.index.Add(deferredOp.offset); err != nil {
799 0 : return err
800 0 : }
801 : }
802 1 : return nil
803 : }
804 :
805 : // DeleteSizedDeferred is similar to DeleteSized in that it adds a sized delete
806 : // operation to the batch, except it only takes in key length instead of a
807 : // complete key slice, letting the caller encode into the DeferredBatchOp.Key
808 : // slice and then call Finish() on the returned object.
809 1 : func (b *Batch) DeleteSizedDeferred(keyLen int, deletedValueSize uint32) *DeferredBatchOp {
810 1 : if b.minimumFormatMajorVersion < FormatDeleteSizedAndObsolete {
811 1 : b.minimumFormatMajorVersion = FormatDeleteSizedAndObsolete
812 1 : }
813 :
814 : // Encode the sum of the key length and the value in the value.
815 1 : v := uint64(deletedValueSize) + uint64(keyLen)
816 1 :
817 1 : // Encode `v` as a varint.
818 1 : var buf [binary.MaxVarintLen64]byte
819 1 : n := 0
820 1 : {
821 1 : x := v
822 1 : for x >= 0x80 {
823 0 : buf[n] = byte(x) | 0x80
824 0 : x >>= 7
825 0 : n++
826 0 : }
827 1 : buf[n] = byte(x)
828 1 : n++
829 : }
830 :
831 : // NB: In batch entries and sstable entries, values are stored as
832 : // varstrings. Here, the value is itself a simple varint. This results in an
833 : // unnecessary double layer of encoding:
834 : // varint(n) varint(deletedValueSize)
835 : // The first varint will always be 1-byte, since a varint-encoded uint64
836 : // will never exceed 128 bytes. This unnecessary extra byte and wrapping is
837 : // preserved to avoid special casing across the database, and in particular
838 : // in sstable block decoding which is performance sensitive.
839 1 : b.prepareDeferredKeyValueRecord(keyLen, n, InternalKeyKindDeleteSized)
840 1 : b.deferredOp.index = b.index
841 1 : copy(b.deferredOp.Value, buf[:n])
842 1 : return &b.deferredOp
843 : }
844 :
845 : // SingleDelete adds an action to the batch that single deletes the entry for key.
846 : // See Writer.SingleDelete for more details on the semantics of SingleDelete.
847 : //
848 : // It is safe to modify the contents of the arguments after SingleDelete returns.
849 1 : func (b *Batch) SingleDelete(key []byte, _ *WriteOptions) error {
850 1 : deferredOp := b.SingleDeleteDeferred(len(key))
851 1 : copy(deferredOp.Key, key)
852 1 : // TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
853 1 : // in go1.13 will remove the need for this.
854 1 : if b.index != nil {
855 1 : if err := b.index.Add(deferredOp.offset); err != nil {
856 0 : return err
857 0 : }
858 : }
859 1 : return nil
860 : }
861 :
862 : // SingleDeleteDeferred is similar to SingleDelete in that it adds a single delete
863 : // operation to the batch, except it only takes in key/value lengths instead of
864 : // complete slices, letting the caller encode into those objects and then call
865 : // Finish() on the returned object.
866 1 : func (b *Batch) SingleDeleteDeferred(keyLen int) *DeferredBatchOp {
867 1 : b.prepareDeferredKeyRecord(keyLen, InternalKeyKindSingleDelete)
868 1 : b.deferredOp.index = b.index
869 1 : return &b.deferredOp
870 1 : }
871 :
872 : // DeleteRange deletes all of the point keys (and values) in the range
873 : // [start,end) (inclusive on start, exclusive on end). DeleteRange does NOT
874 : // delete overlapping range keys (eg, keys set via RangeKeySet).
875 : //
876 : // It is safe to modify the contents of the arguments after DeleteRange
877 : // returns.
878 1 : func (b *Batch) DeleteRange(start, end []byte, _ *WriteOptions) error {
879 1 : deferredOp := b.DeleteRangeDeferred(len(start), len(end))
880 1 : copy(deferredOp.Key, start)
881 1 : copy(deferredOp.Value, end)
882 1 : // TODO(peter): Manually inline DeferredBatchOp.Finish(). Mid-stack inlining
883 1 : // in go1.13 will remove the need for this.
884 1 : if deferredOp.index != nil {
885 1 : if err := deferredOp.index.Add(deferredOp.offset); err != nil {
886 0 : return err
887 0 : }
888 : }
889 1 : return nil
890 : }
891 :
892 : // DeleteRangeDeferred is similar to DeleteRange in that it adds a delete range
893 : // operation to the batch, except it only takes in key lengths instead of
894 : // complete slices, letting the caller encode into those objects and then call
895 : // Finish() on the returned object. Note that DeferredBatchOp.Key should be
896 : // populated with the start key, and DeferredBatchOp.Value should be populated
897 : // with the end key.
898 1 : func (b *Batch) DeleteRangeDeferred(startLen, endLen int) *DeferredBatchOp {
899 1 : b.prepareDeferredKeyValueRecord(startLen, endLen, InternalKeyKindRangeDelete)
900 1 : b.countRangeDels++
901 1 : if b.index != nil {
902 1 : b.tombstones = nil
903 1 : b.tombstonesSeqNum = 0
904 1 : // Range deletions are rare, so we lazily allocate the index for them.
905 1 : if b.rangeDelIndex == nil {
906 1 : b.rangeDelIndex = batchskl.NewSkiplist(&b.data, b.cmp, b.abbreviatedKey)
907 1 : }
908 1 : b.deferredOp.index = b.rangeDelIndex
909 : }
910 1 : return &b.deferredOp
911 : }
912 :
913 : // RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
914 : // timestamp suffix to value. The suffix is optional. If any portion of the key
915 : // range [start, end) is already set by a range key with the same suffix value,
916 : // RangeKeySet overrides it.
917 : //
918 : // It is safe to modify the contents of the arguments after RangeKeySet returns.
919 1 : func (b *Batch) RangeKeySet(start, end, suffix, value []byte, _ *WriteOptions) error {
920 1 : suffixValues := [1]rangekey.SuffixValue{{Suffix: suffix, Value: value}}
921 1 : internalValueLen := rangekey.EncodedSetValueLen(end, suffixValues[:])
922 1 :
923 1 : deferredOp := b.rangeKeySetDeferred(len(start), internalValueLen)
924 1 : copy(deferredOp.Key, start)
925 1 : n := rangekey.EncodeSetValue(deferredOp.Value, end, suffixValues[:])
926 1 : if n != internalValueLen {
927 0 : panic("unexpected internal value length mismatch")
928 : }
929 :
930 : // Manually inline DeferredBatchOp.Finish().
931 1 : if deferredOp.index != nil {
932 1 : if err := deferredOp.index.Add(deferredOp.offset); err != nil {
933 0 : return err
934 0 : }
935 : }
936 1 : return nil
937 : }
938 :
939 1 : func (b *Batch) rangeKeySetDeferred(startLen, internalValueLen int) *DeferredBatchOp {
940 1 : b.prepareDeferredKeyValueRecord(startLen, internalValueLen, InternalKeyKindRangeKeySet)
941 1 : b.incrementRangeKeysCount()
942 1 : return &b.deferredOp
943 1 : }
944 :
945 1 : func (b *Batch) incrementRangeKeysCount() {
946 1 : b.countRangeKeys++
947 1 : if b.minimumFormatMajorVersion < FormatRangeKeys {
948 1 : b.minimumFormatMajorVersion = FormatRangeKeys
949 1 : }
950 1 : if b.index != nil {
951 1 : b.rangeKeys = nil
952 1 : b.rangeKeysSeqNum = 0
953 1 : // Range keys are rare, so we lazily allocate the index for them.
954 1 : if b.rangeKeyIndex == nil {
955 1 : b.rangeKeyIndex = batchskl.NewSkiplist(&b.data, b.cmp, b.abbreviatedKey)
956 1 : }
957 1 : b.deferredOp.index = b.rangeKeyIndex
958 : }
959 : }
960 :
961 : // RangeKeyUnset removes a range key mapping the key range [start, end) at the
962 : // MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
963 : // range key. RangeKeyUnset only removes portions of range keys that fall within
964 : // the [start, end) key span, and only range keys with suffixes that exactly
965 : // match the unset suffix.
966 : //
967 : // It is safe to modify the contents of the arguments after RangeKeyUnset
968 : // returns.
969 1 : func (b *Batch) RangeKeyUnset(start, end, suffix []byte, _ *WriteOptions) error {
970 1 : suffixes := [1][]byte{suffix}
971 1 : internalValueLen := rangekey.EncodedUnsetValueLen(end, suffixes[:])
972 1 :
973 1 : deferredOp := b.rangeKeyUnsetDeferred(len(start), internalValueLen)
974 1 : copy(deferredOp.Key, start)
975 1 : n := rangekey.EncodeUnsetValue(deferredOp.Value, end, suffixes[:])
976 1 : if n != internalValueLen {
977 0 : panic("unexpected internal value length mismatch")
978 : }
979 :
980 : // Manually inline DeferredBatchOp.Finish()
981 1 : if deferredOp.index != nil {
982 1 : if err := deferredOp.index.Add(deferredOp.offset); err != nil {
983 0 : return err
984 0 : }
985 : }
986 1 : return nil
987 : }
988 :
989 1 : func (b *Batch) rangeKeyUnsetDeferred(startLen, internalValueLen int) *DeferredBatchOp {
990 1 : b.prepareDeferredKeyValueRecord(startLen, internalValueLen, InternalKeyKindRangeKeyUnset)
991 1 : b.incrementRangeKeysCount()
992 1 : return &b.deferredOp
993 1 : }
994 :
995 : // RangeKeyDelete deletes all of the range keys in the range [start,end)
996 : // (inclusive on start, exclusive on end). It does not delete point keys (for
997 : // that use DeleteRange). RangeKeyDelete removes all range keys within the
998 : // bounds, including those with or without suffixes.
999 : //
1000 : // It is safe to modify the contents of the arguments after RangeKeyDelete
1001 : // returns.
1002 1 : func (b *Batch) RangeKeyDelete(start, end []byte, _ *WriteOptions) error {
1003 1 : deferredOp := b.RangeKeyDeleteDeferred(len(start), len(end))
1004 1 : copy(deferredOp.Key, start)
1005 1 : copy(deferredOp.Value, end)
1006 1 : // Manually inline DeferredBatchOp.Finish().
1007 1 : if deferredOp.index != nil {
1008 1 : if err := deferredOp.index.Add(deferredOp.offset); err != nil {
1009 0 : return err
1010 0 : }
1011 : }
1012 1 : return nil
1013 : }
1014 :
1015 : // RangeKeyDeleteDeferred is similar to RangeKeyDelete in that it adds an
1016 : // operation to delete range keys to the batch, except it only takes in key
1017 : // lengths instead of complete slices, letting the caller encode into those
1018 : // objects and then call Finish() on the returned object. Note that
1019 : // DeferredBatchOp.Key should be populated with the start key, and
1020 : // DeferredBatchOp.Value should be populated with the end key.
1021 1 : func (b *Batch) RangeKeyDeleteDeferred(startLen, endLen int) *DeferredBatchOp {
1022 1 : b.prepareDeferredKeyValueRecord(startLen, endLen, InternalKeyKindRangeKeyDelete)
1023 1 : b.incrementRangeKeysCount()
1024 1 : return &b.deferredOp
1025 1 : }
1026 :
1027 : // LogData adds the specified to the batch. The data will be written to the
1028 : // WAL, but not added to memtables or sstables. Log data is never indexed,
1029 : // which makes it useful for testing WAL performance.
1030 : //
1031 : // It is safe to modify the contents of the argument after LogData returns.
1032 0 : func (b *Batch) LogData(data []byte, _ *WriteOptions) error {
1033 0 : origCount, origMemTableSize := b.count, b.memTableSize
1034 0 : b.prepareDeferredKeyRecord(len(data), InternalKeyKindLogData)
1035 0 : copy(b.deferredOp.Key, data)
1036 0 : // Since LogData only writes to the WAL and does not affect the memtable, we
1037 0 : // restore b.count and b.memTableSize to their origin values. Note that
1038 0 : // Batch.count only refers to records that are added to the memtable.
1039 0 : b.count, b.memTableSize = origCount, origMemTableSize
1040 0 : return nil
1041 0 : }
1042 :
1043 : // IngestSST adds the FileNum for an sstable to the batch. The data will only be
1044 : // written to the WAL (not added to memtables or sstables).
1045 1 : func (b *Batch) ingestSST(fileNum base.FileNum) {
1046 1 : if b.Empty() {
1047 1 : b.ingestedSSTBatch = true
1048 1 : } else if !b.ingestedSSTBatch {
1049 0 : // Batch contains other key kinds.
1050 0 : panic("pebble: invalid call to ingestSST")
1051 : }
1052 :
1053 1 : origMemTableSize := b.memTableSize
1054 1 : var buf [binary.MaxVarintLen64]byte
1055 1 : length := binary.PutUvarint(buf[:], uint64(fileNum))
1056 1 : b.prepareDeferredKeyRecord(length, InternalKeyKindIngestSST)
1057 1 : copy(b.deferredOp.Key, buf[:length])
1058 1 : // Since IngestSST writes only to the WAL and does not affect the memtable,
1059 1 : // we restore b.memTableSize to its original value. Note that Batch.count
1060 1 : // is not reset because for the InternalKeyKindIngestSST the count is the
1061 1 : // number of sstable paths which have been added to the batch.
1062 1 : b.memTableSize = origMemTableSize
1063 1 : b.minimumFormatMajorVersion = FormatFlushableIngest
1064 : }
1065 :
1066 : // Empty returns true if the batch is empty, and false otherwise.
1067 1 : func (b *Batch) Empty() bool {
1068 1 : return len(b.data) <= batchHeaderLen
1069 1 : }
1070 :
1071 : // Len returns the current size of the batch in bytes.
1072 0 : func (b *Batch) Len() int {
1073 0 : if len(b.data) <= batchHeaderLen {
1074 0 : return batchHeaderLen
1075 0 : }
1076 0 : return len(b.data)
1077 : }
1078 :
1079 : // Repr returns the underlying batch representation. It is not safe to modify
1080 : // the contents. Reset() will not change the contents of the returned value,
1081 : // though any other mutation operation may do so.
1082 1 : func (b *Batch) Repr() []byte {
1083 1 : if len(b.data) == 0 {
1084 0 : b.init(batchHeaderLen)
1085 0 : }
1086 1 : binary.LittleEndian.PutUint32(b.countData(), b.Count())
1087 1 : return b.data
1088 : }
1089 :
1090 : // SetRepr sets the underlying batch representation. The batch takes ownership
1091 : // of the supplied slice. It is not safe to modify it afterwards until the
1092 : // Batch is no longer in use.
1093 1 : func (b *Batch) SetRepr(data []byte) error {
1094 1 : if len(data) < batchHeaderLen {
1095 0 : return base.CorruptionErrorf("invalid batch")
1096 0 : }
1097 1 : b.data = data
1098 1 : b.count = uint64(binary.LittleEndian.Uint32(b.countData()))
1099 1 : if b.db != nil {
1100 1 : // Only track memTableSize for batches that will be committed to the DB.
1101 1 : b.refreshMemTableSize()
1102 1 : }
1103 1 : return nil
1104 : }
1105 :
1106 : // NewIter returns an iterator that is unpositioned (Iterator.Valid() will
1107 : // return false). The iterator can be positioned via a call to SeekGE,
1108 : // SeekPrefixGE, SeekLT, First or Last. Only indexed batches support iterators.
1109 : //
1110 : // The returned Iterator observes all of the Batch's existing mutations, but no
1111 : // later mutations. Its view can be refreshed via RefreshBatchSnapshot or
1112 : // SetOptions().
1113 1 : func (b *Batch) NewIter(o *IterOptions) (*Iterator, error) {
1114 1 : return b.NewIterWithContext(context.Background(), o)
1115 1 : }
1116 :
1117 : // NewIterWithContext is like NewIter, and additionally accepts a context for
1118 : // tracing.
1119 1 : func (b *Batch) NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error) {
1120 1 : if b.index == nil {
1121 0 : return &Iterator{err: ErrNotIndexed}, nil
1122 0 : }
1123 1 : return b.db.newIter(ctx, b, newIterOpts{}, o), nil
1124 : }
1125 :
1126 : // NewBatchOnlyIter constructs an iterator that only reads the contents of the
1127 : // batch, and does not overlay the batch mutations on top of the DB state.
1128 : //
1129 : // The returned Iterator observes all of the Batch's existing mutations, but
1130 : // no later mutations. Its view can be refreshed via RefreshBatchSnapshot or
1131 : // SetOptions().
1132 0 : func (b *Batch) NewBatchOnlyIter(ctx context.Context, o *IterOptions) (*Iterator, error) {
1133 0 : if b.index == nil {
1134 0 : return &Iterator{err: ErrNotIndexed}, nil
1135 0 : }
1136 0 : return b.db.newIter(ctx, b, newIterOpts{batch: batchIterOpts{batchOnly: true}}, o), nil
1137 : }
1138 :
1139 : // newInternalIter creates a new internalIterator that iterates over the
1140 : // contents of the batch.
1141 1 : func (b *Batch) newInternalIter(o *IterOptions) *batchIter {
1142 1 : iter := &batchIter{}
1143 1 : b.initInternalIter(o, iter)
1144 1 : return iter
1145 1 : }
1146 :
1147 1 : func (b *Batch) initInternalIter(o *IterOptions, iter *batchIter) {
1148 1 : *iter = batchIter{
1149 1 : cmp: b.cmp,
1150 1 : batch: b,
1151 1 : iter: b.index.NewIter(o.GetLowerBound(), o.GetUpperBound()),
1152 1 : // NB: We explicitly do not propagate the batch snapshot to the point
1153 1 : // key iterator. Filtering point keys within the batch iterator can
1154 1 : // cause pathological behavior where a batch iterator advances
1155 1 : // significantly farther than necessary filtering many batch keys that
1156 1 : // are not visible at the batch sequence number. Instead, the merging
1157 1 : // iterator enforces bounds.
1158 1 : //
1159 1 : // For example, consider an engine that contains the committed keys
1160 1 : // 'bar' and 'bax', with no keys between them. Consider a batch
1161 1 : // containing keys 1,000 keys within the range [a,z]. All of the
1162 1 : // batch keys were added to the batch after the iterator was
1163 1 : // constructed, so they are not visible to the iterator. A call to
1164 1 : // SeekGE('bax') would seek the LSM iterators and discover the key
1165 1 : // 'bax'. It would also seek the batch iterator, landing on the key
1166 1 : // 'baz' but discover it that it's not visible. The batch iterator would
1167 1 : // next through the rest of the batch's keys, only to discover there are
1168 1 : // no visible keys greater than or equal to 'bax'.
1169 1 : //
1170 1 : // Filtering these batch points within the merging iterator ensures that
1171 1 : // the batch iterator never needs to iterate beyond 'baz', because it
1172 1 : // already found a smaller, visible key 'bax'.
1173 1 : snapshot: base.InternalKeySeqNumMax,
1174 1 : }
1175 1 : }
1176 :
1177 1 : func (b *Batch) newRangeDelIter(o *IterOptions, batchSnapshot uint64) *keyspan.Iter {
1178 1 : // Construct an iterator even if rangeDelIndex is nil, because it is allowed
1179 1 : // to refresh later, so we need the container to exist.
1180 1 : iter := new(keyspan.Iter)
1181 1 : b.initRangeDelIter(o, iter, batchSnapshot)
1182 1 : return iter
1183 1 : }
1184 :
1185 1 : func (b *Batch) initRangeDelIter(_ *IterOptions, iter *keyspan.Iter, batchSnapshot uint64) {
1186 1 : if b.rangeDelIndex == nil {
1187 1 : iter.Init(b.cmp, nil)
1188 1 : return
1189 1 : }
1190 :
1191 : // Fragment the range tombstones the first time a range deletion iterator is
1192 : // requested. The cached tombstones are invalidated if another range
1193 : // deletion tombstone is added to the batch. This cache is only guaranteed
1194 : // to be correct if we're opening an iterator to read at a batch sequence
1195 : // number at least as high as tombstonesSeqNum. The cache is guaranteed to
1196 : // include all tombstones up to tombstonesSeqNum, and if any additional
1197 : // tombstones were added after that sequence number the cache would've been
1198 : // cleared.
1199 1 : nextSeqNum := b.nextSeqNum()
1200 1 : if b.tombstones != nil && b.tombstonesSeqNum <= batchSnapshot {
1201 1 : iter.Init(b.cmp, b.tombstones)
1202 1 : return
1203 1 : }
1204 :
1205 1 : tombstones := make([]keyspan.Span, 0, b.countRangeDels)
1206 1 : frag := &keyspan.Fragmenter{
1207 1 : Cmp: b.cmp,
1208 1 : Format: b.formatKey,
1209 1 : Emit: func(s keyspan.Span) {
1210 1 : tombstones = append(tombstones, s)
1211 1 : },
1212 : }
1213 1 : it := &batchIter{
1214 1 : cmp: b.cmp,
1215 1 : batch: b,
1216 1 : iter: b.rangeDelIndex.NewIter(nil, nil),
1217 1 : snapshot: batchSnapshot,
1218 1 : }
1219 1 : fragmentRangeDels(frag, it, int(b.countRangeDels))
1220 1 : iter.Init(b.cmp, tombstones)
1221 1 :
1222 1 : // If we just read all the tombstones in the batch (eg, batchSnapshot was
1223 1 : // set to b.nextSeqNum()), then cache the tombstones so that a subsequent
1224 1 : // call to initRangeDelIter may use them without refragmenting.
1225 1 : if nextSeqNum == batchSnapshot {
1226 1 : b.tombstones = tombstones
1227 1 : b.tombstonesSeqNum = nextSeqNum
1228 1 : }
1229 : }
1230 :
1231 1 : func fragmentRangeDels(frag *keyspan.Fragmenter, it internalIterator, count int) {
1232 1 : // The memory management here is a bit subtle. The keys and values returned
1233 1 : // by the iterator are slices in Batch.data. Thus the fragmented tombstones
1234 1 : // are slices within Batch.data. If additional entries are added to the
1235 1 : // Batch, Batch.data may be reallocated. The references in the fragmented
1236 1 : // tombstones will remain valid, pointing into the old Batch.data. GC for
1237 1 : // the win.
1238 1 :
1239 1 : // Use a single []keyspan.Key buffer to avoid allocating many
1240 1 : // individual []keyspan.Key slices with a single element each.
1241 1 : keyBuf := make([]keyspan.Key, 0, count)
1242 1 : for key, val := it.First(); key != nil; key, val = it.Next() {
1243 1 : s := rangedel.Decode(*key, val.InPlaceValue(), keyBuf)
1244 1 : keyBuf = s.Keys[len(s.Keys):]
1245 1 :
1246 1 : // Set a fixed capacity to avoid accidental overwriting.
1247 1 : s.Keys = s.Keys[:len(s.Keys):len(s.Keys)]
1248 1 : frag.Add(s)
1249 1 : }
1250 1 : frag.Finish()
1251 : }
1252 :
1253 1 : func (b *Batch) newRangeKeyIter(o *IterOptions, batchSnapshot uint64) *keyspan.Iter {
1254 1 : // Construct an iterator even if rangeKeyIndex is nil, because it is allowed
1255 1 : // to refresh later, so we need the container to exist.
1256 1 : iter := new(keyspan.Iter)
1257 1 : b.initRangeKeyIter(o, iter, batchSnapshot)
1258 1 : return iter
1259 1 : }
1260 :
1261 1 : func (b *Batch) initRangeKeyIter(_ *IterOptions, iter *keyspan.Iter, batchSnapshot uint64) {
1262 1 : if b.rangeKeyIndex == nil {
1263 1 : iter.Init(b.cmp, nil)
1264 1 : return
1265 1 : }
1266 :
1267 : // Fragment the range keys the first time a range key iterator is requested.
1268 : // The cached spans are invalidated if another range key is added to the
1269 : // batch. This cache is only guaranteed to be correct if we're opening an
1270 : // iterator to read at a batch sequence number at least as high as
1271 : // rangeKeysSeqNum. The cache is guaranteed to include all range keys up to
1272 : // rangeKeysSeqNum, and if any additional range keys were added after that
1273 : // sequence number the cache would've been cleared.
1274 1 : nextSeqNum := b.nextSeqNum()
1275 1 : if b.rangeKeys != nil && b.rangeKeysSeqNum <= batchSnapshot {
1276 1 : iter.Init(b.cmp, b.rangeKeys)
1277 1 : return
1278 1 : }
1279 :
1280 1 : rangeKeys := make([]keyspan.Span, 0, b.countRangeKeys)
1281 1 : frag := &keyspan.Fragmenter{
1282 1 : Cmp: b.cmp,
1283 1 : Format: b.formatKey,
1284 1 : Emit: func(s keyspan.Span) {
1285 1 : rangeKeys = append(rangeKeys, s)
1286 1 : },
1287 : }
1288 1 : it := &batchIter{
1289 1 : cmp: b.cmp,
1290 1 : batch: b,
1291 1 : iter: b.rangeKeyIndex.NewIter(nil, nil),
1292 1 : snapshot: batchSnapshot,
1293 1 : }
1294 1 : fragmentRangeKeys(frag, it, int(b.countRangeKeys))
1295 1 : iter.Init(b.cmp, rangeKeys)
1296 1 :
1297 1 : // If we just read all the range keys in the batch (eg, batchSnapshot was
1298 1 : // set to b.nextSeqNum()), then cache the range keys so that a subsequent
1299 1 : // call to initRangeKeyIter may use them without refragmenting.
1300 1 : if nextSeqNum == batchSnapshot {
1301 1 : b.rangeKeys = rangeKeys
1302 1 : b.rangeKeysSeqNum = nextSeqNum
1303 1 : }
1304 : }
1305 :
1306 1 : func fragmentRangeKeys(frag *keyspan.Fragmenter, it internalIterator, count int) error {
1307 1 : // The memory management here is a bit subtle. The keys and values
1308 1 : // returned by the iterator are slices in Batch.data. Thus the
1309 1 : // fragmented key spans are slices within Batch.data. If additional
1310 1 : // entries are added to the Batch, Batch.data may be reallocated. The
1311 1 : // references in the fragmented keys will remain valid, pointing into
1312 1 : // the old Batch.data. GC for the win.
1313 1 :
1314 1 : // Use a single []keyspan.Key buffer to avoid allocating many
1315 1 : // individual []keyspan.Key slices with a single element each.
1316 1 : keyBuf := make([]keyspan.Key, 0, count)
1317 1 : for ik, val := it.First(); ik != nil; ik, val = it.Next() {
1318 1 : s, err := rangekey.Decode(*ik, val.InPlaceValue(), keyBuf)
1319 1 : if err != nil {
1320 0 : return err
1321 0 : }
1322 1 : keyBuf = s.Keys[len(s.Keys):]
1323 1 :
1324 1 : // Set a fixed capacity to avoid accidental overwriting.
1325 1 : s.Keys = s.Keys[:len(s.Keys):len(s.Keys)]
1326 1 : frag.Add(s)
1327 : }
1328 1 : frag.Finish()
1329 1 : return nil
1330 : }
1331 :
1332 : // Commit applies the batch to its parent writer.
1333 1 : func (b *Batch) Commit(o *WriteOptions) error {
1334 1 : return b.db.Apply(b, o)
1335 1 : }
1336 :
1337 : // Close closes the batch without committing it.
1338 1 : func (b *Batch) Close() error {
1339 1 : b.release()
1340 1 : return nil
1341 1 : }
1342 :
1343 : // Indexed returns true if the batch is indexed (i.e. supports read
1344 : // operations).
1345 1 : func (b *Batch) Indexed() bool {
1346 1 : return b.index != nil
1347 1 : }
1348 :
1349 : // init ensures that the batch data slice is initialized to meet the
1350 : // minimum required size and allocates space for the batch header.
1351 1 : func (b *Batch) init(size int) {
1352 1 : n := batchInitialSize
1353 1 : for n < size {
1354 0 : n *= 2
1355 0 : }
1356 1 : if cap(b.data) < n {
1357 1 : b.data = rawalloc.New(batchHeaderLen, n)
1358 1 : }
1359 1 : b.data = b.data[:batchHeaderLen]
1360 1 : clear(b.data) // Zero the sequence number in the header
1361 : }
1362 :
1363 : // Reset resets the batch for reuse. The underlying byte slice (that is
1364 : // returned by Repr()) may not be modified. It is only necessary to call this
1365 : // method if a batch is explicitly being reused. Close automatically takes are
1366 : // of releasing resources when appropriate for batches that are internally
1367 : // being reused.
1368 1 : func (b *Batch) Reset() {
1369 1 : // Zero out the struct, retaining only the fields necessary for manual
1370 1 : // reuse.
1371 1 : b.batchInternal = batchInternal{
1372 1 : data: b.data,
1373 1 : cmp: b.cmp,
1374 1 : formatKey: b.formatKey,
1375 1 : abbreviatedKey: b.abbreviatedKey,
1376 1 : index: b.index,
1377 1 : db: b.db,
1378 1 : }
1379 1 : b.applied.Store(false)
1380 1 : if b.data != nil {
1381 1 : if cap(b.data) > batchMaxRetainedSize {
1382 0 : // If the capacity of the buffer is larger than our maximum
1383 0 : // retention size, don't re-use it. Let it be GC-ed instead.
1384 0 : // This prevents the memory from an unusually large batch from
1385 0 : // being held on to indefinitely.
1386 0 : b.data = nil
1387 1 : } else {
1388 1 : // Otherwise, reset the buffer for re-use.
1389 1 : b.data = b.data[:batchHeaderLen]
1390 1 : clear(b.data)
1391 1 : }
1392 : }
1393 1 : if b.index != nil {
1394 1 : b.index.Init(&b.data, b.cmp, b.abbreviatedKey)
1395 1 : }
1396 : }
1397 :
1398 : // seqNumData returns the 8 byte little-endian sequence number. Zero means that
1399 : // the batch has not yet been applied.
1400 1 : func (b *Batch) seqNumData() []byte {
1401 1 : return b.data[:8]
1402 1 : }
1403 :
1404 : // countData returns the 4 byte little-endian count data. "\xff\xff\xff\xff"
1405 : // means that the batch is invalid.
1406 1 : func (b *Batch) countData() []byte {
1407 1 : return b.data[8:12]
1408 1 : }
1409 :
1410 1 : func (b *Batch) grow(n int) {
1411 1 : newSize := len(b.data) + n
1412 1 : if uint64(newSize) >= maxBatchSize {
1413 0 : panic(ErrBatchTooLarge)
1414 : }
1415 1 : if newSize > cap(b.data) {
1416 0 : newCap := 2 * cap(b.data)
1417 0 : for newCap < newSize {
1418 0 : newCap *= 2
1419 0 : }
1420 0 : newData := rawalloc.New(len(b.data), newCap)
1421 0 : copy(newData, b.data)
1422 0 : b.data = newData
1423 : }
1424 1 : b.data = b.data[:newSize]
1425 : }
1426 :
1427 1 : func (b *Batch) setSeqNum(seqNum uint64) {
1428 1 : binary.LittleEndian.PutUint64(b.seqNumData(), seqNum)
1429 1 : }
1430 :
1431 : // SeqNum returns the batch sequence number which is applied to the first
1432 : // record in the batch. The sequence number is incremented for each subsequent
1433 : // record. It returns zero if the batch is empty.
1434 1 : func (b *Batch) SeqNum() uint64 {
1435 1 : if len(b.data) == 0 {
1436 0 : b.init(batchHeaderLen)
1437 0 : }
1438 1 : return binary.LittleEndian.Uint64(b.seqNumData())
1439 : }
1440 :
1441 1 : func (b *Batch) setCount(v uint32) {
1442 1 : b.count = uint64(v)
1443 1 : }
1444 :
1445 : // Count returns the count of memtable-modifying operations in this batch. All
1446 : // operations with the except of LogData increment this count. For IngestSSTs,
1447 : // count is only used to indicate the number of SSTs ingested in the record, the
1448 : // batch isn't applied to the memtable.
1449 1 : func (b *Batch) Count() uint32 {
1450 1 : if b.count > math.MaxUint32 {
1451 0 : panic(ErrInvalidBatch)
1452 : }
1453 1 : return uint32(b.count)
1454 : }
1455 :
1456 : // Reader returns a BatchReader for the current batch contents. If the batch is
1457 : // mutated, the new entries will not be visible to the reader.
1458 1 : func (b *Batch) Reader() BatchReader {
1459 1 : if len(b.data) == 0 {
1460 0 : b.init(batchHeaderLen)
1461 0 : }
1462 1 : return b.data[batchHeaderLen:]
1463 : }
1464 :
1465 1 : func batchDecodeStr(data []byte) (odata []byte, s []byte, ok bool) {
1466 1 : var v uint32
1467 1 : var n int
1468 1 : ptr := unsafe.Pointer(&data[0])
1469 1 : if a := *((*uint8)(ptr)); a < 128 {
1470 1 : v = uint32(a)
1471 1 : n = 1
1472 1 : } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
1473 0 : v = uint32(b)<<7 | uint32(a)
1474 0 : n = 2
1475 0 : } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
1476 0 : v = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
1477 0 : n = 3
1478 0 : } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
1479 0 : v = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
1480 0 : n = 4
1481 0 : } else {
1482 0 : d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
1483 0 : v = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
1484 0 : n = 5
1485 0 : }
1486 :
1487 1 : data = data[n:]
1488 1 : if v > uint32(len(data)) {
1489 0 : return nil, nil, false
1490 0 : }
1491 1 : return data[v:], data[:v], true
1492 : }
1493 :
1494 : // SyncWait is to be used in conjunction with DB.ApplyNoSyncWait.
1495 1 : func (b *Batch) SyncWait() error {
1496 1 : now := time.Now()
1497 1 : b.fsyncWait.Wait()
1498 1 : if b.commitErr != nil {
1499 0 : b.db = nil // prevent batch reuse on error
1500 0 : }
1501 1 : waitDuration := time.Since(now)
1502 1 : b.commitStats.CommitWaitDuration += waitDuration
1503 1 : b.commitStats.TotalDuration += waitDuration
1504 1 : return b.commitErr
1505 : }
1506 :
1507 : // CommitStats returns stats related to committing the batch. Should be called
1508 : // after Batch.Commit, DB.Apply. If DB.ApplyNoSyncWait is used, should be
1509 : // called after Batch.SyncWait.
1510 0 : func (b *Batch) CommitStats() BatchCommitStats {
1511 0 : return b.commitStats
1512 0 : }
1513 :
1514 : // BatchReader iterates over the entries contained in a batch.
1515 : type BatchReader []byte
1516 :
1517 : // ReadBatch constructs a BatchReader from a batch representation. The
1518 : // header is not validated. ReadBatch returns a new batch reader and the
1519 : // count of entries contained within the batch.
1520 0 : func ReadBatch(repr []byte) (r BatchReader, count uint32) {
1521 0 : if len(repr) <= batchHeaderLen {
1522 0 : return nil, count
1523 0 : }
1524 0 : count = binary.LittleEndian.Uint32(repr[batchCountOffset:batchHeaderLen])
1525 0 : return repr[batchHeaderLen:], count
1526 : }
1527 :
1528 : // Next returns the next entry in this batch. The final return value is false
1529 : // if the batch is corrupt. The end of batch is reached when len(r)==0.
1530 1 : func (r *BatchReader) Next() (kind InternalKeyKind, ukey []byte, value []byte, ok bool) {
1531 1 : if len(*r) == 0 {
1532 1 : return 0, nil, nil, false
1533 1 : }
1534 1 : kind = InternalKeyKind((*r)[0])
1535 1 : if kind > InternalKeyKindMax {
1536 0 : return 0, nil, nil, false
1537 0 : }
1538 1 : *r, ukey, ok = batchDecodeStr((*r)[1:])
1539 1 : if !ok {
1540 0 : return 0, nil, nil, false
1541 0 : }
1542 1 : switch kind {
1543 : case InternalKeyKindSet, InternalKeyKindMerge, InternalKeyKindRangeDelete,
1544 : InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete,
1545 1 : InternalKeyKindDeleteSized:
1546 1 : *r, value, ok = batchDecodeStr(*r)
1547 1 : if !ok {
1548 0 : return 0, nil, nil, false
1549 0 : }
1550 : }
1551 1 : return kind, ukey, value, true
1552 : }
1553 :
1554 : // Note: batchIter mirrors the implementation of flushableBatchIter. Keep the
1555 : // two in sync.
1556 : type batchIter struct {
1557 : cmp Compare
1558 : batch *Batch
1559 : iter batchskl.Iterator
1560 : err error
1561 : // snapshot holds a batch "sequence number" at which the batch is being
1562 : // read. This sequence number has the InternalKeySeqNumBatch bit set, so it
1563 : // encodes an offset within the batch. Only batch entries earlier than the
1564 : // offset are visible during iteration.
1565 : snapshot uint64
1566 : }
1567 :
1568 : // batchIter implements the base.InternalIterator interface.
1569 : var _ base.InternalIterator = (*batchIter)(nil)
1570 :
1571 0 : func (i *batchIter) String() string {
1572 0 : return "batch"
1573 0 : }
1574 :
1575 1 : func (i *batchIter) SeekGE(key []byte, flags base.SeekGEFlags) (*InternalKey, base.LazyValue) {
1576 1 : // Ignore TrySeekUsingNext if the view of the batch changed.
1577 1 : if flags.TrySeekUsingNext() && flags.BatchJustRefreshed() {
1578 0 : flags = flags.DisableTrySeekUsingNext()
1579 0 : }
1580 :
1581 1 : i.err = nil // clear cached iteration error
1582 1 : ikey := i.iter.SeekGE(key, flags)
1583 1 : for ikey != nil && ikey.SeqNum() >= i.snapshot {
1584 0 : ikey = i.iter.Next()
1585 0 : }
1586 1 : if ikey == nil {
1587 1 : return nil, base.LazyValue{}
1588 1 : }
1589 1 : return ikey, base.MakeInPlaceValue(i.value())
1590 : }
1591 :
1592 : func (i *batchIter) SeekPrefixGE(
1593 : prefix, key []byte, flags base.SeekGEFlags,
1594 1 : ) (*base.InternalKey, base.LazyValue) {
1595 1 : i.err = nil // clear cached iteration error
1596 1 : return i.SeekGE(key, flags)
1597 1 : }
1598 :
1599 1 : func (i *batchIter) SeekLT(key []byte, flags base.SeekLTFlags) (*InternalKey, base.LazyValue) {
1600 1 : i.err = nil // clear cached iteration error
1601 1 : ikey := i.iter.SeekLT(key)
1602 1 : for ikey != nil && ikey.SeqNum() >= i.snapshot {
1603 0 : ikey = i.iter.Prev()
1604 0 : }
1605 1 : if ikey == nil {
1606 1 : return nil, base.LazyValue{}
1607 1 : }
1608 1 : return ikey, base.MakeInPlaceValue(i.value())
1609 : }
1610 :
1611 1 : func (i *batchIter) First() (*InternalKey, base.LazyValue) {
1612 1 : i.err = nil // clear cached iteration error
1613 1 : ikey := i.iter.First()
1614 1 : for ikey != nil && ikey.SeqNum() >= i.snapshot {
1615 0 : ikey = i.iter.Next()
1616 0 : }
1617 1 : if ikey == nil {
1618 1 : return nil, base.LazyValue{}
1619 1 : }
1620 1 : return ikey, base.MakeInPlaceValue(i.value())
1621 : }
1622 :
1623 1 : func (i *batchIter) Last() (*InternalKey, base.LazyValue) {
1624 1 : i.err = nil // clear cached iteration error
1625 1 : ikey := i.iter.Last()
1626 1 : for ikey != nil && ikey.SeqNum() >= i.snapshot {
1627 0 : ikey = i.iter.Prev()
1628 0 : }
1629 1 : if ikey == nil {
1630 1 : return nil, base.LazyValue{}
1631 1 : }
1632 0 : return ikey, base.MakeInPlaceValue(i.value())
1633 : }
1634 :
1635 1 : func (i *batchIter) Next() (*InternalKey, base.LazyValue) {
1636 1 : ikey := i.iter.Next()
1637 1 : for ikey != nil && ikey.SeqNum() >= i.snapshot {
1638 0 : ikey = i.iter.Next()
1639 0 : }
1640 1 : if ikey == nil {
1641 1 : return nil, base.LazyValue{}
1642 1 : }
1643 1 : return ikey, base.MakeInPlaceValue(i.value())
1644 : }
1645 :
1646 0 : func (i *batchIter) NextPrefix(succKey []byte) (*InternalKey, LazyValue) {
1647 0 : // Because NextPrefix was invoked `succKey` must be ≥ the key at i's current
1648 0 : // position. Seek the arena iterator using TrySeekUsingNext.
1649 0 : ikey := i.iter.SeekGE(succKey, base.SeekGEFlagsNone.EnableTrySeekUsingNext())
1650 0 : for ikey != nil && ikey.SeqNum() >= i.snapshot {
1651 0 : ikey = i.iter.Next()
1652 0 : }
1653 0 : if ikey == nil {
1654 0 : return nil, base.LazyValue{}
1655 0 : }
1656 0 : return ikey, base.MakeInPlaceValue(i.value())
1657 : }
1658 :
1659 0 : func (i *batchIter) Prev() (*InternalKey, base.LazyValue) {
1660 0 : ikey := i.iter.Prev()
1661 0 : for ikey != nil && ikey.SeqNum() >= i.snapshot {
1662 0 : ikey = i.iter.Prev()
1663 0 : }
1664 0 : if ikey == nil {
1665 0 : return nil, base.LazyValue{}
1666 0 : }
1667 0 : return ikey, base.MakeInPlaceValue(i.value())
1668 : }
1669 :
1670 1 : func (i *batchIter) value() []byte {
1671 1 : offset, _, keyEnd := i.iter.KeyInfo()
1672 1 : data := i.batch.data
1673 1 : if len(data[offset:]) == 0 {
1674 0 : i.err = base.CorruptionErrorf("corrupted batch")
1675 0 : return nil
1676 0 : }
1677 :
1678 1 : switch InternalKeyKind(data[offset]) {
1679 : case InternalKeyKindSet, InternalKeyKindMerge, InternalKeyKindRangeDelete,
1680 : InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete,
1681 1 : InternalKeyKindDeleteSized:
1682 1 : _, value, ok := batchDecodeStr(data[keyEnd:])
1683 1 : if !ok {
1684 0 : return nil
1685 0 : }
1686 1 : return value
1687 1 : default:
1688 1 : return nil
1689 : }
1690 : }
1691 :
1692 1 : func (i *batchIter) Error() error {
1693 1 : return i.err
1694 1 : }
1695 :
1696 1 : func (i *batchIter) Close() error {
1697 1 : _ = i.iter.Close()
1698 1 : return i.err
1699 1 : }
1700 :
1701 1 : func (i *batchIter) SetBounds(lower, upper []byte) {
1702 1 : i.iter.SetBounds(lower, upper)
1703 1 : }
1704 :
1705 0 : func (i *batchIter) SetContext(_ context.Context) {}
1706 :
1707 : type flushableBatchEntry struct {
1708 : // offset is the byte offset of the record within the batch repr.
1709 : offset uint32
1710 : // index is the 0-based ordinal number of the record within the batch. Used
1711 : // to compute the seqnum for the record.
1712 : index uint32
1713 : // key{Start,End} are the start and end byte offsets of the key within the
1714 : // batch repr. Cached to avoid decoding the key length on every
1715 : // comparison. The value is stored starting at keyEnd.
1716 : keyStart uint32
1717 : keyEnd uint32
1718 : }
1719 :
1720 : // flushableBatch wraps an existing batch and provides the interfaces needed
1721 : // for making the batch flushable (i.e. able to mimic a memtable).
1722 : type flushableBatch struct {
1723 : cmp Compare
1724 : formatKey base.FormatKey
1725 : data []byte
1726 :
1727 : // The base sequence number for the entries in the batch. This is the same
1728 : // value as Batch.seqNum() and is cached here for performance.
1729 : seqNum uint64
1730 :
1731 : // A slice of offsets and indices for the entries in the batch. Used to
1732 : // implement flushableBatchIter. Unlike the indexing on a normal batch, a
1733 : // flushable batch is indexed such that batch entry i will be given the
1734 : // sequence number flushableBatch.seqNum+i.
1735 : //
1736 : // Sorted in increasing order of key and decreasing order of offset (since
1737 : // higher offsets correspond to higher sequence numbers).
1738 : //
1739 : // Does not include range deletion entries or range key entries.
1740 : offsets []flushableBatchEntry
1741 :
1742 : // Fragmented range deletion tombstones.
1743 : tombstones []keyspan.Span
1744 :
1745 : // Fragmented range keys.
1746 : rangeKeys []keyspan.Span
1747 : }
1748 :
1749 : var _ flushable = (*flushableBatch)(nil)
1750 :
1751 : // newFlushableBatch creates a new batch that implements the flushable
1752 : // interface. This allows the batch to act like a memtable and be placed in the
1753 : // queue of flushable memtables. Note that the flushable batch takes ownership
1754 : // of the batch data.
1755 1 : func newFlushableBatch(batch *Batch, comparer *Comparer) *flushableBatch {
1756 1 : b := &flushableBatch{
1757 1 : data: batch.data,
1758 1 : cmp: comparer.Compare,
1759 1 : formatKey: comparer.FormatKey,
1760 1 : offsets: make([]flushableBatchEntry, 0, batch.Count()),
1761 1 : }
1762 1 : if b.data != nil {
1763 1 : // Note that this sequence number is not correct when this batch has not
1764 1 : // been applied since the sequence number has not been assigned yet. The
1765 1 : // correct sequence number will be set later. But it is correct when the
1766 1 : // batch is being replayed from the WAL.
1767 1 : b.seqNum = batch.SeqNum()
1768 1 : }
1769 1 : var rangeDelOffsets []flushableBatchEntry
1770 1 : var rangeKeyOffsets []flushableBatchEntry
1771 1 : if len(b.data) > batchHeaderLen {
1772 1 : // Non-empty batch.
1773 1 : var index uint32
1774 1 : for iter := BatchReader(b.data[batchHeaderLen:]); len(iter) > 0; index++ {
1775 1 : offset := uintptr(unsafe.Pointer(&iter[0])) - uintptr(unsafe.Pointer(&b.data[0]))
1776 1 : kind, key, _, ok := iter.Next()
1777 1 : if !ok {
1778 0 : break
1779 : }
1780 1 : entry := flushableBatchEntry{
1781 1 : offset: uint32(offset),
1782 1 : index: uint32(index),
1783 1 : }
1784 1 : if keySize := uint32(len(key)); keySize == 0 {
1785 0 : // Must add 2 to the offset. One byte encodes `kind` and the next
1786 0 : // byte encodes `0`, which is the length of the key.
1787 0 : entry.keyStart = uint32(offset) + 2
1788 0 : entry.keyEnd = entry.keyStart
1789 1 : } else {
1790 1 : entry.keyStart = uint32(uintptr(unsafe.Pointer(&key[0])) -
1791 1 : uintptr(unsafe.Pointer(&b.data[0])))
1792 1 : entry.keyEnd = entry.keyStart + keySize
1793 1 : }
1794 1 : switch kind {
1795 1 : case InternalKeyKindRangeDelete:
1796 1 : rangeDelOffsets = append(rangeDelOffsets, entry)
1797 1 : case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
1798 1 : rangeKeyOffsets = append(rangeKeyOffsets, entry)
1799 1 : default:
1800 1 : b.offsets = append(b.offsets, entry)
1801 : }
1802 : }
1803 : }
1804 :
1805 : // Sort all of offsets, rangeDelOffsets and rangeKeyOffsets, using *batch's
1806 : // sort.Interface implementation.
1807 1 : pointOffsets := b.offsets
1808 1 : sort.Sort(b)
1809 1 : b.offsets = rangeDelOffsets
1810 1 : sort.Sort(b)
1811 1 : b.offsets = rangeKeyOffsets
1812 1 : sort.Sort(b)
1813 1 : b.offsets = pointOffsets
1814 1 :
1815 1 : if len(rangeDelOffsets) > 0 {
1816 1 : frag := &keyspan.Fragmenter{
1817 1 : Cmp: b.cmp,
1818 1 : Format: b.formatKey,
1819 1 : Emit: func(s keyspan.Span) {
1820 1 : b.tombstones = append(b.tombstones, s)
1821 1 : },
1822 : }
1823 1 : it := &flushableBatchIter{
1824 1 : batch: b,
1825 1 : data: b.data,
1826 1 : offsets: rangeDelOffsets,
1827 1 : cmp: b.cmp,
1828 1 : index: -1,
1829 1 : }
1830 1 : fragmentRangeDels(frag, it, len(rangeDelOffsets))
1831 : }
1832 1 : if len(rangeKeyOffsets) > 0 {
1833 1 : frag := &keyspan.Fragmenter{
1834 1 : Cmp: b.cmp,
1835 1 : Format: b.formatKey,
1836 1 : Emit: func(s keyspan.Span) {
1837 1 : b.rangeKeys = append(b.rangeKeys, s)
1838 1 : },
1839 : }
1840 1 : it := &flushableBatchIter{
1841 1 : batch: b,
1842 1 : data: b.data,
1843 1 : offsets: rangeKeyOffsets,
1844 1 : cmp: b.cmp,
1845 1 : index: -1,
1846 1 : }
1847 1 : fragmentRangeKeys(frag, it, len(rangeKeyOffsets))
1848 : }
1849 1 : return b
1850 : }
1851 :
1852 1 : func (b *flushableBatch) setSeqNum(seqNum uint64) {
1853 1 : if b.seqNum != 0 {
1854 0 : panic(fmt.Sprintf("pebble: flushableBatch.seqNum already set: %d", b.seqNum))
1855 : }
1856 1 : b.seqNum = seqNum
1857 1 : for i := range b.tombstones {
1858 1 : for j := range b.tombstones[i].Keys {
1859 1 : b.tombstones[i].Keys[j].Trailer = base.MakeTrailer(
1860 1 : b.tombstones[i].Keys[j].SeqNum()+seqNum,
1861 1 : b.tombstones[i].Keys[j].Kind(),
1862 1 : )
1863 1 : }
1864 : }
1865 1 : for i := range b.rangeKeys {
1866 1 : for j := range b.rangeKeys[i].Keys {
1867 1 : b.rangeKeys[i].Keys[j].Trailer = base.MakeTrailer(
1868 1 : b.rangeKeys[i].Keys[j].SeqNum()+seqNum,
1869 1 : b.rangeKeys[i].Keys[j].Kind(),
1870 1 : )
1871 1 : }
1872 : }
1873 : }
1874 :
1875 1 : func (b *flushableBatch) Len() int {
1876 1 : return len(b.offsets)
1877 1 : }
1878 :
1879 1 : func (b *flushableBatch) Less(i, j int) bool {
1880 1 : ei := &b.offsets[i]
1881 1 : ej := &b.offsets[j]
1882 1 : ki := b.data[ei.keyStart:ei.keyEnd]
1883 1 : kj := b.data[ej.keyStart:ej.keyEnd]
1884 1 : switch c := b.cmp(ki, kj); {
1885 1 : case c < 0:
1886 1 : return true
1887 1 : case c > 0:
1888 1 : return false
1889 1 : default:
1890 1 : return ei.offset > ej.offset
1891 : }
1892 : }
1893 :
1894 1 : func (b *flushableBatch) Swap(i, j int) {
1895 1 : b.offsets[i], b.offsets[j] = b.offsets[j], b.offsets[i]
1896 1 : }
1897 :
1898 : // newIter is part of the flushable interface.
1899 1 : func (b *flushableBatch) newIter(o *IterOptions) internalIterator {
1900 1 : return &flushableBatchIter{
1901 1 : batch: b,
1902 1 : data: b.data,
1903 1 : offsets: b.offsets,
1904 1 : cmp: b.cmp,
1905 1 : index: -1,
1906 1 : lower: o.GetLowerBound(),
1907 1 : upper: o.GetUpperBound(),
1908 1 : }
1909 1 : }
1910 :
1911 : // newFlushIter is part of the flushable interface.
1912 1 : func (b *flushableBatch) newFlushIter(o *IterOptions, bytesFlushed *uint64) internalIterator {
1913 1 : return &flushFlushableBatchIter{
1914 1 : flushableBatchIter: flushableBatchIter{
1915 1 : batch: b,
1916 1 : data: b.data,
1917 1 : offsets: b.offsets,
1918 1 : cmp: b.cmp,
1919 1 : index: -1,
1920 1 : },
1921 1 : bytesIterated: bytesFlushed,
1922 1 : }
1923 1 : }
1924 :
1925 : // newRangeDelIter is part of the flushable interface.
1926 1 : func (b *flushableBatch) newRangeDelIter(o *IterOptions) keyspan.FragmentIterator {
1927 1 : if len(b.tombstones) == 0 {
1928 1 : return nil
1929 1 : }
1930 1 : return keyspan.NewIter(b.cmp, b.tombstones)
1931 : }
1932 :
1933 : // newRangeKeyIter is part of the flushable interface.
1934 1 : func (b *flushableBatch) newRangeKeyIter(o *IterOptions) keyspan.FragmentIterator {
1935 1 : if len(b.rangeKeys) == 0 {
1936 1 : return nil
1937 1 : }
1938 1 : return keyspan.NewIter(b.cmp, b.rangeKeys)
1939 : }
1940 :
1941 : // containsRangeKeys is part of the flushable interface.
1942 1 : func (b *flushableBatch) containsRangeKeys() bool { return len(b.rangeKeys) > 0 }
1943 :
1944 : // inuseBytes is part of the flushable interface.
1945 1 : func (b *flushableBatch) inuseBytes() uint64 {
1946 1 : return uint64(len(b.data) - batchHeaderLen)
1947 1 : }
1948 :
1949 : // totalBytes is part of the flushable interface.
1950 1 : func (b *flushableBatch) totalBytes() uint64 {
1951 1 : return uint64(cap(b.data))
1952 1 : }
1953 :
1954 : // readyForFlush is part of the flushable interface.
1955 1 : func (b *flushableBatch) readyForFlush() bool {
1956 1 : // A flushable batch is always ready for flush; it must be flushed together
1957 1 : // with the previous memtable.
1958 1 : return true
1959 1 : }
1960 :
1961 : // Note: flushableBatchIter mirrors the implementation of batchIter. Keep the
1962 : // two in sync.
1963 : type flushableBatchIter struct {
1964 : // Members to be initialized by creator.
1965 : batch *flushableBatch
1966 : // The bytes backing the batch. Always the same as batch.data?
1967 : data []byte
1968 : // The sorted entries. This is not always equal to batch.offsets.
1969 : offsets []flushableBatchEntry
1970 : cmp Compare
1971 : // Must be initialized to -1. It is the index into offsets that represents
1972 : // the current iterator position.
1973 : index int
1974 :
1975 : // For internal use by the implementation.
1976 : key InternalKey
1977 : err error
1978 :
1979 : // Optionally initialize to bounds of iteration, if any.
1980 : lower []byte
1981 : upper []byte
1982 : }
1983 :
1984 : // flushableBatchIter implements the base.InternalIterator interface.
1985 : var _ base.InternalIterator = (*flushableBatchIter)(nil)
1986 :
1987 1 : func (i *flushableBatchIter) String() string {
1988 1 : return "flushable-batch"
1989 1 : }
1990 :
1991 : // SeekGE implements internalIterator.SeekGE, as documented in the pebble
1992 : // package. Ignore flags.TrySeekUsingNext() since we don't expect this
1993 : // optimization to provide much benefit here at the moment.
1994 : func (i *flushableBatchIter) SeekGE(
1995 : key []byte, flags base.SeekGEFlags,
1996 1 : ) (*InternalKey, base.LazyValue) {
1997 1 : i.err = nil // clear cached iteration error
1998 1 : ikey := base.MakeSearchKey(key)
1999 1 : i.index = sort.Search(len(i.offsets), func(j int) bool {
2000 1 : return base.InternalCompare(i.cmp, ikey, i.getKey(j)) <= 0
2001 1 : })
2002 1 : if i.index >= len(i.offsets) {
2003 1 : return nil, base.LazyValue{}
2004 1 : }
2005 1 : i.key = i.getKey(i.index)
2006 1 : if i.upper != nil && i.cmp(i.key.UserKey, i.upper) >= 0 {
2007 1 : i.index = len(i.offsets)
2008 1 : return nil, base.LazyValue{}
2009 1 : }
2010 1 : return &i.key, i.value()
2011 : }
2012 :
2013 : // SeekPrefixGE implements internalIterator.SeekPrefixGE, as documented in the
2014 : // pebble package.
2015 : func (i *flushableBatchIter) SeekPrefixGE(
2016 : prefix, key []byte, flags base.SeekGEFlags,
2017 1 : ) (*base.InternalKey, base.LazyValue) {
2018 1 : return i.SeekGE(key, flags)
2019 1 : }
2020 :
2021 : // SeekLT implements internalIterator.SeekLT, as documented in the pebble
2022 : // package.
2023 : func (i *flushableBatchIter) SeekLT(
2024 : key []byte, flags base.SeekLTFlags,
2025 1 : ) (*InternalKey, base.LazyValue) {
2026 1 : i.err = nil // clear cached iteration error
2027 1 : ikey := base.MakeSearchKey(key)
2028 1 : i.index = sort.Search(len(i.offsets), func(j int) bool {
2029 1 : return base.InternalCompare(i.cmp, ikey, i.getKey(j)) <= 0
2030 1 : })
2031 1 : i.index--
2032 1 : if i.index < 0 {
2033 1 : return nil, base.LazyValue{}
2034 1 : }
2035 1 : i.key = i.getKey(i.index)
2036 1 : if i.lower != nil && i.cmp(i.key.UserKey, i.lower) < 0 {
2037 1 : i.index = -1
2038 1 : return nil, base.LazyValue{}
2039 1 : }
2040 1 : return &i.key, i.value()
2041 : }
2042 :
2043 : // First implements internalIterator.First, as documented in the pebble
2044 : // package.
2045 1 : func (i *flushableBatchIter) First() (*InternalKey, base.LazyValue) {
2046 1 : i.err = nil // clear cached iteration error
2047 1 : if len(i.offsets) == 0 {
2048 1 : return nil, base.LazyValue{}
2049 1 : }
2050 1 : i.index = 0
2051 1 : i.key = i.getKey(i.index)
2052 1 : if i.upper != nil && i.cmp(i.key.UserKey, i.upper) >= 0 {
2053 1 : i.index = len(i.offsets)
2054 1 : return nil, base.LazyValue{}
2055 1 : }
2056 1 : return &i.key, i.value()
2057 : }
2058 :
2059 : // Last implements internalIterator.Last, as documented in the pebble
2060 : // package.
2061 1 : func (i *flushableBatchIter) Last() (*InternalKey, base.LazyValue) {
2062 1 : i.err = nil // clear cached iteration error
2063 1 : if len(i.offsets) == 0 {
2064 1 : return nil, base.LazyValue{}
2065 1 : }
2066 1 : i.index = len(i.offsets) - 1
2067 1 : i.key = i.getKey(i.index)
2068 1 : if i.lower != nil && i.cmp(i.key.UserKey, i.lower) < 0 {
2069 0 : i.index = -1
2070 0 : return nil, base.LazyValue{}
2071 0 : }
2072 1 : return &i.key, i.value()
2073 : }
2074 :
2075 : // Note: flushFlushableBatchIter.Next mirrors the implementation of
2076 : // flushableBatchIter.Next due to performance. Keep the two in sync.
2077 1 : func (i *flushableBatchIter) Next() (*InternalKey, base.LazyValue) {
2078 1 : if i.index == len(i.offsets) {
2079 0 : return nil, base.LazyValue{}
2080 0 : }
2081 1 : i.index++
2082 1 : if i.index == len(i.offsets) {
2083 1 : return nil, base.LazyValue{}
2084 1 : }
2085 1 : i.key = i.getKey(i.index)
2086 1 : if i.upper != nil && i.cmp(i.key.UserKey, i.upper) >= 0 {
2087 1 : i.index = len(i.offsets)
2088 1 : return nil, base.LazyValue{}
2089 1 : }
2090 1 : return &i.key, i.value()
2091 : }
2092 :
2093 1 : func (i *flushableBatchIter) Prev() (*InternalKey, base.LazyValue) {
2094 1 : if i.index < 0 {
2095 0 : return nil, base.LazyValue{}
2096 0 : }
2097 1 : i.index--
2098 1 : if i.index < 0 {
2099 1 : return nil, base.LazyValue{}
2100 1 : }
2101 1 : i.key = i.getKey(i.index)
2102 1 : if i.lower != nil && i.cmp(i.key.UserKey, i.lower) < 0 {
2103 1 : i.index = -1
2104 1 : return nil, base.LazyValue{}
2105 1 : }
2106 1 : return &i.key, i.value()
2107 : }
2108 :
2109 : // Note: flushFlushableBatchIter.NextPrefix mirrors the implementation of
2110 : // flushableBatchIter.NextPrefix due to performance. Keep the two in sync.
2111 0 : func (i *flushableBatchIter) NextPrefix(succKey []byte) (*InternalKey, LazyValue) {
2112 0 : return i.SeekGE(succKey, base.SeekGEFlagsNone.EnableTrySeekUsingNext())
2113 0 : }
2114 :
2115 1 : func (i *flushableBatchIter) getKey(index int) InternalKey {
2116 1 : e := &i.offsets[index]
2117 1 : kind := InternalKeyKind(i.data[e.offset])
2118 1 : key := i.data[e.keyStart:e.keyEnd]
2119 1 : return base.MakeInternalKey(key, i.batch.seqNum+uint64(e.index), kind)
2120 1 : }
2121 :
2122 1 : func (i *flushableBatchIter) value() base.LazyValue {
2123 1 : p := i.data[i.offsets[i.index].offset:]
2124 1 : if len(p) == 0 {
2125 0 : i.err = base.CorruptionErrorf("corrupted batch")
2126 0 : return base.LazyValue{}
2127 0 : }
2128 1 : kind := InternalKeyKind(p[0])
2129 1 : if kind > InternalKeyKindMax {
2130 0 : i.err = base.CorruptionErrorf("corrupted batch")
2131 0 : return base.LazyValue{}
2132 0 : }
2133 1 : var value []byte
2134 1 : var ok bool
2135 1 : switch kind {
2136 : case InternalKeyKindSet, InternalKeyKindMerge, InternalKeyKindRangeDelete,
2137 : InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete,
2138 1 : InternalKeyKindDeleteSized:
2139 1 : keyEnd := i.offsets[i.index].keyEnd
2140 1 : _, value, ok = batchDecodeStr(i.data[keyEnd:])
2141 1 : if !ok {
2142 0 : i.err = base.CorruptionErrorf("corrupted batch")
2143 0 : return base.LazyValue{}
2144 0 : }
2145 : }
2146 1 : return base.MakeInPlaceValue(value)
2147 : }
2148 :
2149 0 : func (i *flushableBatchIter) Valid() bool {
2150 0 : return i.index >= 0 && i.index < len(i.offsets)
2151 0 : }
2152 :
2153 1 : func (i *flushableBatchIter) Error() error {
2154 1 : return i.err
2155 1 : }
2156 :
2157 1 : func (i *flushableBatchIter) Close() error {
2158 1 : return i.err
2159 1 : }
2160 :
2161 1 : func (i *flushableBatchIter) SetBounds(lower, upper []byte) {
2162 1 : i.lower = lower
2163 1 : i.upper = upper
2164 1 : }
2165 :
2166 0 : func (i *flushableBatchIter) SetContext(_ context.Context) {}
2167 :
2168 : // flushFlushableBatchIter is similar to flushableBatchIter but it keeps track
2169 : // of number of bytes iterated.
2170 : type flushFlushableBatchIter struct {
2171 : flushableBatchIter
2172 : bytesIterated *uint64
2173 : }
2174 :
2175 : // flushFlushableBatchIter implements the base.InternalIterator interface.
2176 : var _ base.InternalIterator = (*flushFlushableBatchIter)(nil)
2177 :
2178 0 : func (i *flushFlushableBatchIter) String() string {
2179 0 : return "flushable-batch"
2180 0 : }
2181 :
2182 : func (i *flushFlushableBatchIter) SeekGE(
2183 : key []byte, flags base.SeekGEFlags,
2184 0 : ) (*InternalKey, base.LazyValue) {
2185 0 : panic("pebble: SeekGE unimplemented")
2186 : }
2187 :
2188 : func (i *flushFlushableBatchIter) SeekPrefixGE(
2189 : prefix, key []byte, flags base.SeekGEFlags,
2190 0 : ) (*base.InternalKey, base.LazyValue) {
2191 0 : panic("pebble: SeekPrefixGE unimplemented")
2192 : }
2193 :
2194 : func (i *flushFlushableBatchIter) SeekLT(
2195 : key []byte, flags base.SeekLTFlags,
2196 0 : ) (*InternalKey, base.LazyValue) {
2197 0 : panic("pebble: SeekLT unimplemented")
2198 : }
2199 :
2200 1 : func (i *flushFlushableBatchIter) First() (*InternalKey, base.LazyValue) {
2201 1 : i.err = nil // clear cached iteration error
2202 1 : key, val := i.flushableBatchIter.First()
2203 1 : if key == nil {
2204 1 : return nil, base.LazyValue{}
2205 1 : }
2206 1 : entryBytes := i.offsets[i.index].keyEnd - i.offsets[i.index].offset
2207 1 : *i.bytesIterated += uint64(entryBytes) + i.valueSize()
2208 1 : return key, val
2209 : }
2210 :
2211 0 : func (i *flushFlushableBatchIter) NextPrefix(succKey []byte) (*InternalKey, base.LazyValue) {
2212 0 : panic("pebble: Prev unimplemented")
2213 : }
2214 :
2215 : // Note: flushFlushableBatchIter.Next mirrors the implementation of
2216 : // flushableBatchIter.Next due to performance. Keep the two in sync.
2217 1 : func (i *flushFlushableBatchIter) Next() (*InternalKey, base.LazyValue) {
2218 1 : if i.index == len(i.offsets) {
2219 0 : return nil, base.LazyValue{}
2220 0 : }
2221 1 : i.index++
2222 1 : if i.index == len(i.offsets) {
2223 1 : return nil, base.LazyValue{}
2224 1 : }
2225 1 : i.key = i.getKey(i.index)
2226 1 : entryBytes := i.offsets[i.index].keyEnd - i.offsets[i.index].offset
2227 1 : *i.bytesIterated += uint64(entryBytes) + i.valueSize()
2228 1 : return &i.key, i.value()
2229 : }
2230 :
2231 0 : func (i flushFlushableBatchIter) Prev() (*InternalKey, base.LazyValue) {
2232 0 : panic("pebble: Prev unimplemented")
2233 : }
2234 :
2235 1 : func (i flushFlushableBatchIter) valueSize() uint64 {
2236 1 : p := i.data[i.offsets[i.index].offset:]
2237 1 : if len(p) == 0 {
2238 0 : i.err = base.CorruptionErrorf("corrupted batch")
2239 0 : return 0
2240 0 : }
2241 1 : kind := InternalKeyKind(p[0])
2242 1 : if kind > InternalKeyKindMax {
2243 0 : i.err = base.CorruptionErrorf("corrupted batch")
2244 0 : return 0
2245 0 : }
2246 1 : var length uint64
2247 1 : switch kind {
2248 1 : case InternalKeyKindSet, InternalKeyKindMerge, InternalKeyKindRangeDelete:
2249 1 : keyEnd := i.offsets[i.index].keyEnd
2250 1 : v, n := binary.Uvarint(i.data[keyEnd:])
2251 1 : if n <= 0 {
2252 0 : i.err = base.CorruptionErrorf("corrupted batch")
2253 0 : return 0
2254 0 : }
2255 1 : length = v + uint64(n)
2256 : }
2257 1 : return length
2258 : }
2259 :
2260 : // batchSort returns iterators for the sorted contents of the batch. It is
2261 : // intended for testing use only. The batch.Sort dance is done to prevent
2262 : // exposing this method in the public pebble interface.
2263 : func batchSort(
2264 : i interface{},
2265 : ) (
2266 : points internalIterator,
2267 : rangeDels keyspan.FragmentIterator,
2268 : rangeKeys keyspan.FragmentIterator,
2269 1 : ) {
2270 1 : b := i.(*Batch)
2271 1 : if b.Indexed() {
2272 1 : pointIter := b.newInternalIter(nil)
2273 1 : rangeDelIter := b.newRangeDelIter(nil, math.MaxUint64)
2274 1 : rangeKeyIter := b.newRangeKeyIter(nil, math.MaxUint64)
2275 1 : return pointIter, rangeDelIter, rangeKeyIter
2276 1 : }
2277 1 : f := newFlushableBatch(b, b.db.opts.Comparer)
2278 1 : return f.newIter(nil), f.newRangeDelIter(nil), f.newRangeKeyIter(nil)
2279 : }
2280 :
2281 1 : func init() {
2282 1 : private.BatchSort = batchSort
2283 1 : }
|