LCOV - code coverage report
Current view: top level - pebble - batch.go (source / functions) Hit Total Coverage
Test: 2024-10-05 08:16Z 649e50ad - meta test only.lcov Lines: 1106 1401 78.9 %
Date: 2024-10-05 08:16:48 Functions: 0 0 -

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

Generated by: LCOV version 1.14