LCOV - code coverage report
Current view: top level - pebble - options.go (source / functions) Hit Total Coverage
Test: 2024-09-04 08:16Z 137a1655 - tests only.lcov Lines: 718 813 88.3 %
Date: 2024-09-04 08:16:49 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2011 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             :         "fmt"
      10             :         "io"
      11             :         "runtime"
      12             :         "strconv"
      13             :         "strings"
      14             :         "time"
      15             :         "unicode"
      16             : 
      17             :         "github.com/cockroachdb/errors"
      18             :         "github.com/cockroachdb/fifo"
      19             :         "github.com/cockroachdb/pebble/internal/base"
      20             :         "github.com/cockroachdb/pebble/internal/cache"
      21             :         "github.com/cockroachdb/pebble/internal/humanize"
      22             :         "github.com/cockroachdb/pebble/internal/keyspan"
      23             :         "github.com/cockroachdb/pebble/internal/manifest"
      24             :         "github.com/cockroachdb/pebble/objstorage/objstorageprovider"
      25             :         "github.com/cockroachdb/pebble/objstorage/remote"
      26             :         "github.com/cockroachdb/pebble/rangekey"
      27             :         "github.com/cockroachdb/pebble/sstable"
      28             :         "github.com/cockroachdb/pebble/sstable/block"
      29             :         "github.com/cockroachdb/pebble/vfs"
      30             :         "github.com/cockroachdb/pebble/wal"
      31             : )
      32             : 
      33             : const (
      34             :         cacheDefaultSize       = 8 << 20 // 8 MB
      35             :         defaultLevelMultiplier = 10
      36             : )
      37             : 
      38             : // Compression exports the base.Compression type.
      39             : type Compression = block.Compression
      40             : 
      41             : // Exported Compression constants.
      42             : const (
      43             :         DefaultCompression = block.DefaultCompression
      44             :         NoCompression      = block.NoCompression
      45             :         SnappyCompression  = block.SnappyCompression
      46             :         ZstdCompression    = block.ZstdCompression
      47             : )
      48             : 
      49             : // FilterType exports the base.FilterType type.
      50             : type FilterType = base.FilterType
      51             : 
      52             : // Exported TableFilter constants.
      53             : const (
      54             :         TableFilter = base.TableFilter
      55             : )
      56             : 
      57             : // FilterWriter exports the base.FilterWriter type.
      58             : type FilterWriter = base.FilterWriter
      59             : 
      60             : // FilterPolicy exports the base.FilterPolicy type.
      61             : type FilterPolicy = base.FilterPolicy
      62             : 
      63             : // BlockPropertyCollector exports the sstable.BlockPropertyCollector type.
      64             : type BlockPropertyCollector = sstable.BlockPropertyCollector
      65             : 
      66             : // BlockPropertyFilter exports the sstable.BlockPropertyFilter type.
      67             : type BlockPropertyFilter = base.BlockPropertyFilter
      68             : 
      69             : // ShortAttributeExtractor exports the base.ShortAttributeExtractor type.
      70             : type ShortAttributeExtractor = base.ShortAttributeExtractor
      71             : 
      72             : // UserKeyPrefixBound exports the sstable.UserKeyPrefixBound type.
      73             : type UserKeyPrefixBound = sstable.UserKeyPrefixBound
      74             : 
      75             : // IterKeyType configures which types of keys an iterator should surface.
      76             : type IterKeyType int8
      77             : 
      78             : const (
      79             :         // IterKeyTypePointsOnly configures an iterator to iterate over point keys
      80             :         // only.
      81             :         IterKeyTypePointsOnly IterKeyType = iota
      82             :         // IterKeyTypeRangesOnly configures an iterator to iterate over range keys
      83             :         // only.
      84             :         IterKeyTypeRangesOnly
      85             :         // IterKeyTypePointsAndRanges configures an iterator iterate over both point
      86             :         // keys and range keys simultaneously.
      87             :         IterKeyTypePointsAndRanges
      88             : )
      89             : 
      90             : // String implements fmt.Stringer.
      91           1 : func (t IterKeyType) String() string {
      92           1 :         switch t {
      93           1 :         case IterKeyTypePointsOnly:
      94           1 :                 return "points-only"
      95           1 :         case IterKeyTypeRangesOnly:
      96           1 :                 return "ranges-only"
      97           1 :         case IterKeyTypePointsAndRanges:
      98           1 :                 return "points-and-ranges"
      99           0 :         default:
     100           0 :                 panic(fmt.Sprintf("unknown key type %d", t))
     101             :         }
     102             : }
     103             : 
     104             : // IterOptions hold the optional per-query parameters for NewIter.
     105             : //
     106             : // Like Options, a nil *IterOptions is valid and means to use the default
     107             : // values.
     108             : type IterOptions struct {
     109             :         // LowerBound specifies the smallest key (inclusive) that the iterator will
     110             :         // return during iteration. If the iterator is seeked or iterated past this
     111             :         // boundary the iterator will return Valid()==false. Setting LowerBound
     112             :         // effectively truncates the key space visible to the iterator.
     113             :         LowerBound []byte
     114             :         // UpperBound specifies the largest key (exclusive) that the iterator will
     115             :         // return during iteration. If the iterator is seeked or iterated past this
     116             :         // boundary the iterator will return Valid()==false. Setting UpperBound
     117             :         // effectively truncates the key space visible to the iterator.
     118             :         UpperBound []byte
     119             :         // SkipPoint may be used to skip over point keys that don't match an
     120             :         // arbitrary predicate during iteration. If set, the Iterator invokes
     121             :         // SkipPoint for keys encountered. If SkipPoint returns true, the iterator
     122             :         // will skip the key without yielding it to the iterator operation in
     123             :         // progress.
     124             :         //
     125             :         // SkipPoint must be a pure function and always return the same result when
     126             :         // provided the same arguments. The iterator may call SkipPoint multiple
     127             :         // times for the same user key.
     128             :         SkipPoint func(userKey []byte) bool
     129             :         // PointKeyFilters can be used to avoid scanning tables and blocks in tables
     130             :         // when iterating over point keys. This slice represents an intersection
     131             :         // across all filters, i.e., all filters must indicate that the block is
     132             :         // relevant.
     133             :         //
     134             :         // Performance note: When len(PointKeyFilters) > 0, the caller should ensure
     135             :         // that cap(PointKeyFilters) is at least len(PointKeyFilters)+1. This helps
     136             :         // avoid allocations in Pebble internal code that mutates the slice.
     137             :         PointKeyFilters []BlockPropertyFilter
     138             :         // RangeKeyFilters can be usefd to avoid scanning tables and blocks in tables
     139             :         // when iterating over range keys. The same requirements that apply to
     140             :         // PointKeyFilters apply here too.
     141             :         RangeKeyFilters []BlockPropertyFilter
     142             :         // KeyTypes configures which types of keys to iterate over: point keys,
     143             :         // range keys, or both.
     144             :         KeyTypes IterKeyType
     145             :         // RangeKeyMasking can be used to enable automatic masking of point keys by
     146             :         // range keys. Range key masking is only supported during combined range key
     147             :         // and point key iteration mode (IterKeyTypePointsAndRanges).
     148             :         RangeKeyMasking RangeKeyMasking
     149             : 
     150             :         // OnlyReadGuaranteedDurable is an advanced option that is only supported by
     151             :         // the Reader implemented by DB. When set to true, only the guaranteed to be
     152             :         // durable state is visible in the iterator.
     153             :         // - This definition is made under the assumption that the FS implementation
     154             :         //   is providing a durability guarantee when data is synced.
     155             :         // - The visible state represents a consistent point in the history of the
     156             :         //   DB.
     157             :         // - The implementation is free to choose a conservative definition of what
     158             :         //   is guaranteed durable. For simplicity, the current implementation
     159             :         //   ignores memtables. A more sophisticated implementation could track the
     160             :         //   highest seqnum that is synced to the WAL and published and use that as
     161             :         //   the visible seqnum for an iterator. Note that the latter approach is
     162             :         //   not strictly better than the former since we can have DBs that are (a)
     163             :         //   synced more rarely than memtable flushes, (b) have no WAL. (a) is
     164             :         //   likely to be true in a future CockroachDB context where the DB
     165             :         //   containing the state machine may be rarely synced.
     166             :         // NB: this current implementation relies on the fact that memtables are
     167             :         // flushed in seqnum order, and any ingested sstables that happen to have a
     168             :         // lower seqnum than a non-flushed memtable don't have any overlapping keys.
     169             :         // This is the fundamental level invariant used in other code too, like when
     170             :         // merging iterators.
     171             :         //
     172             :         // Semantically, using this option provides the caller a "snapshot" as of
     173             :         // the time the most recent memtable was flushed. An alternate interface
     174             :         // would be to add a NewSnapshot variant. Creating a snapshot is heavier
     175             :         // weight than creating an iterator, so we have opted to support this
     176             :         // iterator option.
     177             :         OnlyReadGuaranteedDurable bool
     178             :         // UseL6Filters allows the caller to opt into reading filter blocks for L6
     179             :         // sstables. Helpful if a lot of SeekPrefixGEs are expected in quick
     180             :         // succession, that are also likely to not yield a single key. Filter blocks in
     181             :         // L6 can be relatively large, often larger than data blocks, so the benefit of
     182             :         // loading them in the cache is minimized if the probability of the key
     183             :         // existing is not low or if we just expect a one-time Seek (where loading the
     184             :         // data block directly is better).
     185             :         UseL6Filters bool
     186             :         // CategoryAndQoS is used for categorized iterator stats. This should not be
     187             :         // changed by calling SetOptions.
     188             :         sstable.CategoryAndQoS
     189             : 
     190             :         DebugRangeKeyStack bool
     191             : 
     192             :         // Internal options.
     193             : 
     194             :         logger Logger
     195             :         // Layer corresponding to this file. Only passed in if constructed by a
     196             :         // levelIter.
     197             :         layer manifest.Layer
     198             :         // disableLazyCombinedIteration is an internal testing option.
     199             :         disableLazyCombinedIteration bool
     200             :         // snapshotForHideObsoletePoints is specified for/by levelIter when opening
     201             :         // files and is used to decide whether to hide obsolete points. A value of 0
     202             :         // implies obsolete points should not be hidden.
     203             :         snapshotForHideObsoletePoints base.SeqNum
     204             : 
     205             :         // NB: If adding new Options, you must account for them in iterator
     206             :         // construction and Iterator.SetOptions.
     207             : }
     208             : 
     209             : // GetLowerBound returns the LowerBound or nil if the receiver is nil.
     210           1 : func (o *IterOptions) GetLowerBound() []byte {
     211           1 :         if o == nil {
     212           1 :                 return nil
     213           1 :         }
     214           1 :         return o.LowerBound
     215             : }
     216             : 
     217             : // GetUpperBound returns the UpperBound or nil if the receiver is nil.
     218           1 : func (o *IterOptions) GetUpperBound() []byte {
     219           1 :         if o == nil {
     220           1 :                 return nil
     221           1 :         }
     222           1 :         return o.UpperBound
     223             : }
     224             : 
     225           1 : func (o *IterOptions) pointKeys() bool {
     226           1 :         if o == nil {
     227           0 :                 return true
     228           0 :         }
     229           1 :         return o.KeyTypes == IterKeyTypePointsOnly || o.KeyTypes == IterKeyTypePointsAndRanges
     230             : }
     231             : 
     232           1 : func (o *IterOptions) rangeKeys() bool {
     233           1 :         if o == nil {
     234           0 :                 return false
     235           0 :         }
     236           1 :         return o.KeyTypes == IterKeyTypeRangesOnly || o.KeyTypes == IterKeyTypePointsAndRanges
     237             : }
     238             : 
     239           1 : func (o *IterOptions) getLogger() Logger {
     240           1 :         if o == nil || o.logger == nil {
     241           1 :                 return DefaultLogger
     242           1 :         }
     243           1 :         return o.logger
     244             : }
     245             : 
     246             : // SpanIterOptions creates a SpanIterOptions from this IterOptions.
     247           1 : func (o *IterOptions) SpanIterOptions() keyspan.SpanIterOptions {
     248           1 :         if o == nil {
     249           1 :                 return keyspan.SpanIterOptions{}
     250           1 :         }
     251           1 :         return keyspan.SpanIterOptions{
     252           1 :                 RangeKeyFilters: o.RangeKeyFilters,
     253           1 :         }
     254             : }
     255             : 
     256             : // scanInternalOptions is similar to IterOptions, meant for use with
     257             : // scanInternalIterator.
     258             : type scanInternalOptions struct {
     259             :         sstable.CategoryAndQoS
     260             :         IterOptions
     261             : 
     262             :         visitPointKey     func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error
     263             :         visitRangeDel     func(start, end []byte, seqNum SeqNum) error
     264             :         visitRangeKey     func(start, end []byte, keys []rangekey.Key) error
     265             :         visitSharedFile   func(sst *SharedSSTMeta) error
     266             :         visitExternalFile func(sst *ExternalFile) error
     267             : 
     268             :         // includeObsoleteKeys specifies whether keys shadowed by newer internal keys
     269             :         // are exposed. If false, only one internal key per user key is exposed.
     270             :         includeObsoleteKeys bool
     271             : 
     272             :         // rateLimitFunc is used to limit the amount of bytes read per second.
     273             :         rateLimitFunc func(key *InternalKey, value LazyValue) error
     274             : }
     275             : 
     276             : // RangeKeyMasking configures automatic hiding of point keys by range keys. A
     277             : // non-nil Suffix enables range-key masking. When enabled, range keys with
     278             : // suffixes ≥ Suffix behave as masks. All point keys that are contained within a
     279             : // masking range key's bounds and have suffixes greater than the range key's
     280             : // suffix are automatically skipped.
     281             : //
     282             : // Specifically, when configured with a RangeKeyMasking.Suffix _s_, and there
     283             : // exists a range key with suffix _r_ covering a point key with suffix _p_, and
     284             : //
     285             : //      _s_ ≤ _r_ < _p_
     286             : //
     287             : // then the point key is elided.
     288             : //
     289             : // Range-key masking may only be used when iterating over both point keys and
     290             : // range keys with IterKeyTypePointsAndRanges.
     291             : type RangeKeyMasking struct {
     292             :         // Suffix configures which range keys may mask point keys. Only range keys
     293             :         // that are defined at suffixes greater than or equal to Suffix will mask
     294             :         // point keys.
     295             :         Suffix []byte
     296             :         // Filter is an optional field that may be used to improve performance of
     297             :         // range-key masking through a block-property filter defined over key
     298             :         // suffixes. If non-nil, Filter is called by Pebble to construct a
     299             :         // block-property filter mask at iterator creation. The filter is used to
     300             :         // skip whole point-key blocks containing point keys with suffixes greater
     301             :         // than a covering range-key's suffix.
     302             :         //
     303             :         // To use this functionality, the caller must create and configure (through
     304             :         // Options.BlockPropertyCollectors) a block-property collector that records
     305             :         // the maxmimum suffix contained within a block. The caller then must write
     306             :         // and provide a BlockPropertyFilterMask implementation on that same
     307             :         // property. See the BlockPropertyFilterMask type for more information.
     308             :         Filter func() BlockPropertyFilterMask
     309             : }
     310             : 
     311             : // BlockPropertyFilterMask extends the BlockPropertyFilter interface for use
     312             : // with range-key masking. Unlike an ordinary block property filter, a
     313             : // BlockPropertyFilterMask's filtering criteria is allowed to change when Pebble
     314             : // invokes its SetSuffix method.
     315             : //
     316             : // When a Pebble iterator steps into a range key's bounds and the range key has
     317             : // a suffix greater than or equal to RangeKeyMasking.Suffix, the range key acts
     318             : // as a mask. The masking range key hides all point keys that fall within the
     319             : // range key's bounds and have suffixes > the range key's suffix. Without a
     320             : // filter mask configured, Pebble performs this hiding by stepping through point
     321             : // keys and comparing suffixes. If large numbers of point keys are masked, this
     322             : // requires Pebble to load, iterate through and discard a large number of
     323             : // sstable blocks containing masked point keys.
     324             : //
     325             : // If a block-property collector and a filter mask are configured, Pebble may
     326             : // skip loading some point-key blocks altogether. If a block's keys are known to
     327             : // all fall within the bounds of the masking range key and the block was
     328             : // annotated by a block-property collector with the maximal suffix, Pebble can
     329             : // ask the filter mask to compare the property to the current masking range
     330             : // key's suffix. If the mask reports no intersection, the block may be skipped.
     331             : //
     332             : // If unsuffixed and suffixed keys are written to the database, care must be
     333             : // taken to avoid unintentionally masking un-suffixed keys located in the same
     334             : // block as suffixed keys. One solution is to interpret unsuffixed keys as
     335             : // containing the maximal suffix value, ensuring that blocks containing
     336             : // unsuffixed keys are always loaded.
     337             : type BlockPropertyFilterMask interface {
     338             :         BlockPropertyFilter
     339             : 
     340             :         // SetSuffix configures the mask with the suffix of a range key. The filter
     341             :         // should return false from Intersects whenever it's provided with a
     342             :         // property encoding a block's minimum suffix that's greater (according to
     343             :         // Compare) than the provided suffix.
     344             :         SetSuffix(suffix []byte) error
     345             : }
     346             : 
     347             : // WriteOptions hold the optional per-query parameters for Set and Delete
     348             : // operations.
     349             : //
     350             : // Like Options, a nil *WriteOptions is valid and means to use the default
     351             : // values.
     352             : type WriteOptions struct {
     353             :         // Sync is whether to sync writes through the OS buffer cache and down onto
     354             :         // the actual disk, if applicable. Setting Sync is required for durability of
     355             :         // individual write operations but can result in slower writes.
     356             :         //
     357             :         // If false, and the process or machine crashes, then a recent write may be
     358             :         // lost. This is due to the recently written data being buffered inside the
     359             :         // process running Pebble. This differs from the semantics of a write system
     360             :         // call in which the data is buffered in the OS buffer cache and would thus
     361             :         // survive a process crash.
     362             :         //
     363             :         // The default value is true.
     364             :         Sync bool
     365             : }
     366             : 
     367             : // Sync specifies the default write options for writes which synchronize to
     368             : // disk.
     369             : var Sync = &WriteOptions{Sync: true}
     370             : 
     371             : // NoSync specifies the default write options for writes which do not
     372             : // synchronize to disk.
     373             : var NoSync = &WriteOptions{Sync: false}
     374             : 
     375             : // GetSync returns the Sync value or true if the receiver is nil.
     376           1 : func (o *WriteOptions) GetSync() bool {
     377           1 :         return o == nil || o.Sync
     378           1 : }
     379             : 
     380             : // LevelOptions holds the optional per-level parameters.
     381             : type LevelOptions struct {
     382             :         // BlockRestartInterval is the number of keys between restart points
     383             :         // for delta encoding of keys.
     384             :         //
     385             :         // The default value is 16.
     386             :         BlockRestartInterval int
     387             : 
     388             :         // BlockSize is the target uncompressed size in bytes of each table block.
     389             :         //
     390             :         // The default value is 4096.
     391             :         BlockSize int
     392             : 
     393             :         // BlockSizeThreshold finishes a block if the block size is larger than the
     394             :         // specified percentage of the target block size and adding the next entry
     395             :         // would cause the block to be larger than the target block size.
     396             :         //
     397             :         // The default value is 90
     398             :         BlockSizeThreshold int
     399             : 
     400             :         // Compression defines the per-block compression to use.
     401             :         //
     402             :         // The default value (DefaultCompression) uses snappy compression.
     403             :         Compression func() Compression
     404             : 
     405             :         // FilterPolicy defines a filter algorithm (such as a Bloom filter) that can
     406             :         // reduce disk reads for Get calls.
     407             :         //
     408             :         // One such implementation is bloom.FilterPolicy(10) from the pebble/bloom
     409             :         // package.
     410             :         //
     411             :         // The default value means to use no filter.
     412             :         FilterPolicy FilterPolicy
     413             : 
     414             :         // FilterType defines whether an existing filter policy is applied at a
     415             :         // block-level or table-level. Block-level filters use less memory to create,
     416             :         // but are slower to access as a check for the key in the index must first be
     417             :         // performed to locate the filter block. A table-level filter will require
     418             :         // memory proportional to the number of keys in an sstable to create, but
     419             :         // avoids the index lookup when determining if a key is present. Table-level
     420             :         // filters should be preferred except under constrained memory situations.
     421             :         FilterType FilterType
     422             : 
     423             :         // IndexBlockSize is the target uncompressed size in bytes of each index
     424             :         // block. When the index block size is larger than this target, two-level
     425             :         // indexes are automatically enabled. Setting this option to a large value
     426             :         // (such as math.MaxInt32) disables the automatic creation of two-level
     427             :         // indexes.
     428             :         //
     429             :         // The default value is the value of BlockSize.
     430             :         IndexBlockSize int
     431             : 
     432             :         // The target file size for the level.
     433             :         TargetFileSize int64
     434             : }
     435             : 
     436             : // EnsureDefaults ensures that the default values for all of the options have
     437             : // been initialized. It is valid to call EnsureDefaults on a nil receiver. A
     438             : // non-nil result will always be returned.
     439           1 : func (o *LevelOptions) EnsureDefaults() *LevelOptions {
     440           1 :         if o == nil {
     441           0 :                 o = &LevelOptions{}
     442           0 :         }
     443           1 :         if o.BlockRestartInterval <= 0 {
     444           1 :                 o.BlockRestartInterval = base.DefaultBlockRestartInterval
     445           1 :         }
     446           1 :         if o.BlockSize <= 0 {
     447           1 :                 o.BlockSize = base.DefaultBlockSize
     448           1 :         } else if o.BlockSize > sstable.MaximumBlockSize {
     449           0 :                 panic(errors.Errorf("BlockSize %d exceeds MaximumBlockSize", o.BlockSize))
     450             :         }
     451           1 :         if o.BlockSizeThreshold <= 0 {
     452           1 :                 o.BlockSizeThreshold = base.DefaultBlockSizeThreshold
     453           1 :         }
     454           1 :         if o.Compression == nil {
     455           1 :                 o.Compression = func() Compression { return DefaultCompression }
     456             :         }
     457           1 :         if o.IndexBlockSize <= 0 {
     458           1 :                 o.IndexBlockSize = o.BlockSize
     459           1 :         }
     460           1 :         if o.TargetFileSize <= 0 {
     461           1 :                 o.TargetFileSize = 2 << 20 // 2 MB
     462           1 :         }
     463           1 :         return o
     464             : }
     465             : 
     466             : // Options holds the optional parameters for configuring pebble. These options
     467             : // apply to the DB at large; per-query options are defined by the IterOptions
     468             : // and WriteOptions types.
     469             : type Options struct {
     470             :         // Sync sstables periodically in order to smooth out writes to disk. This
     471             :         // option does not provide any persistency guarantee, but is used to avoid
     472             :         // latency spikes if the OS automatically decides to write out a large chunk
     473             :         // of dirty filesystem buffers. This option only controls SSTable syncs; WAL
     474             :         // syncs are controlled by WALBytesPerSync.
     475             :         //
     476             :         // The default value is 512KB.
     477             :         BytesPerSync int
     478             : 
     479             :         // Cache is used to cache uncompressed blocks from sstables.
     480             :         //
     481             :         // The default cache size is 8 MB.
     482             :         Cache *cache.Cache
     483             : 
     484             :         // LoadBlockSema, if set, is used to limit the number of blocks that can be
     485             :         // loaded (i.e. read from the filesystem) in parallel. Each load acquires one
     486             :         // unit from the semaphore for the duration of the read.
     487             :         LoadBlockSema *fifo.Semaphore
     488             : 
     489             :         // Cleaner cleans obsolete files.
     490             :         //
     491             :         // The default cleaner uses the DeleteCleaner.
     492             :         Cleaner Cleaner
     493             : 
     494             :         // Local contains option that pertain to files stored on the local filesystem.
     495             :         Local struct {
     496             :                 // ReadaheadConfig is used to retrieve the current readahead mode; it is
     497             :                 // consulted whenever a read handle is initialized.
     498             :                 ReadaheadConfig *ReadaheadConfig
     499             : 
     500             :                 // TODO(radu): move BytesPerSync, LoadBlockSema, Cleaner here.
     501             :         }
     502             : 
     503             :         // Comparer defines a total ordering over the space of []byte keys: a 'less
     504             :         // than' relationship. The same comparison algorithm must be used for reads
     505             :         // and writes over the lifetime of the DB.
     506             :         //
     507             :         // The default value uses the same ordering as bytes.Compare.
     508             :         Comparer *Comparer
     509             : 
     510             :         // DebugCheck is invoked, if non-nil, whenever a new version is being
     511             :         // installed. Typically, this is set to pebble.DebugCheckLevels in tests
     512             :         // or tools only, to check invariants over all the data in the database.
     513             :         DebugCheck func(*DB) error
     514             : 
     515             :         // Disable the write-ahead log (WAL). Disabling the write-ahead log prohibits
     516             :         // crash recovery, but can improve performance if crash recovery is not
     517             :         // needed (e.g. when only temporary state is being stored in the database).
     518             :         //
     519             :         // TODO(peter): untested
     520             :         DisableWAL bool
     521             : 
     522             :         // ErrorIfExists causes an error on Open if the database already exists.
     523             :         // The error can be checked with errors.Is(err, ErrDBAlreadyExists).
     524             :         //
     525             :         // The default value is false.
     526             :         ErrorIfExists bool
     527             : 
     528             :         // ErrorIfNotExists causes an error on Open if the database does not already
     529             :         // exist. The error can be checked with errors.Is(err, ErrDBDoesNotExist).
     530             :         //
     531             :         // The default value is false which will cause a database to be created if it
     532             :         // does not already exist.
     533             :         ErrorIfNotExists bool
     534             : 
     535             :         // ErrorIfNotPristine causes an error on Open if the database already exists
     536             :         // and any operations have been performed on the database. The error can be
     537             :         // checked with errors.Is(err, ErrDBNotPristine).
     538             :         //
     539             :         // Note that a database that contained keys that were all subsequently deleted
     540             :         // may or may not trigger the error. Currently, we check if there are any live
     541             :         // SSTs or log records to replay.
     542             :         ErrorIfNotPristine bool
     543             : 
     544             :         // EventListener provides hooks to listening to significant DB events such as
     545             :         // flushes, compactions, and table deletion.
     546             :         EventListener *EventListener
     547             : 
     548             :         // Experimental contains experimental options which are off by default.
     549             :         // These options are temporary and will eventually either be deleted, moved
     550             :         // out of the experimental group, or made the non-adjustable default. These
     551             :         // options may change at any time, so do not rely on them.
     552             :         Experimental struct {
     553             :                 // The threshold of L0 read-amplification at which compaction concurrency
     554             :                 // is enabled (if CompactionDebtConcurrency was not already exceeded).
     555             :                 // Every multiple of this value enables another concurrent
     556             :                 // compaction up to MaxConcurrentCompactions.
     557             :                 L0CompactionConcurrency int
     558             : 
     559             :                 // CompactionDebtConcurrency controls the threshold of compaction debt
     560             :                 // at which additional compaction concurrency slots are added. For every
     561             :                 // multiple of this value in compaction debt bytes, an additional
     562             :                 // concurrent compaction is added. This works "on top" of
     563             :                 // L0CompactionConcurrency, so the higher of the count of compaction
     564             :                 // concurrency slots as determined by the two options is chosen.
     565             :                 CompactionDebtConcurrency uint64
     566             : 
     567             :                 // IngestSplit, if it returns true, allows for ingest-time splitting of
     568             :                 // existing sstables into two virtual sstables to allow ingestion sstables to
     569             :                 // slot into a lower level than they otherwise would have.
     570             :                 IngestSplit func() bool
     571             : 
     572             :                 // ReadCompactionRate controls the frequency of read triggered
     573             :                 // compactions by adjusting `AllowedSeeks` in manifest.FileMetadata:
     574             :                 //
     575             :                 // AllowedSeeks = FileSize / ReadCompactionRate
     576             :                 //
     577             :                 // From LevelDB:
     578             :                 // ```
     579             :                 // We arrange to automatically compact this file after
     580             :                 // a certain number of seeks. Let's assume:
     581             :                 //   (1) One seek costs 10ms
     582             :                 //   (2) Writing or reading 1MB costs 10ms (100MB/s)
     583             :                 //   (3) A compaction of 1MB does 25MB of IO:
     584             :                 //         1MB read from this level
     585             :                 //         10-12MB read from next level (boundaries may be misaligned)
     586             :                 //         10-12MB written to next level
     587             :                 // This implies that 25 seeks cost the same as the compaction
     588             :                 // of 1MB of data.  I.e., one seek costs approximately the
     589             :                 // same as the compaction of 40KB of data.  We are a little
     590             :                 // conservative and allow approximately one seek for every 16KB
     591             :                 // of data before triggering a compaction.
     592             :                 // ```
     593             :                 ReadCompactionRate int64
     594             : 
     595             :                 // ReadSamplingMultiplier is a multiplier for the readSamplingPeriod in
     596             :                 // iterator.maybeSampleRead() to control the frequency of read sampling
     597             :                 // to trigger a read triggered compaction. A value of -1 prevents sampling
     598             :                 // and disables read triggered compactions. The default is 1 << 4. which
     599             :                 // gets multiplied with a constant of 1 << 16 to yield 1 << 20 (1MB).
     600             :                 ReadSamplingMultiplier int64
     601             : 
     602             :                 // NumDeletionsThreshold defines the minimum number of point tombstones
     603             :                 // that must be present in a single data block for that block to be
     604             :                 // considered tombstone-dense for the purposes of triggering a
     605             :                 // tombstone density compaction. Data blocks may also be considered
     606             :                 // tombstone-dense if they meet the criteria defined by
     607             :                 // DeletionSizeRatioThreshold below. Tombstone-dense blocks are identified
     608             :                 // when sstables are written, and so this is effectively an option for
     609             :                 // sstable writers. The default value is 100.
     610             :                 NumDeletionsThreshold int
     611             : 
     612             :                 // DeletionSizeRatioThreshold defines the minimum ratio of the size of
     613             :                 // point tombstones to the size of a data block that must be reached
     614             :                 // for that block to be considered tombstone-dense for the purposes of
     615             :                 // triggering a tombstone density compaction. Data blocks may also be
     616             :                 // considered tombstone-dense if they meet the criteria defined by
     617             :                 // NumDeletionsThreshold above. Tombstone-dense blocks are identified
     618             :                 // when sstables are written, and so this is effectively an option for
     619             :                 // sstable writers. The default value is 0.5.
     620             :                 DeletionSizeRatioThreshold float32
     621             : 
     622             :                 // TombstoneDenseCompactionThreshold is the minimum percent of data
     623             :                 // blocks in a table that must be tombstone-dense for that table to be
     624             :                 // eligible for a tombstone density compaction. It should be defined as a
     625             :                 // ratio out of 1. The default value is 0.05.
     626             :                 //
     627             :                 // If multiple tables are eligible for a tombstone density compaction, then
     628             :                 // tables with a higher percent of tombstone-dense blocks are still
     629             :                 // prioritized for compaction.
     630             :                 //
     631             :                 // A zero or negative value disables tombstone density compactions.
     632             :                 TombstoneDenseCompactionThreshold float64
     633             : 
     634             :                 // TableCacheShards is the number of shards per table cache.
     635             :                 // Reducing the value can reduce the number of idle goroutines per DB
     636             :                 // instance which can be useful in scenarios with a lot of DB instances
     637             :                 // and a large number of CPUs, but doing so can lead to higher contention
     638             :                 // in the table cache and reduced performance.
     639             :                 //
     640             :                 // The default value is the number of logical CPUs, which can be
     641             :                 // limited by runtime.GOMAXPROCS.
     642             :                 TableCacheShards int
     643             : 
     644             :                 // KeyValidationFunc is a function to validate a user key in an SSTable.
     645             :                 //
     646             :                 // Currently, this function is used to validate the smallest and largest
     647             :                 // keys in an SSTable undergoing compaction. In this case, returning an
     648             :                 // error from the validation function will result in a panic at runtime,
     649             :                 // given that there is rarely any way of recovering from malformed keys
     650             :                 // present in compacted files. By default, validation is not performed.
     651             :                 //
     652             :                 // Additional use-cases may be added in the future.
     653             :                 //
     654             :                 // NOTE: callers should take care to not mutate the key being validated.
     655             :                 KeyValidationFunc func(userKey []byte) error
     656             : 
     657             :                 // ValidateOnIngest schedules validation of sstables after they have
     658             :                 // been ingested.
     659             :                 //
     660             :                 // By default, this value is false.
     661             :                 ValidateOnIngest bool
     662             : 
     663             :                 // LevelMultiplier configures the size multiplier used to determine the
     664             :                 // desired size of each level of the LSM. Defaults to 10.
     665             :                 LevelMultiplier int
     666             : 
     667             :                 // MultiLevelCompactionHeuristic determines whether to add an additional
     668             :                 // level to a conventional two level compaction. If nil, a multilevel
     669             :                 // compaction will never get triggered.
     670             :                 MultiLevelCompactionHeuristic MultiLevelHeuristic
     671             : 
     672             :                 // MaxWriterConcurrency is used to indicate the maximum number of
     673             :                 // compression workers the compression queue is allowed to use. If
     674             :                 // MaxWriterConcurrency > 0, then the Writer will use parallelism, to
     675             :                 // compress and write blocks to disk. Otherwise, the writer will
     676             :                 // compress and write blocks to disk synchronously.
     677             :                 MaxWriterConcurrency int
     678             : 
     679             :                 // ForceWriterParallelism is used to force parallelism in the sstable
     680             :                 // Writer for the metamorphic tests. Even with the MaxWriterConcurrency
     681             :                 // option set, we only enable parallelism in the sstable Writer if there
     682             :                 // is enough CPU available, and this option bypasses that.
     683             :                 ForceWriterParallelism bool
     684             : 
     685             :                 // CPUWorkPermissionGranter should be set if Pebble should be given the
     686             :                 // ability to optionally schedule additional CPU. See the documentation
     687             :                 // for CPUWorkPermissionGranter for more details.
     688             :                 CPUWorkPermissionGranter CPUWorkPermissionGranter
     689             : 
     690             :                 // EnableValueBlocks is used to decide whether to enable writing
     691             :                 // TableFormatPebblev3 sstables. This setting is only respected by a
     692             :                 // specific subset of format major versions: FormatSSTableValueBlocks,
     693             :                 // FormatFlushableIngest and FormatPrePebblev1MarkedCompacted. In lower
     694             :                 // format major versions, value blocks are never enabled. In higher
     695             :                 // format major versions, value blocks are always enabled.
     696             :                 EnableValueBlocks func() bool
     697             : 
     698             :                 // ShortAttributeExtractor is used iff EnableValueBlocks() returns true
     699             :                 // (else ignored). If non-nil, a ShortAttribute can be extracted from the
     700             :                 // value and stored with the key, when the value is stored elsewhere.
     701             :                 ShortAttributeExtractor ShortAttributeExtractor
     702             : 
     703             :                 // RequiredInPlaceValueBound specifies an optional span of user key
     704             :                 // prefixes that are not-MVCC, but have a suffix. For these the values
     705             :                 // must be stored with the key, since the concept of "older versions" is
     706             :                 // not defined. It is also useful for statically known exclusions to value
     707             :                 // separation. In CockroachDB, this will be used for the lock table key
     708             :                 // space that has non-empty suffixes, but those locks don't represent
     709             :                 // actual MVCC versions (the suffix ordering is arbitrary). We will also
     710             :                 // need to add support for dynamically configured exclusions (we want the
     711             :                 // default to be to allow Pebble to decide whether to separate the value
     712             :                 // or not, hence this is structured as exclusions), for example, for users
     713             :                 // of CockroachDB to dynamically exclude certain tables.
     714             :                 //
     715             :                 // Any change in exclusion behavior takes effect only on future written
     716             :                 // sstables, and does not start rewriting existing sstables.
     717             :                 //
     718             :                 // Even ignoring changes in this setting, exclusions are interpreted as a
     719             :                 // guidance by Pebble, and not necessarily honored. Specifically, user
     720             :                 // keys with multiple Pebble-versions *may* have the older versions stored
     721             :                 // in value blocks.
     722             :                 RequiredInPlaceValueBound UserKeyPrefixBound
     723             : 
     724             :                 // DisableIngestAsFlushable disables lazy ingestion of sstables through
     725             :                 // a WAL write and memtable rotation. Only effectual if the format
     726             :                 // major version is at least `FormatFlushableIngest`.
     727             :                 DisableIngestAsFlushable func() bool
     728             : 
     729             :                 // RemoteStorage enables use of remote storage (e.g. S3) for storing
     730             :                 // sstables. Setting this option enables use of CreateOnShared option and
     731             :                 // allows ingestion of external files.
     732             :                 RemoteStorage remote.StorageFactory
     733             : 
     734             :                 // If CreateOnShared is non-zero, new sstables are created on remote storage
     735             :                 // (using CreateOnSharedLocator and with the appropriate
     736             :                 // CreateOnSharedStrategy). These sstables can be shared between different
     737             :                 // Pebble instances; the lifecycle of such objects is managed by the
     738             :                 // remote.Storage constructed by options.RemoteStorage.
     739             :                 //
     740             :                 // Can only be used when RemoteStorage is set (and recognizes
     741             :                 // CreateOnSharedLocator).
     742             :                 CreateOnShared        remote.CreateOnSharedStrategy
     743             :                 CreateOnSharedLocator remote.Locator
     744             : 
     745             :                 // CacheSizeBytesBytes is the size of the on-disk block cache for objects
     746             :                 // on shared storage in bytes. If it is 0, no cache is used.
     747             :                 SecondaryCacheSizeBytes int64
     748             : 
     749             :                 // NB: DO NOT crash on SingleDeleteInvariantViolationCallback or
     750             :                 // IneffectualSingleDeleteCallback, since these can be false positives
     751             :                 // even if SingleDel has been used correctly.
     752             :                 //
     753             :                 // Pebble's delete-only compactions can cause a recent RANGEDEL to peek
     754             :                 // below an older SINGLEDEL and delete an arbitrary subset of data below
     755             :                 // that SINGLEDEL. When that SINGLEDEL gets compacted (without the
     756             :                 // RANGEDEL), any of these callbacks can happen, without it being a real
     757             :                 // correctness problem.
     758             :                 //
     759             :                 // Example 1:
     760             :                 // RANGEDEL [a, c)#10 in L0
     761             :                 // SINGLEDEL b#5 in L1
     762             :                 // SET b#3 in L6
     763             :                 //
     764             :                 // If the L6 file containing the SET is narrow and the L1 file containing
     765             :                 // the SINGLEDEL is wide, a delete-only compaction can remove the file in
     766             :                 // L2 before the SINGLEDEL is compacted down. Then when the SINGLEDEL is
     767             :                 // compacted down, it will not find any SET to delete, resulting in the
     768             :                 // ineffectual callback.
     769             :                 //
     770             :                 // Example 2:
     771             :                 // RANGEDEL [a, z)#60 in L0
     772             :                 // SINGLEDEL g#50 in L1
     773             :                 // SET g#40 in L2
     774             :                 // RANGEDEL [g,h)#30 in L3
     775             :                 // SET g#20 in L6
     776             :                 //
     777             :                 // In this example, the two SETs represent the same user write, and the
     778             :                 // RANGEDELs are caused by the CockroachDB range being dropped. That is,
     779             :                 // the user wrote to g once, range was dropped, then added back, which
     780             :                 // caused the SET again, then at some point g was validly deleted using a
     781             :                 // SINGLEDEL, and then the range was dropped again. The older RANGEDEL can
     782             :                 // get fragmented due to compactions it has been part of. Say this L3 file
     783             :                 // containing the RANGEDEL is very narrow, while the L1, L2, L6 files are
     784             :                 // wider than the RANGEDEL in L0. Then the RANGEDEL in L3 can be dropped
     785             :                 // using a delete-only compaction, resulting in an LSM with state:
     786             :                 //
     787             :                 // RANGEDEL [a, z)#60 in L0
     788             :                 // SINGLEDEL g#50 in L1
     789             :                 // SET g#40 in L2
     790             :                 // SET g#20 in L6
     791             :                 //
     792             :                 // A multi-level compaction involving L1, L2, L6 will cause the invariant
     793             :                 // violation callback. This example doesn't need multi-level compactions:
     794             :                 // say there was a Pebble snapshot at g#21 preventing g#20 from being
     795             :                 // dropped when it meets g#40 in a compaction. That snapshot will not save
     796             :                 // RANGEDEL [g,h)#30, so we can have:
     797             :                 //
     798             :                 // SINGLEDEL g#50 in L1
     799             :                 // SET g#40, SET g#20 in L6
     800             :                 //
     801             :                 // And say the snapshot is removed and then the L1 and L6 compaction
     802             :                 // happens, resulting in the invariant violation callback.
     803             :                 //
     804             :                 // TODO(sumeer): rename SingleDeleteInvariantViolationCallback to remove
     805             :                 // the word "invariant".
     806             : 
     807             :                 // IneffectualPointDeleteCallback is called in compactions/flushes if any
     808             :                 // single delete is being elided without deleting a point set/merge.
     809             :                 IneffectualSingleDeleteCallback func(userKey []byte)
     810             : 
     811             :                 // SingleDeleteInvariantViolationCallback is called in compactions/flushes if any
     812             :                 // single delete has consumed a Set/Merge, and there is another immediately older
     813             :                 // Set/SetWithDelete/Merge. The user of Pebble has violated the invariant under
     814             :                 // which SingleDelete can be used correctly.
     815             :                 //
     816             :                 // Consider the sequence SingleDelete#3, Set#2, Set#1. There are three
     817             :                 // ways some of these keys can first meet in a compaction.
     818             :                 //
     819             :                 // - All 3 keys in the same compaction: this callback will detect the
     820             :                 //   violation.
     821             :                 //
     822             :                 // - SingleDelete#3, Set#2 meet in a compaction first: Both keys will
     823             :                 //   disappear. The violation will not be detected, and the DB will have
     824             :                 //   Set#1 which is likely incorrect (from the user's perspective).
     825             :                 //
     826             :                 // - Set#2, Set#1 meet in a compaction first: The output will be Set#2,
     827             :                 //   which will later be consumed by SingleDelete#3. The violation will
     828             :                 //   not be detected and the DB will be correct.
     829             :                 SingleDeleteInvariantViolationCallback func(userKey []byte)
     830             :         }
     831             : 
     832             :         // Filters is a map from filter policy name to filter policy. It is used for
     833             :         // debugging tools which may be used on multiple databases configured with
     834             :         // different filter policies. It is not necessary to populate this filters
     835             :         // map during normal usage of a DB (it will be done automatically by
     836             :         // EnsureDefaults).
     837             :         Filters map[string]FilterPolicy
     838             : 
     839             :         // FlushDelayDeleteRange configures how long the database should wait before
     840             :         // forcing a flush of a memtable that contains a range deletion. Disk space
     841             :         // cannot be reclaimed until the range deletion is flushed. No automatic
     842             :         // flush occurs if zero.
     843             :         FlushDelayDeleteRange time.Duration
     844             : 
     845             :         // FlushDelayRangeKey configures how long the database should wait before
     846             :         // forcing a flush of a memtable that contains a range key. Range keys in
     847             :         // the memtable prevent lazy combined iteration, so it's desirable to flush
     848             :         // range keys promptly. No automatic flush occurs if zero.
     849             :         FlushDelayRangeKey time.Duration
     850             : 
     851             :         // FlushSplitBytes denotes the target number of bytes per sublevel in
     852             :         // each flush split interval (i.e. range between two flush split keys)
     853             :         // in L0 sstables. When set to zero, only a single sstable is generated
     854             :         // by each flush. When set to a non-zero value, flushes are split at
     855             :         // points to meet L0's TargetFileSize, any grandparent-related overlap
     856             :         // options, and at boundary keys of L0 flush split intervals (which are
     857             :         // targeted to contain around FlushSplitBytes bytes in each sublevel
     858             :         // between pairs of boundary keys). Splitting sstables during flush
     859             :         // allows increased compaction flexibility and concurrency when those
     860             :         // tables are compacted to lower levels.
     861             :         FlushSplitBytes int64
     862             : 
     863             :         // FormatMajorVersion sets the format of on-disk files. It is
     864             :         // recommended to set the format major version to an explicit
     865             :         // version, as the default may change over time.
     866             :         //
     867             :         // At Open if the existing database is formatted using a later
     868             :         // format major version that is known to this version of Pebble,
     869             :         // Pebble will continue to use the later format major version. If
     870             :         // the existing database's version is unknown, the caller may use
     871             :         // FormatMostCompatible and will be able to open the database
     872             :         // regardless of its actual version.
     873             :         //
     874             :         // If the existing database is formatted using a format major
     875             :         // version earlier than the one specified, Open will automatically
     876             :         // ratchet the database to the specified format major version.
     877             :         FormatMajorVersion FormatMajorVersion
     878             : 
     879             :         // FS provides the interface for persistent file storage.
     880             :         //
     881             :         // The default value uses the underlying operating system's file system.
     882             :         FS vfs.FS
     883             : 
     884             :         // Lock, if set, must be a database lock acquired through LockDirectory for
     885             :         // the same directory passed to Open. If provided, Open will skip locking
     886             :         // the directory. Closing the database will not release the lock, and it's
     887             :         // the responsibility of the caller to release the lock after closing the
     888             :         // database.
     889             :         //
     890             :         // Open will enforce that the Lock passed locks the same directory passed to
     891             :         // Open. Concurrent calls to Open using the same Lock are detected and
     892             :         // prohibited.
     893             :         Lock *Lock
     894             : 
     895             :         // The count of L0 files necessary to trigger an L0 compaction.
     896             :         L0CompactionFileThreshold int
     897             : 
     898             :         // The amount of L0 read-amplification necessary to trigger an L0 compaction.
     899             :         L0CompactionThreshold int
     900             : 
     901             :         // Hard limit on L0 read-amplification, computed as the number of L0
     902             :         // sublevels. Writes are stopped when this threshold is reached.
     903             :         L0StopWritesThreshold int
     904             : 
     905             :         // The maximum number of bytes for LBase. The base level is the level which
     906             :         // L0 is compacted into. The base level is determined dynamically based on
     907             :         // the existing data in the LSM. The maximum number of bytes for other levels
     908             :         // is computed dynamically based on the base level's maximum size. When the
     909             :         // maximum number of bytes for a level is exceeded, compaction is requested.
     910             :         LBaseMaxBytes int64
     911             : 
     912             :         // Per-level options. Options for at least one level must be specified. The
     913             :         // options for the last level are used for all subsequent levels.
     914             :         Levels []LevelOptions
     915             : 
     916             :         // LoggerAndTracer will be used, if non-nil, else Logger will be used and
     917             :         // tracing will be a noop.
     918             : 
     919             :         // Logger used to write log messages.
     920             :         //
     921             :         // The default logger uses the Go standard library log package.
     922             :         Logger Logger
     923             :         // LoggerAndTracer is used for writing log messages and traces.
     924             :         LoggerAndTracer LoggerAndTracer
     925             : 
     926             :         // MaxManifestFileSize is the maximum size the MANIFEST file is allowed to
     927             :         // become. When the MANIFEST exceeds this size it is rolled over and a new
     928             :         // MANIFEST is created.
     929             :         MaxManifestFileSize int64
     930             : 
     931             :         // MaxOpenFiles is a soft limit on the number of open files that can be
     932             :         // used by the DB.
     933             :         //
     934             :         // The default value is 1000.
     935             :         MaxOpenFiles int
     936             : 
     937             :         // The size of a MemTable in steady state. The actual MemTable size starts at
     938             :         // min(256KB, MemTableSize) and doubles for each subsequent MemTable up to
     939             :         // MemTableSize. This reduces the memory pressure caused by MemTables for
     940             :         // short lived (test) DB instances. Note that more than one MemTable can be
     941             :         // in existence since flushing a MemTable involves creating a new one and
     942             :         // writing the contents of the old one in the
     943             :         // background. MemTableStopWritesThreshold places a hard limit on the size of
     944             :         // the queued MemTables.
     945             :         //
     946             :         // The default value is 4MB.
     947             :         MemTableSize uint64
     948             : 
     949             :         // Hard limit on the number of queued of MemTables. Writes are stopped when
     950             :         // the sum of the queued memtable sizes exceeds:
     951             :         //   MemTableStopWritesThreshold * MemTableSize.
     952             :         //
     953             :         // This value should be at least 2 or writes will stop whenever a MemTable is
     954             :         // being flushed.
     955             :         //
     956             :         // The default value is 2.
     957             :         MemTableStopWritesThreshold int
     958             : 
     959             :         // Merger defines the associative merge operation to use for merging values
     960             :         // written with {Batch,DB}.Merge.
     961             :         //
     962             :         // The default merger concatenates values.
     963             :         Merger *Merger
     964             : 
     965             :         // MaxConcurrentCompactions specifies the maximum number of concurrent
     966             :         // compactions (not including download compactions).
     967             :         //
     968             :         // Concurrent compactions are performed:
     969             :         //  - when L0 read-amplification passes the L0CompactionConcurrency threshold;
     970             :         //  - for automatic background compactions;
     971             :         //  - when a manual compaction for a level is split and parallelized.
     972             :         //
     973             :         // MaxConcurrentCompactions() must be greater than 0.
     974             :         //
     975             :         // The default value is 1.
     976             :         MaxConcurrentCompactions func() int
     977             : 
     978             :         // MaxConcurrentDownloads specifies the maximum number of download
     979             :         // compactions. These are compactions that copy an external file to the local
     980             :         // store.
     981             :         //
     982             :         // This limit is independent of MaxConcurrentCompactions; at any point in
     983             :         // time, we may be running MaxConcurrentCompactions non-download compactions
     984             :         // and MaxConcurrentDownloads download compactions.
     985             :         //
     986             :         // MaxConcurrentDownloads() must be greater than 0.
     987             :         //
     988             :         // The default value is 1.
     989             :         MaxConcurrentDownloads func() int
     990             : 
     991             :         // DisableAutomaticCompactions dictates whether automatic compactions are
     992             :         // scheduled or not. The default is false (enabled). This option is only used
     993             :         // externally when running a manual compaction, and internally for tests.
     994             :         DisableAutomaticCompactions bool
     995             : 
     996             :         // DisableConsistencyCheck disables the consistency check that is performed on
     997             :         // open. Should only be used when a database cannot be opened normally (e.g.
     998             :         // some of the tables don't exist / aren't accessible).
     999             :         DisableConsistencyCheck bool
    1000             : 
    1001             :         // DisableTableStats dictates whether tables should be loaded asynchronously
    1002             :         // to compute statistics that inform compaction heuristics. The collection
    1003             :         // of table stats improves compaction of tombstones, reclaiming disk space
    1004             :         // more quickly and in some cases reducing write amplification in the
    1005             :         // presence of tombstones. Disabling table stats may be useful in tests
    1006             :         // that require determinism as the asynchronicity of table stats collection
    1007             :         // introduces significant nondeterminism.
    1008             :         DisableTableStats bool
    1009             : 
    1010             :         // NoSyncOnClose decides whether the Pebble instance will enforce a
    1011             :         // close-time synchronization (e.g., fdatasync() or sync_file_range())
    1012             :         // on files it writes to. Setting this to true removes the guarantee for a
    1013             :         // sync on close. Some implementations can still issue a non-blocking sync.
    1014             :         NoSyncOnClose bool
    1015             : 
    1016             :         // NumPrevManifest is the number of non-current or older manifests which
    1017             :         // we want to keep around for debugging purposes. By default, we're going
    1018             :         // to keep one older manifest.
    1019             :         NumPrevManifest int
    1020             : 
    1021             :         // ReadOnly indicates that the DB should be opened in read-only mode. Writes
    1022             :         // to the DB will return an error, background compactions are disabled, and
    1023             :         // the flush that normally occurs after replaying the WAL at startup is
    1024             :         // disabled.
    1025             :         ReadOnly bool
    1026             : 
    1027             :         // TableCache is an initialized TableCache which should be set as an
    1028             :         // option if the DB needs to be initialized with a pre-existing table cache.
    1029             :         // If TableCache is nil, then a table cache which is unique to the DB instance
    1030             :         // is created. TableCache can be shared between db instances by setting it here.
    1031             :         // The TableCache set here must use the same underlying cache as Options.Cache
    1032             :         // and pebble will panic otherwise.
    1033             :         TableCache *TableCache
    1034             : 
    1035             :         // BlockPropertyCollectors is a list of BlockPropertyCollector creation
    1036             :         // functions. A new BlockPropertyCollector is created for each sstable
    1037             :         // built and lives for the lifetime of writing that table.
    1038             :         BlockPropertyCollectors []func() BlockPropertyCollector
    1039             : 
    1040             :         // WALBytesPerSync sets the number of bytes to write to a WAL before calling
    1041             :         // Sync on it in the background. Just like with BytesPerSync above, this
    1042             :         // helps smooth out disk write latencies, and avoids cases where the OS
    1043             :         // writes a lot of buffered data to disk at once. However, this is less
    1044             :         // necessary with WALs, as many write operations already pass in
    1045             :         // Sync = true.
    1046             :         //
    1047             :         // The default value is 0, i.e. no background syncing. This matches the
    1048             :         // default behaviour in RocksDB.
    1049             :         WALBytesPerSync int
    1050             : 
    1051             :         // WALDir specifies the directory to store write-ahead logs (WALs) in. If
    1052             :         // empty (the default), WALs will be stored in the same directory as sstables
    1053             :         // (i.e. the directory passed to pebble.Open).
    1054             :         WALDir string
    1055             : 
    1056             :         // WALFailover may be set to configure Pebble to monitor writes to its
    1057             :         // write-ahead log and failover to writing write-ahead log entries to a
    1058             :         // secondary location (eg, a separate physical disk). WALFailover may be
    1059             :         // used to improve write availability in the presence of transient disk
    1060             :         // unavailability.
    1061             :         WALFailover *WALFailoverOptions
    1062             : 
    1063             :         // WALRecoveryDirs is a list of additional directories that should be
    1064             :         // scanned for the existence of additional write-ahead logs. WALRecoveryDirs
    1065             :         // is expected to be used when starting Pebble with a new WALDir or a new
    1066             :         // WALFailover configuration. The directories associated with the previous
    1067             :         // configuration may still contain WALs that are required for recovery of
    1068             :         // the current database state.
    1069             :         //
    1070             :         // If a previous WAL configuration may have stored WALs elsewhere but there
    1071             :         // is not a corresponding entry in WALRecoveryDirs, Open will error.
    1072             :         WALRecoveryDirs []wal.Dir
    1073             : 
    1074             :         // WALMinSyncInterval is the minimum duration between syncs of the WAL. If
    1075             :         // WAL syncs are requested faster than this interval, they will be
    1076             :         // artificially delayed. Introducing a small artificial delay (500us) between
    1077             :         // WAL syncs can allow more operations to arrive and reduce IO operations
    1078             :         // while having a minimal impact on throughput. This option is supplied as a
    1079             :         // closure in order to allow the value to be changed dynamically. The default
    1080             :         // value is 0.
    1081             :         //
    1082             :         // TODO(peter): rather than a closure, should there be another mechanism for
    1083             :         // changing options dynamically?
    1084             :         WALMinSyncInterval func() time.Duration
    1085             : 
    1086             :         // TargetByteDeletionRate is the rate (in bytes per second) at which sstable file
    1087             :         // deletions are limited to (under normal circumstances).
    1088             :         //
    1089             :         // Deletion pacing is used to slow down deletions when compactions finish up
    1090             :         // or readers close and newly-obsolete files need cleaning up. Deleting lots
    1091             :         // of files at once can cause disk latency to go up on some SSDs, which this
    1092             :         // functionality guards against.
    1093             :         //
    1094             :         // This value is only a best-effort target; the effective rate can be
    1095             :         // higher if deletions are falling behind or disk space is running low.
    1096             :         //
    1097             :         // Setting this to 0 disables deletion pacing, which is also the default.
    1098             :         TargetByteDeletionRate int
    1099             : 
    1100             :         // EnableSQLRowSpillMetrics specifies whether the Pebble instance will only be used
    1101             :         // to temporarily persist data spilled to disk for row-oriented SQL query execution.
    1102             :         EnableSQLRowSpillMetrics bool
    1103             : 
    1104             :         // AllocatorSizeClasses provides a sorted list containing the supported size
    1105             :         // classes of the underlying memory allocator. This provides hints to the
    1106             :         // sstable block writer's flushing policy to select block sizes that
    1107             :         // preemptively reduce internal fragmentation when loaded into the block cache.
    1108             :         AllocatorSizeClasses []int
    1109             : 
    1110             :         // private options are only used by internal tests or are used internally
    1111             :         // for facilitating upgrade paths of unconfigurable functionality.
    1112             :         private struct {
    1113             :                 // disableDeleteOnlyCompactions prevents the scheduling of delete-only
    1114             :                 // compactions that drop sstables wholy covered by range tombstones or
    1115             :                 // range key tombstones.
    1116             :                 disableDeleteOnlyCompactions bool
    1117             : 
    1118             :                 // disableElisionOnlyCompactions prevents the scheduling of elision-only
    1119             :                 // compactions that rewrite sstables in place in order to elide obsolete
    1120             :                 // keys.
    1121             :                 disableElisionOnlyCompactions bool
    1122             : 
    1123             :                 // disableLazyCombinedIteration is a private option used by the
    1124             :                 // metamorphic tests to test equivalence between lazy-combined iteration
    1125             :                 // and constructing the range-key iterator upfront. It's a private
    1126             :                 // option to avoid littering the public interface with options that we
    1127             :                 // do not want to allow users to actually configure.
    1128             :                 disableLazyCombinedIteration bool
    1129             : 
    1130             :                 // testingAlwaysWaitForCleanup is set by some tests to force waiting for
    1131             :                 // obsolete file deletion (to make events deterministic).
    1132             :                 testingAlwaysWaitForCleanup bool
    1133             : 
    1134             :                 // fsCloser holds a closer that should be invoked after a DB using these
    1135             :                 // Options is closed. This is used to automatically stop the
    1136             :                 // long-running goroutine associated with the disk-health-checking FS.
    1137             :                 // See the initialization of FS in EnsureDefaults. Note that care has
    1138             :                 // been taken to ensure that it is still safe to continue using the FS
    1139             :                 // after this closer has been invoked. However, if write operations
    1140             :                 // against the FS are made after the DB is closed, the FS may leak a
    1141             :                 // goroutine indefinitely.
    1142             :                 fsCloser io.Closer
    1143             :         }
    1144             : }
    1145             : 
    1146             : // WALFailoverOptions configures the WAL failover mechanics to use during
    1147             : // transient write unavailability on the primary WAL volume.
    1148             : type WALFailoverOptions struct {
    1149             :         // Secondary indicates the secondary directory and VFS to use in the event a
    1150             :         // write to the primary WAL stalls.
    1151             :         Secondary wal.Dir
    1152             :         // FailoverOptions provides configuration of the thresholds and intervals
    1153             :         // involved in WAL failover. If any of its fields are left unspecified,
    1154             :         // reasonable defaults will be used.
    1155             :         wal.FailoverOptions
    1156             : }
    1157             : 
    1158             : // ReadaheadConfig controls the use of read-ahead.
    1159             : type ReadaheadConfig = objstorageprovider.ReadaheadConfig
    1160             : 
    1161             : // DebugCheckLevels calls CheckLevels on the provided database.
    1162             : // It may be set in the DebugCheck field of Options to check
    1163             : // level invariants whenever a new version is installed.
    1164           1 : func DebugCheckLevels(db *DB) error {
    1165           1 :         return db.CheckLevels(nil)
    1166           1 : }
    1167             : 
    1168             : // EnsureDefaults ensures that the default values for all options are set if a
    1169             : // valid value was not already specified. Returns the new options.
    1170           1 : func (o *Options) EnsureDefaults() *Options {
    1171           1 :         if o == nil {
    1172           1 :                 o = &Options{}
    1173           1 :         }
    1174           1 :         o.Comparer = o.Comparer.EnsureDefaults()
    1175           1 : 
    1176           1 :         if o.BytesPerSync <= 0 {
    1177           1 :                 o.BytesPerSync = 512 << 10 // 512 KB
    1178           1 :         }
    1179           1 :         if o.Cleaner == nil {
    1180           1 :                 o.Cleaner = DeleteCleaner{}
    1181           1 :         }
    1182             : 
    1183           1 :         if o.Experimental.DisableIngestAsFlushable == nil {
    1184           1 :                 o.Experimental.DisableIngestAsFlushable = func() bool { return false }
    1185             :         }
    1186           1 :         if o.Experimental.L0CompactionConcurrency <= 0 {
    1187           1 :                 o.Experimental.L0CompactionConcurrency = 10
    1188           1 :         }
    1189           1 :         if o.Experimental.CompactionDebtConcurrency <= 0 {
    1190           1 :                 o.Experimental.CompactionDebtConcurrency = 1 << 30 // 1 GB
    1191           1 :         }
    1192           1 :         if o.Experimental.KeyValidationFunc == nil {
    1193           1 :                 o.Experimental.KeyValidationFunc = func([]byte) error { return nil }
    1194             :         }
    1195           1 :         if o.L0CompactionThreshold <= 0 {
    1196           1 :                 o.L0CompactionThreshold = 4
    1197           1 :         }
    1198           1 :         if o.L0CompactionFileThreshold <= 0 {
    1199           1 :                 // Some justification for the default of 500:
    1200           1 :                 // Why not smaller?:
    1201           1 :                 // - The default target file size for L0 is 2MB, so 500 files is <= 1GB
    1202           1 :                 //   of data. At observed compaction speeds of > 20MB/s, L0 can be
    1203           1 :                 //   cleared of all files in < 1min, so this backlog is not huge.
    1204           1 :                 // - 500 files is low overhead for instantiating L0 sublevels from
    1205           1 :                 //   scratch.
    1206           1 :                 // - Lower values were observed to cause excessive and inefficient
    1207           1 :                 //   compactions out of L0 in a TPCC import benchmark.
    1208           1 :                 // Why not larger?:
    1209           1 :                 // - More than 1min to compact everything out of L0.
    1210           1 :                 // - CockroachDB's admission control system uses a threshold of 1000
    1211           1 :                 //   files to start throttling writes to Pebble. Using 500 here gives
    1212           1 :                 //   us headroom between when Pebble should start compacting L0 and
    1213           1 :                 //   when the admission control threshold is reached.
    1214           1 :                 //
    1215           1 :                 // We can revisit this default in the future based on better
    1216           1 :                 // experimental understanding.
    1217           1 :                 //
    1218           1 :                 // TODO(jackson): Experiment with slightly lower thresholds [or higher
    1219           1 :                 // admission control thresholds] to see whether a higher L0 score at the
    1220           1 :                 // threshold (currently 2.0) is necessary for some workloads to avoid
    1221           1 :                 // starving L0 in favor of lower-level compactions.
    1222           1 :                 o.L0CompactionFileThreshold = 500
    1223           1 :         }
    1224           1 :         if o.L0StopWritesThreshold <= 0 {
    1225           1 :                 o.L0StopWritesThreshold = 12
    1226           1 :         }
    1227           1 :         if o.LBaseMaxBytes <= 0 {
    1228           1 :                 o.LBaseMaxBytes = 64 << 20 // 64 MB
    1229           1 :         }
    1230           1 :         if o.Levels == nil {
    1231           1 :                 o.Levels = make([]LevelOptions, 1)
    1232           1 :                 for i := range o.Levels {
    1233           1 :                         if i > 0 {
    1234           0 :                                 l := &o.Levels[i]
    1235           0 :                                 if l.TargetFileSize <= 0 {
    1236           0 :                                         l.TargetFileSize = o.Levels[i-1].TargetFileSize * 2
    1237           0 :                                 }
    1238             :                         }
    1239           1 :                         o.Levels[i].EnsureDefaults()
    1240             :                 }
    1241           1 :         } else {
    1242           1 :                 for i := range o.Levels {
    1243           1 :                         o.Levels[i].EnsureDefaults()
    1244           1 :                 }
    1245             :         }
    1246           1 :         if o.Logger == nil {
    1247           1 :                 o.Logger = DefaultLogger
    1248           1 :         }
    1249           1 :         if o.EventListener == nil {
    1250           1 :                 o.EventListener = &EventListener{}
    1251           1 :         }
    1252           1 :         o.EventListener.EnsureDefaults(o.Logger)
    1253           1 :         if o.MaxManifestFileSize == 0 {
    1254           1 :                 o.MaxManifestFileSize = 128 << 20 // 128 MB
    1255           1 :         }
    1256           1 :         if o.MaxOpenFiles == 0 {
    1257           1 :                 o.MaxOpenFiles = 1000
    1258           1 :         }
    1259           1 :         if o.MemTableSize <= 0 {
    1260           1 :                 o.MemTableSize = 4 << 20 // 4 MB
    1261           1 :         }
    1262           1 :         if o.MemTableStopWritesThreshold <= 0 {
    1263           1 :                 o.MemTableStopWritesThreshold = 2
    1264           1 :         }
    1265           1 :         if o.Merger == nil {
    1266           1 :                 o.Merger = DefaultMerger
    1267           1 :         }
    1268           1 :         if o.MaxConcurrentCompactions == nil {
    1269           1 :                 o.MaxConcurrentCompactions = func() int { return 1 }
    1270             :         }
    1271           1 :         if o.MaxConcurrentDownloads == nil {
    1272           1 :                 o.MaxConcurrentDownloads = func() int { return 1 }
    1273             :         }
    1274           1 :         if o.NumPrevManifest <= 0 {
    1275           1 :                 o.NumPrevManifest = 1
    1276           1 :         }
    1277             : 
    1278           1 :         if o.FormatMajorVersion == FormatDefault {
    1279           1 :                 o.FormatMajorVersion = FormatMinSupported
    1280           1 :                 if o.Experimental.CreateOnShared != remote.CreateOnSharedNone {
    1281           1 :                         o.FormatMajorVersion = FormatMinForSharedObjects
    1282           1 :                 }
    1283             :         }
    1284             : 
    1285           1 :         if o.FS == nil {
    1286           1 :                 o.WithFSDefaults()
    1287           1 :         }
    1288           1 :         if o.FlushSplitBytes <= 0 {
    1289           1 :                 o.FlushSplitBytes = 2 * o.Levels[0].TargetFileSize
    1290           1 :         }
    1291           1 :         if o.WALFailover != nil {
    1292           1 :                 o.WALFailover.FailoverOptions.EnsureDefaults()
    1293           1 :         }
    1294           1 :         if o.Experimental.LevelMultiplier <= 0 {
    1295           1 :                 o.Experimental.LevelMultiplier = defaultLevelMultiplier
    1296           1 :         }
    1297           1 :         if o.Experimental.ReadCompactionRate == 0 {
    1298           1 :                 o.Experimental.ReadCompactionRate = 16000
    1299           1 :         }
    1300           1 :         if o.Experimental.ReadSamplingMultiplier == 0 {
    1301           1 :                 o.Experimental.ReadSamplingMultiplier = 1 << 4
    1302           1 :         }
    1303           1 :         if o.Experimental.NumDeletionsThreshold == 0 {
    1304           1 :                 o.Experimental.NumDeletionsThreshold = sstable.DefaultNumDeletionsThreshold
    1305           1 :         }
    1306           1 :         if o.Experimental.DeletionSizeRatioThreshold == 0 {
    1307           1 :                 o.Experimental.DeletionSizeRatioThreshold = sstable.DefaultDeletionSizeRatioThreshold
    1308           1 :         }
    1309           1 :         if o.Experimental.TombstoneDenseCompactionThreshold == 0 {
    1310           1 :                 o.Experimental.TombstoneDenseCompactionThreshold = 0.05
    1311           1 :         }
    1312           1 :         if o.Experimental.TableCacheShards <= 0 {
    1313           1 :                 o.Experimental.TableCacheShards = runtime.GOMAXPROCS(0)
    1314           1 :         }
    1315           1 :         if o.Experimental.CPUWorkPermissionGranter == nil {
    1316           1 :                 o.Experimental.CPUWorkPermissionGranter = defaultCPUWorkGranter{}
    1317           1 :         }
    1318           1 :         if o.Experimental.MultiLevelCompactionHeuristic == nil {
    1319           1 :                 o.Experimental.MultiLevelCompactionHeuristic = WriteAmpHeuristic{}
    1320           1 :         }
    1321             : 
    1322           1 :         o.initMaps()
    1323           1 :         return o
    1324             : }
    1325             : 
    1326             : // WithFSDefaults configures the Options to wrap the configured filesystem with
    1327             : // the default virtual file system middleware, like disk-health checking.
    1328           1 : func (o *Options) WithFSDefaults() *Options {
    1329           1 :         if o.FS == nil {
    1330           1 :                 o.FS = vfs.Default
    1331           1 :         }
    1332           1 :         o.FS, o.private.fsCloser = vfs.WithDiskHealthChecks(o.FS, 5*time.Second, nil,
    1333           1 :                 func(info vfs.DiskSlowInfo) {
    1334           0 :                         o.EventListener.DiskSlow(info)
    1335           0 :                 })
    1336           1 :         return o
    1337             : }
    1338             : 
    1339             : // AddEventListener adds the provided event listener to the Options, in addition
    1340             : // to any existing event listener.
    1341           1 : func (o *Options) AddEventListener(l EventListener) {
    1342           1 :         if o.EventListener != nil {
    1343           1 :                 l = TeeEventListener(l, *o.EventListener)
    1344           1 :         }
    1345           1 :         o.EventListener = &l
    1346             : }
    1347             : 
    1348             : // initMaps initializes the Comparers, Filters, and Mergers maps.
    1349           1 : func (o *Options) initMaps() {
    1350           1 :         for i := range o.Levels {
    1351           1 :                 l := &o.Levels[i]
    1352           1 :                 if l.FilterPolicy != nil {
    1353           1 :                         if o.Filters == nil {
    1354           1 :                                 o.Filters = make(map[string]FilterPolicy)
    1355           1 :                         }
    1356           1 :                         name := l.FilterPolicy.Name()
    1357           1 :                         if _, ok := o.Filters[name]; !ok {
    1358           1 :                                 o.Filters[name] = l.FilterPolicy
    1359           1 :                         }
    1360             :                 }
    1361             :         }
    1362             : }
    1363             : 
    1364             : // Level returns the LevelOptions for the specified level.
    1365           1 : func (o *Options) Level(level int) LevelOptions {
    1366           1 :         if level < len(o.Levels) {
    1367           1 :                 return o.Levels[level]
    1368           1 :         }
    1369           1 :         n := len(o.Levels) - 1
    1370           1 :         l := o.Levels[n]
    1371           1 :         for i := n; i < level; i++ {
    1372           1 :                 l.TargetFileSize *= 2
    1373           1 :         }
    1374           1 :         return l
    1375             : }
    1376             : 
    1377             : // Clone creates a shallow-copy of the supplied options.
    1378           1 : func (o *Options) Clone() *Options {
    1379           1 :         n := &Options{}
    1380           1 :         if o != nil {
    1381           1 :                 *n = *o
    1382           1 :         }
    1383           1 :         return n
    1384             : }
    1385             : 
    1386           1 : func filterPolicyName(p FilterPolicy) string {
    1387           1 :         if p == nil {
    1388           1 :                 return "none"
    1389           1 :         }
    1390           1 :         return p.Name()
    1391             : }
    1392             : 
    1393           1 : func (o *Options) String() string {
    1394           1 :         var buf bytes.Buffer
    1395           1 : 
    1396           1 :         cacheSize := int64(cacheDefaultSize)
    1397           1 :         if o.Cache != nil {
    1398           1 :                 cacheSize = o.Cache.MaxSize()
    1399           1 :         }
    1400             : 
    1401           1 :         fmt.Fprintf(&buf, "[Version]\n")
    1402           1 :         fmt.Fprintf(&buf, "  pebble_version=0.1\n")
    1403           1 :         fmt.Fprintf(&buf, "\n")
    1404           1 :         fmt.Fprintf(&buf, "[Options]\n")
    1405           1 :         fmt.Fprintf(&buf, "  bytes_per_sync=%d\n", o.BytesPerSync)
    1406           1 :         fmt.Fprintf(&buf, "  cache_size=%d\n", cacheSize)
    1407           1 :         fmt.Fprintf(&buf, "  cleaner=%s\n", o.Cleaner)
    1408           1 :         fmt.Fprintf(&buf, "  compaction_debt_concurrency=%d\n", o.Experimental.CompactionDebtConcurrency)
    1409           1 :         fmt.Fprintf(&buf, "  comparer=%s\n", o.Comparer.Name)
    1410           1 :         fmt.Fprintf(&buf, "  disable_wal=%t\n", o.DisableWAL)
    1411           1 :         if o.Experimental.DisableIngestAsFlushable != nil && o.Experimental.DisableIngestAsFlushable() {
    1412           1 :                 fmt.Fprintf(&buf, "  disable_ingest_as_flushable=%t\n", true)
    1413           1 :         }
    1414           1 :         fmt.Fprintf(&buf, "  flush_delay_delete_range=%s\n", o.FlushDelayDeleteRange)
    1415           1 :         fmt.Fprintf(&buf, "  flush_delay_range_key=%s\n", o.FlushDelayRangeKey)
    1416           1 :         fmt.Fprintf(&buf, "  flush_split_bytes=%d\n", o.FlushSplitBytes)
    1417           1 :         fmt.Fprintf(&buf, "  format_major_version=%d\n", o.FormatMajorVersion)
    1418           1 :         fmt.Fprintf(&buf, "  l0_compaction_concurrency=%d\n", o.Experimental.L0CompactionConcurrency)
    1419           1 :         fmt.Fprintf(&buf, "  l0_compaction_file_threshold=%d\n", o.L0CompactionFileThreshold)
    1420           1 :         fmt.Fprintf(&buf, "  l0_compaction_threshold=%d\n", o.L0CompactionThreshold)
    1421           1 :         fmt.Fprintf(&buf, "  l0_stop_writes_threshold=%d\n", o.L0StopWritesThreshold)
    1422           1 :         fmt.Fprintf(&buf, "  lbase_max_bytes=%d\n", o.LBaseMaxBytes)
    1423           1 :         if o.Experimental.LevelMultiplier != defaultLevelMultiplier {
    1424           1 :                 fmt.Fprintf(&buf, "  level_multiplier=%d\n", o.Experimental.LevelMultiplier)
    1425           1 :         }
    1426           1 :         fmt.Fprintf(&buf, "  max_concurrent_compactions=%d\n", o.MaxConcurrentCompactions())
    1427           1 :         fmt.Fprintf(&buf, "  max_concurrent_downloads=%d\n", o.MaxConcurrentDownloads())
    1428           1 :         fmt.Fprintf(&buf, "  max_manifest_file_size=%d\n", o.MaxManifestFileSize)
    1429           1 :         fmt.Fprintf(&buf, "  max_open_files=%d\n", o.MaxOpenFiles)
    1430           1 :         fmt.Fprintf(&buf, "  mem_table_size=%d\n", o.MemTableSize)
    1431           1 :         fmt.Fprintf(&buf, "  mem_table_stop_writes_threshold=%d\n", o.MemTableStopWritesThreshold)
    1432           1 :         fmt.Fprintf(&buf, "  min_deletion_rate=%d\n", o.TargetByteDeletionRate)
    1433           1 :         fmt.Fprintf(&buf, "  merger=%s\n", o.Merger.Name)
    1434           1 :         if o.Experimental.MultiLevelCompactionHeuristic != nil {
    1435           1 :                 fmt.Fprintf(&buf, "  multilevel_compaction_heuristic=%s\n", o.Experimental.MultiLevelCompactionHeuristic.String())
    1436           1 :         }
    1437           1 :         fmt.Fprintf(&buf, "  read_compaction_rate=%d\n", o.Experimental.ReadCompactionRate)
    1438           1 :         fmt.Fprintf(&buf, "  read_sampling_multiplier=%d\n", o.Experimental.ReadSamplingMultiplier)
    1439           1 :         fmt.Fprintf(&buf, "  num_deletions_threshold=%d\n", o.Experimental.NumDeletionsThreshold)
    1440           1 :         fmt.Fprintf(&buf, "  deletion_size_ratio_threshold=%f\n", o.Experimental.DeletionSizeRatioThreshold)
    1441           1 :         fmt.Fprintf(&buf, "  tombstone_dense_compaction_threshold=%f\n", o.Experimental.TombstoneDenseCompactionThreshold)
    1442           1 :         // We no longer care about strict_wal_tail, but set it to true in case an
    1443           1 :         // older version reads the options.
    1444           1 :         fmt.Fprintf(&buf, "  strict_wal_tail=%t\n", true)
    1445           1 :         fmt.Fprintf(&buf, "  table_cache_shards=%d\n", o.Experimental.TableCacheShards)
    1446           1 :         fmt.Fprintf(&buf, "  validate_on_ingest=%t\n", o.Experimental.ValidateOnIngest)
    1447           1 :         fmt.Fprintf(&buf, "  wal_dir=%s\n", o.WALDir)
    1448           1 :         fmt.Fprintf(&buf, "  wal_bytes_per_sync=%d\n", o.WALBytesPerSync)
    1449           1 :         fmt.Fprintf(&buf, "  max_writer_concurrency=%d\n", o.Experimental.MaxWriterConcurrency)
    1450           1 :         fmt.Fprintf(&buf, "  force_writer_parallelism=%t\n", o.Experimental.ForceWriterParallelism)
    1451           1 :         fmt.Fprintf(&buf, "  secondary_cache_size_bytes=%d\n", o.Experimental.SecondaryCacheSizeBytes)
    1452           1 :         fmt.Fprintf(&buf, "  create_on_shared=%d\n", o.Experimental.CreateOnShared)
    1453           1 : 
    1454           1 :         // Private options.
    1455           1 :         //
    1456           1 :         // These options are only encoded if true, because we do not want them to
    1457           1 :         // appear in production serialized Options files, since they're testing-only
    1458           1 :         // options. They're only serialized when true, which still ensures that the
    1459           1 :         // metamorphic tests may propagate them to subprocesses.
    1460           1 :         if o.private.disableDeleteOnlyCompactions {
    1461           1 :                 fmt.Fprintln(&buf, "  disable_delete_only_compactions=true")
    1462           1 :         }
    1463           1 :         if o.private.disableElisionOnlyCompactions {
    1464           1 :                 fmt.Fprintln(&buf, "  disable_elision_only_compactions=true")
    1465           1 :         }
    1466           1 :         if o.private.disableLazyCombinedIteration {
    1467           1 :                 fmt.Fprintln(&buf, "  disable_lazy_combined_iteration=true")
    1468           1 :         }
    1469             : 
    1470           1 :         if o.WALFailover != nil {
    1471           1 :                 unhealthyThreshold, _ := o.WALFailover.FailoverOptions.UnhealthyOperationLatencyThreshold()
    1472           1 :                 fmt.Fprintf(&buf, "\n")
    1473           1 :                 fmt.Fprintf(&buf, "[WAL Failover]\n")
    1474           1 :                 fmt.Fprintf(&buf, "  secondary_dir=%s\n", o.WALFailover.Secondary.Dirname)
    1475           1 :                 fmt.Fprintf(&buf, "  primary_dir_probe_interval=%s\n", o.WALFailover.FailoverOptions.PrimaryDirProbeInterval)
    1476           1 :                 fmt.Fprintf(&buf, "  healthy_probe_latency_threshold=%s\n", o.WALFailover.FailoverOptions.HealthyProbeLatencyThreshold)
    1477           1 :                 fmt.Fprintf(&buf, "  healthy_interval=%s\n", o.WALFailover.FailoverOptions.HealthyInterval)
    1478           1 :                 fmt.Fprintf(&buf, "  unhealthy_sampling_interval=%s\n", o.WALFailover.FailoverOptions.UnhealthySamplingInterval)
    1479           1 :                 fmt.Fprintf(&buf, "  unhealthy_operation_latency_threshold=%s\n", unhealthyThreshold)
    1480           1 :                 fmt.Fprintf(&buf, "  elevated_write_stall_threshold_lag=%s\n", o.WALFailover.FailoverOptions.ElevatedWriteStallThresholdLag)
    1481           1 :         }
    1482             : 
    1483           1 :         for i := range o.Levels {
    1484           1 :                 l := &o.Levels[i]
    1485           1 :                 fmt.Fprintf(&buf, "\n")
    1486           1 :                 fmt.Fprintf(&buf, "[Level \"%d\"]\n", i)
    1487           1 :                 fmt.Fprintf(&buf, "  block_restart_interval=%d\n", l.BlockRestartInterval)
    1488           1 :                 fmt.Fprintf(&buf, "  block_size=%d\n", l.BlockSize)
    1489           1 :                 fmt.Fprintf(&buf, "  block_size_threshold=%d\n", l.BlockSizeThreshold)
    1490           1 :                 fmt.Fprintf(&buf, "  compression=%s\n", resolveDefaultCompression(l.Compression()))
    1491           1 :                 fmt.Fprintf(&buf, "  filter_policy=%s\n", filterPolicyName(l.FilterPolicy))
    1492           1 :                 fmt.Fprintf(&buf, "  filter_type=%s\n", l.FilterType)
    1493           1 :                 fmt.Fprintf(&buf, "  index_block_size=%d\n", l.IndexBlockSize)
    1494           1 :                 fmt.Fprintf(&buf, "  target_file_size=%d\n", l.TargetFileSize)
    1495           1 :         }
    1496             : 
    1497           1 :         return buf.String()
    1498             : }
    1499             : 
    1500             : // parseOptions takes options serialized by Options.String() and parses them into
    1501             : // keys and values, calling fn for each one.
    1502           1 : func parseOptions(s string, fn func(section, key, value string) error) error {
    1503           1 :         var section string
    1504           1 :         for _, line := range strings.Split(s, "\n") {
    1505           1 :                 line = strings.TrimSpace(line)
    1506           1 :                 if len(line) == 0 {
    1507           1 :                         // Skip blank lines.
    1508           1 :                         continue
    1509             :                 }
    1510           1 :                 if line[0] == ';' || line[0] == '#' {
    1511           0 :                         // Skip comments.
    1512           0 :                         continue
    1513             :                 }
    1514           1 :                 n := len(line)
    1515           1 :                 if line[0] == '[' && line[n-1] == ']' {
    1516           1 :                         // Parse section.
    1517           1 :                         section = line[1 : n-1]
    1518           1 :                         continue
    1519             :                 }
    1520             : 
    1521           1 :                 pos := strings.Index(line, "=")
    1522           1 :                 if pos < 0 {
    1523           1 :                         const maxLen = 50
    1524           1 :                         if len(line) > maxLen {
    1525           0 :                                 line = line[:maxLen-3] + "..."
    1526           0 :                         }
    1527           1 :                         return base.CorruptionErrorf("invalid key=value syntax: %q", errors.Safe(line))
    1528             :                 }
    1529             : 
    1530           1 :                 key := strings.TrimSpace(line[:pos])
    1531           1 :                 value := strings.TrimSpace(line[pos+1:])
    1532           1 : 
    1533           1 :                 // RocksDB uses a similar (INI-style) syntax for the OPTIONS file, but
    1534           1 :                 // different section names and keys. The "CFOptions ..." paths are the
    1535           1 :                 // RocksDB versions which we map to the Pebble paths.
    1536           1 :                 mappedSection := section
    1537           1 :                 if section == `CFOptions "default"` {
    1538           1 :                         mappedSection = "Options"
    1539           1 :                         switch key {
    1540           1 :                         case "comparator":
    1541           1 :                                 key = "comparer"
    1542           1 :                         case "merge_operator":
    1543           1 :                                 key = "merger"
    1544             :                         }
    1545             :                 }
    1546             : 
    1547           1 :                 if err := fn(mappedSection, key, value); err != nil {
    1548           1 :                         return err
    1549           1 :                 }
    1550             :         }
    1551           1 :         return nil
    1552             : }
    1553             : 
    1554             : // ParseHooks contains callbacks to create options fields which can have
    1555             : // user-defined implementations.
    1556             : type ParseHooks struct {
    1557             :         NewCache        func(size int64) *Cache
    1558             :         NewCleaner      func(name string) (Cleaner, error)
    1559             :         NewComparer     func(name string) (*Comparer, error)
    1560             :         NewFilterPolicy func(name string) (FilterPolicy, error)
    1561             :         NewMerger       func(name string) (*Merger, error)
    1562             :         SkipUnknown     func(name, value string) bool
    1563             : }
    1564             : 
    1565             : // Parse parses the options from the specified string. Note that certain
    1566             : // options cannot be parsed into populated fields. For example, comparer and
    1567             : // merger.
    1568           1 : func (o *Options) Parse(s string, hooks *ParseHooks) error {
    1569           1 :         return parseOptions(s, func(section, key, value string) error {
    1570           1 :                 // WARNING: DO NOT remove entries from the switches below because doing so
    1571           1 :                 // causes a key previously written to the OPTIONS file to be considered unknown,
    1572           1 :                 // a backwards incompatible change. Instead, leave in support for parsing the
    1573           1 :                 // key but simply don't parse the value.
    1574           1 : 
    1575           1 :                 switch {
    1576           1 :                 case section == "Version":
    1577           1 :                         switch key {
    1578           1 :                         case "pebble_version":
    1579           0 :                         default:
    1580           0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    1581           0 :                                         return nil
    1582           0 :                                 }
    1583           0 :                                 return errors.Errorf("pebble: unknown option: %s.%s",
    1584           0 :                                         errors.Safe(section), errors.Safe(key))
    1585             :                         }
    1586           1 :                         return nil
    1587             : 
    1588           1 :                 case section == "Options":
    1589           1 :                         var err error
    1590           1 :                         switch key {
    1591           1 :                         case "bytes_per_sync":
    1592           1 :                                 o.BytesPerSync, err = strconv.Atoi(value)
    1593           1 :                         case "cache_size":
    1594           1 :                                 var n int64
    1595           1 :                                 n, err = strconv.ParseInt(value, 10, 64)
    1596           1 :                                 if err == nil && hooks != nil && hooks.NewCache != nil {
    1597           1 :                                         if o.Cache != nil {
    1598           0 :                                                 o.Cache.Unref()
    1599           0 :                                         }
    1600           1 :                                         o.Cache = hooks.NewCache(n)
    1601             :                                 }
    1602             :                                 // We avoid calling cache.New in parsing because it makes it
    1603             :                                 // too easy to leak a cache.
    1604           1 :                         case "cleaner":
    1605           1 :                                 switch value {
    1606           1 :                                 case "archive":
    1607           1 :                                         o.Cleaner = ArchiveCleaner{}
    1608           1 :                                 case "delete":
    1609           1 :                                         o.Cleaner = DeleteCleaner{}
    1610           0 :                                 default:
    1611           0 :                                         if hooks != nil && hooks.NewCleaner != nil {
    1612           0 :                                                 o.Cleaner, err = hooks.NewCleaner(value)
    1613           0 :                                         }
    1614             :                                 }
    1615           1 :                         case "comparer":
    1616           1 :                                 switch value {
    1617           1 :                                 case "leveldb.BytewiseComparator":
    1618           1 :                                         o.Comparer = DefaultComparer
    1619           1 :                                 default:
    1620           1 :                                         if hooks != nil && hooks.NewComparer != nil {
    1621           1 :                                                 o.Comparer, err = hooks.NewComparer(value)
    1622           1 :                                         }
    1623             :                                 }
    1624           1 :                         case "compaction_debt_concurrency":
    1625           1 :                                 o.Experimental.CompactionDebtConcurrency, err = strconv.ParseUint(value, 10, 64)
    1626           0 :                         case "delete_range_flush_delay":
    1627           0 :                                 // NB: This is a deprecated serialization of the
    1628           0 :                                 // `flush_delay_delete_range`.
    1629           0 :                                 o.FlushDelayDeleteRange, err = time.ParseDuration(value)
    1630           1 :                         case "disable_delete_only_compactions":
    1631           1 :                                 o.private.disableDeleteOnlyCompactions, err = strconv.ParseBool(value)
    1632           1 :                         case "disable_elision_only_compactions":
    1633           1 :                                 o.private.disableElisionOnlyCompactions, err = strconv.ParseBool(value)
    1634           1 :                         case "disable_ingest_as_flushable":
    1635           1 :                                 var v bool
    1636           1 :                                 v, err = strconv.ParseBool(value)
    1637           1 :                                 if err == nil {
    1638           1 :                                         o.Experimental.DisableIngestAsFlushable = func() bool { return v }
    1639             :                                 }
    1640           1 :                         case "disable_lazy_combined_iteration":
    1641           1 :                                 o.private.disableLazyCombinedIteration, err = strconv.ParseBool(value)
    1642           1 :                         case "disable_wal":
    1643           1 :                                 o.DisableWAL, err = strconv.ParseBool(value)
    1644           1 :                         case "flush_delay_delete_range":
    1645           1 :                                 o.FlushDelayDeleteRange, err = time.ParseDuration(value)
    1646           1 :                         case "flush_delay_range_key":
    1647           1 :                                 o.FlushDelayRangeKey, err = time.ParseDuration(value)
    1648           1 :                         case "flush_split_bytes":
    1649           1 :                                 o.FlushSplitBytes, err = strconv.ParseInt(value, 10, 64)
    1650           1 :                         case "format_major_version":
    1651           1 :                                 // NB: The version written here may be stale. Open does
    1652           1 :                                 // not use the format major version encoded in the
    1653           1 :                                 // OPTIONS file other than to validate that the encoded
    1654           1 :                                 // version is valid right here.
    1655           1 :                                 var v uint64
    1656           1 :                                 v, err = strconv.ParseUint(value, 10, 64)
    1657           1 :                                 if vers := FormatMajorVersion(v); vers > internalFormatNewest || vers == FormatDefault {
    1658           0 :                                         err = errors.Newf("unsupported format major version %d", o.FormatMajorVersion)
    1659           0 :                                 }
    1660           1 :                                 if err == nil {
    1661           1 :                                         o.FormatMajorVersion = FormatMajorVersion(v)
    1662           1 :                                 }
    1663           1 :                         case "l0_compaction_concurrency":
    1664           1 :                                 o.Experimental.L0CompactionConcurrency, err = strconv.Atoi(value)
    1665           1 :                         case "l0_compaction_file_threshold":
    1666           1 :                                 o.L0CompactionFileThreshold, err = strconv.Atoi(value)
    1667           1 :                         case "l0_compaction_threshold":
    1668           1 :                                 o.L0CompactionThreshold, err = strconv.Atoi(value)
    1669           1 :                         case "l0_stop_writes_threshold":
    1670           1 :                                 o.L0StopWritesThreshold, err = strconv.Atoi(value)
    1671           0 :                         case "l0_sublevel_compactions":
    1672             :                                 // Do nothing; option existed in older versions of pebble.
    1673           1 :                         case "lbase_max_bytes":
    1674           1 :                                 o.LBaseMaxBytes, err = strconv.ParseInt(value, 10, 64)
    1675           1 :                         case "level_multiplier":
    1676           1 :                                 o.Experimental.LevelMultiplier, err = strconv.Atoi(value)
    1677           1 :                         case "max_concurrent_compactions":
    1678           1 :                                 var concurrentCompactions int
    1679           1 :                                 concurrentCompactions, err = strconv.Atoi(value)
    1680           1 :                                 if concurrentCompactions <= 0 {
    1681           0 :                                         err = errors.New("max_concurrent_compactions cannot be <= 0")
    1682           1 :                                 } else {
    1683           1 :                                         o.MaxConcurrentCompactions = func() int { return concurrentCompactions }
    1684             :                                 }
    1685           1 :                         case "max_concurrent_downloads":
    1686           1 :                                 var concurrentDownloads int
    1687           1 :                                 concurrentDownloads, err = strconv.Atoi(value)
    1688           1 :                                 if concurrentDownloads <= 0 {
    1689           0 :                                         err = errors.New("max_concurrent_compactions cannot be <= 0")
    1690           1 :                                 } else {
    1691           1 :                                         o.MaxConcurrentDownloads = func() int { return concurrentDownloads }
    1692             :                                 }
    1693           1 :                         case "max_manifest_file_size":
    1694           1 :                                 o.MaxManifestFileSize, err = strconv.ParseInt(value, 10, 64)
    1695           1 :                         case "max_open_files":
    1696           1 :                                 o.MaxOpenFiles, err = strconv.Atoi(value)
    1697           1 :                         case "mem_table_size":
    1698           1 :                                 o.MemTableSize, err = strconv.ParseUint(value, 10, 64)
    1699           1 :                         case "mem_table_stop_writes_threshold":
    1700           1 :                                 o.MemTableStopWritesThreshold, err = strconv.Atoi(value)
    1701           0 :                         case "min_compaction_rate":
    1702             :                                 // Do nothing; option existed in older versions of pebble, and
    1703             :                                 // may be meaningful again eventually.
    1704           1 :                         case "min_deletion_rate":
    1705           1 :                                 o.TargetByteDeletionRate, err = strconv.Atoi(value)
    1706           0 :                         case "min_flush_rate":
    1707             :                                 // Do nothing; option existed in older versions of pebble, and
    1708             :                                 // may be meaningful again eventually.
    1709           1 :                         case "multilevel_compaction_heuristic":
    1710           1 :                                 switch {
    1711           1 :                                 case value == "none":
    1712           1 :                                         o.Experimental.MultiLevelCompactionHeuristic = NoMultiLevel{}
    1713           1 :                                 case strings.HasPrefix(value, "wamp"):
    1714           1 :                                         fields := strings.FieldsFunc(strings.TrimPrefix(value, "wamp"), func(r rune) bool {
    1715           1 :                                                 return unicode.IsSpace(r) || r == ',' || r == '(' || r == ')'
    1716           1 :                                         })
    1717           1 :                                         if len(fields) != 2 {
    1718           0 :                                                 err = errors.Newf("require 2 arguments")
    1719           0 :                                         }
    1720           1 :                                         var h WriteAmpHeuristic
    1721           1 :                                         if err == nil {
    1722           1 :                                                 h.AddPropensity, err = strconv.ParseFloat(fields[0], 64)
    1723           1 :                                         }
    1724           1 :                                         if err == nil {
    1725           1 :                                                 h.AllowL0, err = strconv.ParseBool(fields[1])
    1726           1 :                                         }
    1727           1 :                                         if err == nil {
    1728           1 :                                                 o.Experimental.MultiLevelCompactionHeuristic = h
    1729           1 :                                         } else {
    1730           0 :                                                 err = errors.Wrapf(err, "unexpected wamp heuristic arguments: %s", value)
    1731           0 :                                         }
    1732           0 :                                 default:
    1733           0 :                                         err = errors.Newf("unrecognized multilevel compaction heuristic: %s", value)
    1734             :                                 }
    1735           0 :                         case "point_tombstone_weight":
    1736             :                                 // Do nothing; deprecated.
    1737           1 :                         case "strict_wal_tail":
    1738           1 :                                 var strictWALTail bool
    1739           1 :                                 strictWALTail, err = strconv.ParseBool(value)
    1740           1 :                                 if err == nil && !strictWALTail {
    1741           0 :                                         err = errors.Newf("reading from versions with strict_wal_tail=false no longer supported")
    1742           0 :                                 }
    1743           1 :                         case "merger":
    1744           1 :                                 switch value {
    1745           0 :                                 case "nullptr":
    1746           0 :                                         o.Merger = nil
    1747           1 :                                 case "pebble.concatenate":
    1748           1 :                                         o.Merger = DefaultMerger
    1749           1 :                                 default:
    1750           1 :                                         if hooks != nil && hooks.NewMerger != nil {
    1751           1 :                                                 o.Merger, err = hooks.NewMerger(value)
    1752           1 :                                         }
    1753             :                                 }
    1754           1 :                         case "read_compaction_rate":
    1755           1 :                                 o.Experimental.ReadCompactionRate, err = strconv.ParseInt(value, 10, 64)
    1756           1 :                         case "read_sampling_multiplier":
    1757           1 :                                 o.Experimental.ReadSamplingMultiplier, err = strconv.ParseInt(value, 10, 64)
    1758           1 :                         case "num_deletions_threshold":
    1759           1 :                                 o.Experimental.NumDeletionsThreshold, err = strconv.Atoi(value)
    1760           1 :                         case "deletion_size_ratio_threshold":
    1761           1 :                                 val, parseErr := strconv.ParseFloat(value, 32)
    1762           1 :                                 o.Experimental.DeletionSizeRatioThreshold = float32(val)
    1763           1 :                                 err = parseErr
    1764           1 :                         case "tombstone_dense_compaction_threshold":
    1765           1 :                                 o.Experimental.TombstoneDenseCompactionThreshold, err = strconv.ParseFloat(value, 64)
    1766           1 :                         case "table_cache_shards":
    1767           1 :                                 o.Experimental.TableCacheShards, err = strconv.Atoi(value)
    1768           0 :                         case "table_format":
    1769           0 :                                 switch value {
    1770           0 :                                 case "leveldb":
    1771           0 :                                 case "rocksdbv2":
    1772           0 :                                 default:
    1773           0 :                                         return errors.Errorf("pebble: unknown table format: %q", errors.Safe(value))
    1774             :                                 }
    1775           1 :                         case "table_property_collectors":
    1776             :                                 // No longer implemented; ignore.
    1777           1 :                         case "validate_on_ingest":
    1778           1 :                                 o.Experimental.ValidateOnIngest, err = strconv.ParseBool(value)
    1779           1 :                         case "wal_dir":
    1780           1 :                                 o.WALDir = value
    1781           1 :                         case "wal_bytes_per_sync":
    1782           1 :                                 o.WALBytesPerSync, err = strconv.Atoi(value)
    1783           1 :                         case "max_writer_concurrency":
    1784           1 :                                 o.Experimental.MaxWriterConcurrency, err = strconv.Atoi(value)
    1785           1 :                         case "force_writer_parallelism":
    1786           1 :                                 o.Experimental.ForceWriterParallelism, err = strconv.ParseBool(value)
    1787           1 :                         case "secondary_cache_size_bytes":
    1788           1 :                                 o.Experimental.SecondaryCacheSizeBytes, err = strconv.ParseInt(value, 10, 64)
    1789           1 :                         case "create_on_shared":
    1790           1 :                                 var createOnSharedInt int64
    1791           1 :                                 createOnSharedInt, err = strconv.ParseInt(value, 10, 64)
    1792           1 :                                 o.Experimental.CreateOnShared = remote.CreateOnSharedStrategy(createOnSharedInt)
    1793           0 :                         default:
    1794           0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    1795           0 :                                         return nil
    1796           0 :                                 }
    1797           0 :                                 return errors.Errorf("pebble: unknown option: %s.%s",
    1798           0 :                                         errors.Safe(section), errors.Safe(key))
    1799             :                         }
    1800           1 :                         return err
    1801             : 
    1802           1 :                 case section == "WAL Failover":
    1803           1 :                         if o.WALFailover == nil {
    1804           1 :                                 o.WALFailover = new(WALFailoverOptions)
    1805           1 :                         }
    1806           1 :                         var err error
    1807           1 :                         switch key {
    1808           1 :                         case "secondary_dir":
    1809           1 :                                 o.WALFailover.Secondary = wal.Dir{Dirname: value, FS: vfs.Default}
    1810           1 :                         case "primary_dir_probe_interval":
    1811           1 :                                 o.WALFailover.PrimaryDirProbeInterval, err = time.ParseDuration(value)
    1812           1 :                         case "healthy_probe_latency_threshold":
    1813           1 :                                 o.WALFailover.HealthyProbeLatencyThreshold, err = time.ParseDuration(value)
    1814           1 :                         case "healthy_interval":
    1815           1 :                                 o.WALFailover.HealthyInterval, err = time.ParseDuration(value)
    1816           1 :                         case "unhealthy_sampling_interval":
    1817           1 :                                 o.WALFailover.UnhealthySamplingInterval, err = time.ParseDuration(value)
    1818           1 :                         case "unhealthy_operation_latency_threshold":
    1819           1 :                                 var threshold time.Duration
    1820           1 :                                 threshold, err = time.ParseDuration(value)
    1821           1 :                                 o.WALFailover.UnhealthyOperationLatencyThreshold = func() (time.Duration, bool) {
    1822           1 :                                         return threshold, true
    1823           1 :                                 }
    1824           1 :                         case "elevated_write_stall_threshold_lag":
    1825           1 :                                 o.WALFailover.ElevatedWriteStallThresholdLag, err = time.ParseDuration(value)
    1826           0 :                         default:
    1827           0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    1828           0 :                                         return nil
    1829           0 :                                 }
    1830           0 :                                 return errors.Errorf("pebble: unknown option: %s.%s",
    1831           0 :                                         errors.Safe(section), errors.Safe(key))
    1832             :                         }
    1833           1 :                         return err
    1834             : 
    1835           1 :                 case strings.HasPrefix(section, "Level "):
    1836           1 :                         var index int
    1837           1 :                         if n, err := fmt.Sscanf(section, `Level "%d"`, &index); err != nil {
    1838           0 :                                 return err
    1839           1 :                         } else if n != 1 {
    1840           0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section, value) {
    1841           0 :                                         return nil
    1842           0 :                                 }
    1843           0 :                                 return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
    1844             :                         }
    1845             : 
    1846           1 :                         if len(o.Levels) <= index {
    1847           1 :                                 newLevels := make([]LevelOptions, index+1)
    1848           1 :                                 copy(newLevels, o.Levels)
    1849           1 :                                 o.Levels = newLevels
    1850           1 :                         }
    1851           1 :                         l := &o.Levels[index]
    1852           1 : 
    1853           1 :                         var err error
    1854           1 :                         switch key {
    1855           1 :                         case "block_restart_interval":
    1856           1 :                                 l.BlockRestartInterval, err = strconv.Atoi(value)
    1857           1 :                         case "block_size":
    1858           1 :                                 l.BlockSize, err = strconv.Atoi(value)
    1859           1 :                         case "block_size_threshold":
    1860           1 :                                 l.BlockSizeThreshold, err = strconv.Atoi(value)
    1861           1 :                         case "compression":
    1862           1 :                                 switch value {
    1863           0 :                                 case "Default":
    1864           0 :                                         l.Compression = func() Compression { return DefaultCompression }
    1865           1 :                                 case "NoCompression":
    1866           1 :                                         l.Compression = func() Compression { return NoCompression }
    1867           1 :                                 case "Snappy":
    1868           1 :                                         l.Compression = func() Compression { return SnappyCompression }
    1869           1 :                                 case "ZSTD":
    1870           1 :                                         l.Compression = func() Compression { return ZstdCompression }
    1871           0 :                                 default:
    1872           0 :                                         return errors.Errorf("pebble: unknown compression: %q", errors.Safe(value))
    1873             :                                 }
    1874           1 :                         case "filter_policy":
    1875           1 :                                 if hooks != nil && hooks.NewFilterPolicy != nil {
    1876           1 :                                         l.FilterPolicy, err = hooks.NewFilterPolicy(value)
    1877           1 :                                 }
    1878           1 :                         case "filter_type":
    1879           1 :                                 switch value {
    1880           1 :                                 case "table":
    1881           1 :                                         l.FilterType = TableFilter
    1882           0 :                                 default:
    1883           0 :                                         return errors.Errorf("pebble: unknown filter type: %q", errors.Safe(value))
    1884             :                                 }
    1885           1 :                         case "index_block_size":
    1886           1 :                                 l.IndexBlockSize, err = strconv.Atoi(value)
    1887           1 :                         case "target_file_size":
    1888           1 :                                 l.TargetFileSize, err = strconv.ParseInt(value, 10, 64)
    1889           0 :                         default:
    1890           0 :                                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    1891           0 :                                         return nil
    1892           0 :                                 }
    1893           0 :                                 return errors.Errorf("pebble: unknown option: %s.%s", errors.Safe(section), errors.Safe(key))
    1894             :                         }
    1895           1 :                         return err
    1896             :                 }
    1897           1 :                 if hooks != nil && hooks.SkipUnknown != nil && hooks.SkipUnknown(section+"."+key, value) {
    1898           1 :                         return nil
    1899           1 :                 }
    1900           0 :                 return errors.Errorf("pebble: unknown section: %q", errors.Safe(section))
    1901             :         })
    1902             : }
    1903             : 
    1904             : // ErrMissingWALRecoveryDir is an error returned when a database is attempted to be
    1905             : // opened without supplying a Options.WALRecoveryDir entry for a directory that
    1906             : // may contain WALs required to recover a consistent database state.
    1907             : type ErrMissingWALRecoveryDir struct {
    1908             :         Dir string
    1909             : }
    1910             : 
    1911             : // Error implements error.
    1912           1 : func (e ErrMissingWALRecoveryDir) Error() string {
    1913           1 :         return fmt.Sprintf("directory %q may contain relevant WALs", e.Dir)
    1914           1 : }
    1915             : 
    1916             : // CheckCompatibility verifies the options are compatible with the previous options
    1917             : // serialized by Options.String(). For example, the Comparer and Merger must be
    1918             : // the same, or data will not be able to be properly read from the DB.
    1919             : //
    1920             : // This function only looks at specific keys and does not error out if the
    1921             : // options are newer and contain unknown keys.
    1922           1 : func (o *Options) CheckCompatibility(previousOptions string) error {
    1923           1 :         return parseOptions(previousOptions, func(section, key, value string) error {
    1924           1 :                 switch section + "." + key {
    1925           1 :                 case "Options.comparer":
    1926           1 :                         if value != o.Comparer.Name {
    1927           1 :                                 return errors.Errorf("pebble: comparer name from file %q != comparer name from options %q",
    1928           1 :                                         errors.Safe(value), errors.Safe(o.Comparer.Name))
    1929           1 :                         }
    1930           1 :                 case "Options.merger":
    1931           1 :                         // RocksDB allows the merge operator to be unspecified, in which case it
    1932           1 :                         // shows up as "nullptr".
    1933           1 :                         if value != "nullptr" && value != o.Merger.Name {
    1934           1 :                                 return errors.Errorf("pebble: merger name from file %q != merger name from options %q",
    1935           1 :                                         errors.Safe(value), errors.Safe(o.Merger.Name))
    1936           1 :                         }
    1937           1 :                 case "Options.wal_dir", "WAL Failover.secondary_dir":
    1938           1 :                         switch {
    1939           1 :                         case o.WALDir == value:
    1940           1 :                                 return nil
    1941           1 :                         case o.WALFailover != nil && o.WALFailover.Secondary.Dirname == value:
    1942           1 :                                 return nil
    1943           1 :                         default:
    1944           1 :                                 for _, d := range o.WALRecoveryDirs {
    1945           1 :                                         if d.Dirname == value {
    1946           1 :                                                 return nil
    1947           1 :                                         }
    1948             :                                 }
    1949           1 :                                 return ErrMissingWALRecoveryDir{Dir: value}
    1950             :                         }
    1951             :                 }
    1952           1 :                 return nil
    1953             :         })
    1954             : }
    1955             : 
    1956             : // Validate verifies that the options are mutually consistent. For example,
    1957             : // L0StopWritesThreshold must be >= L0CompactionThreshold, otherwise a write
    1958             : // stall would persist indefinitely.
    1959           1 : func (o *Options) Validate() error {
    1960           1 :         // Note that we can presume Options.EnsureDefaults has been called, so there
    1961           1 :         // is no need to check for zero values.
    1962           1 : 
    1963           1 :         var buf strings.Builder
    1964           1 :         if o.Experimental.L0CompactionConcurrency < 1 {
    1965           1 :                 fmt.Fprintf(&buf, "L0CompactionConcurrency (%d) must be >= 1\n",
    1966           1 :                         o.Experimental.L0CompactionConcurrency)
    1967           1 :         }
    1968           1 :         if o.L0StopWritesThreshold < o.L0CompactionThreshold {
    1969           1 :                 fmt.Fprintf(&buf, "L0StopWritesThreshold (%d) must be >= L0CompactionThreshold (%d)\n",
    1970           1 :                         o.L0StopWritesThreshold, o.L0CompactionThreshold)
    1971           1 :         }
    1972           1 :         if uint64(o.MemTableSize) >= maxMemTableSize {
    1973           1 :                 fmt.Fprintf(&buf, "MemTableSize (%s) must be < %s\n",
    1974           1 :                         humanize.Bytes.Uint64(uint64(o.MemTableSize)), humanize.Bytes.Uint64(maxMemTableSize))
    1975           1 :         }
    1976           1 :         if o.MemTableStopWritesThreshold < 2 {
    1977           1 :                 fmt.Fprintf(&buf, "MemTableStopWritesThreshold (%d) must be >= 2\n",
    1978           1 :                         o.MemTableStopWritesThreshold)
    1979           1 :         }
    1980           1 :         if o.FormatMajorVersion < FormatMinSupported || o.FormatMajorVersion > internalFormatNewest {
    1981           0 :                 fmt.Fprintf(&buf, "FormatMajorVersion (%d) must be between %d and %d\n",
    1982           0 :                         o.FormatMajorVersion, FormatMinSupported, internalFormatNewest)
    1983           0 :         }
    1984           1 :         if o.Experimental.CreateOnShared != remote.CreateOnSharedNone && o.FormatMajorVersion < FormatMinForSharedObjects {
    1985           0 :                 fmt.Fprintf(&buf, "FormatMajorVersion (%d) when CreateOnShared is set must be at least %d\n",
    1986           0 :                         o.FormatMajorVersion, FormatMinForSharedObjects)
    1987           0 : 
    1988           0 :         }
    1989           1 :         if o.TableCache != nil && o.Cache != o.TableCache.cache {
    1990           1 :                 fmt.Fprintf(&buf, "underlying cache in the TableCache and the Cache dont match\n")
    1991           1 :         }
    1992           1 :         if buf.Len() == 0 {
    1993           1 :                 return nil
    1994           1 :         }
    1995           1 :         return errors.New(buf.String())
    1996             : }
    1997             : 
    1998             : // MakeReaderOptions constructs sstable.ReaderOptions from the corresponding
    1999             : // options in the receiver.
    2000           1 : func (o *Options) MakeReaderOptions() sstable.ReaderOptions {
    2001           1 :         var readerOpts sstable.ReaderOptions
    2002           1 :         if o != nil {
    2003           1 :                 readerOpts.LoadBlockSema = o.LoadBlockSema
    2004           1 :                 readerOpts.Comparer = o.Comparer
    2005           1 :                 readerOpts.Merger = o.Merger
    2006           1 :                 readerOpts.Filters = o.Filters
    2007           1 :                 readerOpts.LoggerAndTracer = o.LoggerAndTracer
    2008           1 :         }
    2009           1 :         return readerOpts
    2010             : }
    2011             : 
    2012             : // MakeWriterOptions constructs sstable.WriterOptions for the specified level
    2013             : // from the corresponding options in the receiver.
    2014           1 : func (o *Options) MakeWriterOptions(level int, format sstable.TableFormat) sstable.WriterOptions {
    2015           1 :         var writerOpts sstable.WriterOptions
    2016           1 :         writerOpts.TableFormat = format
    2017           1 :         if o != nil {
    2018           1 :                 writerOpts.Comparer = o.Comparer
    2019           1 :                 if o.Merger != nil {
    2020           1 :                         writerOpts.MergerName = o.Merger.Name
    2021           1 :                 }
    2022           1 :                 writerOpts.BlockPropertyCollectors = o.BlockPropertyCollectors
    2023             :         }
    2024           1 :         if format >= sstable.TableFormatPebblev3 {
    2025           1 :                 writerOpts.ShortAttributeExtractor = o.Experimental.ShortAttributeExtractor
    2026           1 :                 writerOpts.RequiredInPlaceValueBound = o.Experimental.RequiredInPlaceValueBound
    2027           1 :                 if format >= sstable.TableFormatPebblev4 && level == numLevels-1 {
    2028           1 :                         writerOpts.WritingToLowestLevel = true
    2029           1 :                 }
    2030             :         }
    2031           1 :         levelOpts := o.Level(level)
    2032           1 :         writerOpts.BlockRestartInterval = levelOpts.BlockRestartInterval
    2033           1 :         writerOpts.BlockSize = levelOpts.BlockSize
    2034           1 :         writerOpts.BlockSizeThreshold = levelOpts.BlockSizeThreshold
    2035           1 :         writerOpts.Compression = resolveDefaultCompression(levelOpts.Compression())
    2036           1 :         writerOpts.FilterPolicy = levelOpts.FilterPolicy
    2037           1 :         writerOpts.FilterType = levelOpts.FilterType
    2038           1 :         writerOpts.IndexBlockSize = levelOpts.IndexBlockSize
    2039           1 :         writerOpts.AllocatorSizeClasses = o.AllocatorSizeClasses
    2040           1 :         writerOpts.NumDeletionsThreshold = o.Experimental.NumDeletionsThreshold
    2041           1 :         writerOpts.DeletionSizeRatioThreshold = o.Experimental.DeletionSizeRatioThreshold
    2042           1 :         return writerOpts
    2043             : }
    2044             : 
    2045           1 : func resolveDefaultCompression(c Compression) Compression {
    2046           1 :         if c <= DefaultCompression || c >= block.NCompression {
    2047           1 :                 c = SnappyCompression
    2048           1 :         }
    2049           1 :         return c
    2050             : }

Generated by: LCOV version 1.14