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

Generated by: LCOV version 1.14