Documentation
¶
Index ¶
- Constants
- Variables
- func AppendEncodedValue(dst []byte, v Value) []byte
- func CompareKeys(a, b []byte) int
- func EncodeEntry(e Entry) []byte
- func EncodeValue(v Value) []byte
- func SearchBlock(block *Block, key []byte) int
- type Block
- type BlockBuilder
- func (b *BlockBuilder) Add(key, value []byte) bool
- func (b *BlockBuilder) Build(blockType uint8, compressionLevel int) ([]byte, error)
- func (b *BlockBuilder) Count() int
- func (b *BlockBuilder) Entries() []BlockEntry
- func (b *BlockBuilder) FirstKey() []byte
- func (b *BlockBuilder) Reset()
- func (b *BlockBuilder) Size() int
- type BlockEntry
- type BloomFilter
- type CacheKey
- type CacheStats
- type CompactionStyle
- type DataPointer
- type Entry
- type Index
- type IndexBuilder
- type IndexEntry
- type LRUCache
- type LevelStats
- type Memtable
- type MemtableIterator
- type Options
- type Reader
- func (r *Reader) AddImmutable(mt *Memtable)
- func (r *Reader) AddSSTable(level int, sst *SSTable)
- func (r *Reader) Get(key []byte) (Value, error)
- func (r *Reader) GetLevels() [][]*SSTable
- func (r *Reader) RemoveImmutable(mt *Memtable)
- func (r *Reader) ScanPrefix(prefix []byte, fn func(key []byte, value Value) bool) error
- func (r *Reader) SetLevels(levels [][]*SSTable)
- func (r *Reader) SetMemtable(mt *Memtable)
- type SSTable
- type SSTableFooter
- type SSTableMeta
- type SSTableWriter
- type Store
- func (s *Store) Close() error
- func (s *Store) Compact() error
- func (s *Store) Delete(key []byte) error
- func (s *Store) Flush() error
- func (s *Store) Get(key []byte) (Value, error)
- func (s *Store) GetBool(key []byte) (bool, error)
- func (s *Store) GetBytes(key []byte) ([]byte, error)
- func (s *Store) GetFloat64(key []byte) (float64, error)
- func (s *Store) GetInt64(key []byte) (int64, error)
- func (s *Store) GetString(key []byte) (string, error)
- func (s *Store) Put(key []byte, value Value) error
- func (s *Store) PutBool(key []byte, value bool) error
- func (s *Store) PutBytes(key []byte, value []byte) error
- func (s *Store) PutFloat64(key []byte, value float64) error
- func (s *Store) PutInt64(key []byte, value int64) error
- func (s *Store) PutString(key []byte, value string) error
- func (s *Store) ScanPrefix(prefix []byte, fn func(key []byte, value Value) bool) error
- func (s *Store) Stats() StoreStats
- type StoreStats
- type Value
- type ValueType
- type WAL
- type WALEntry
- type WALSyncMode
- type Writer
Constants ¶
const ( BlockTypeData uint8 = 1 BlockTypeIndex uint8 = 2 BlockTypeBloom uint8 = 3 BlockTypeMeta uint8 = 4 )
Block types
const ( SSTableMagic uint64 = 0x544B5653_00000001 // "TKVS" + version 1 SSTableVersion uint32 = 1 )
SSTable magic number and version
const ( OpPut uint8 = 1 OpDelete uint8 = 2 )
WAL operation types
BlockFooterSize is the size of the block footer in bytes.
const DataPointerSize = 14 // 4 + 4 + 2 + 4
DataPointerSize is the serialized size of a DataPointer.
const InlineThreshold = 64
InlineThreshold determines when to store data inline vs pointer. Values smaller than this are stored directly in the record.
const MaxImmutableMemtables = 2
MaxImmutableMemtables is the max number of memtables waiting to be flushed. When this limit is reached, writes will block until a flush completes.
SSTableFooterSize is the fixed size of the footer in bytes.
Variables ¶
var ( ErrKeyNotFound = errors.New("key not found") ErrInvalidValue = errors.New("invalid value encoding") ErrCorruptedData = errors.New("corrupted data") ErrChecksumMismatch = errors.New("checksum mismatch") )
Common errors
var (
ErrInvalidSSTable = errors.New("invalid sstable format")
)
Errors
var (
ErrStoreClosed = errors.New("store is closed")
)
Errors
Functions ¶
func AppendEncodedValue ¶
AppendEncodedValue appends the encoded value to dst and returns the result. This avoids allocation when dst has sufficient capacity.
func CompareKeys ¶
CompareKeys performs lexicographic comparison of two keys. Returns -1 if a < b, 0 if a == b, 1 if a > b. Uses bytes.Compare which is assembly-optimized on most platforms.
func EncodeEntry ¶
EncodeEntry serializes an entry (key + value + sequence) to bytes.
func SearchBlock ¶
SearchBlock performs binary search within a block for a key. Returns the index of the matching entry, or -1 if not found.
Types ¶
type Block ¶
type Block struct {
Type uint8
Entries []BlockEntry
}
Block represents a decompressed data block.
type BlockBuilder ¶
type BlockBuilder struct {
// contains filtered or unexported fields
}
BlockBuilder builds blocks from entries.
func NewBlockBuilder ¶
func NewBlockBuilder(blockSize int) *BlockBuilder
NewBlockBuilder creates a new block builder.
func (*BlockBuilder) Add ¶
func (b *BlockBuilder) Add(key, value []byte) bool
Add adds an entry to the block. Returns true if the entry was added, false if the block is full.
func (*BlockBuilder) Build ¶
func (b *BlockBuilder) Build(blockType uint8, compressionLevel int) ([]byte, error)
Build serializes and compresses the block.
func (*BlockBuilder) Count ¶
func (b *BlockBuilder) Count() int
Count returns the number of entries in the block.
func (*BlockBuilder) Entries ¶
func (b *BlockBuilder) Entries() []BlockEntry
Entries returns the entries in the block.
func (*BlockBuilder) FirstKey ¶
func (b *BlockBuilder) FirstKey() []byte
FirstKey returns the first key in the block, or nil if empty.
func (*BlockBuilder) Size ¶
func (b *BlockBuilder) Size() int
Size returns the current uncompressed block size.
type BlockEntry ¶
BlockEntry represents a key-value pair within a block.
type BloomFilter ¶
type BloomFilter struct {
// contains filtered or unexported fields
}
BloomFilter wraps a bloom filter with serialization.
func DeserializeBloomFilter ¶
func DeserializeBloomFilter(data []byte) (*BloomFilter, error)
DeserializeBloomFilter recreates a bloom filter from bytes.
func NewBloomFilter ¶
func NewBloomFilter(numKeys uint, fpRate float64) *BloomFilter
NewBloomFilter creates a bloom filter for the expected number of keys.
func (*BloomFilter) Add ¶
func (bf *BloomFilter) Add(key []byte)
Add adds a key to the bloom filter.
func (*BloomFilter) MayContain ¶
func (bf *BloomFilter) MayContain(key []byte) bool
MayContain returns true if the key might be in the set. False positives are possible, but false negatives are not.
func (*BloomFilter) Serialize ¶
func (bf *BloomFilter) Serialize() ([]byte, error)
Serialize encodes the bloom filter for storage.
type CacheStats ¶
CacheStats contains cache statistics.
func (CacheStats) HitRate ¶
func (s CacheStats) HitRate() float64
HitRate returns the cache hit rate as a percentage.
type CompactionStyle ¶
type CompactionStyle int
CompactionStyle determines the compaction strategy.
const ( // CompactionStyleLeveled uses leveled compaction (read-optimized). CompactionStyleLeveled CompactionStyle = iota // CompactionStyleSizeTiered uses size-tiered compaction (write-optimized). CompactionStyleSizeTiered )
type DataPointer ¶
type DataPointer struct {
FileID uint32 // SSTable file identifier
BlockOffset uint32 // Offset to the data block within file
DataOffset uint16 // Offset within the decompressed block
Length uint32 // Total length of the data
}
DataPointer references variable-length data stored in data blocks. Used for strings/bytes larger than InlineThreshold.
type Entry ¶
type Entry struct {
Key []byte
Value Value
Sequence uint64 // Monotonic sequence number for ordering
}
Entry represents a key-value pair with metadata.
type Index ¶
type Index struct {
Entries []IndexEntry
MinKey []byte
MaxKey []byte
NumKeys uint64
}
Index provides efficient key lookup within an SSTable.
func DeserializeIndex ¶
DeserializeIndex recreates an index from bytes.
type IndexBuilder ¶
type IndexBuilder struct {
// contains filtered or unexported fields
}
IndexBuilder builds the sparse index during SSTable creation.
func NewIndexBuilder ¶
func NewIndexBuilder() *IndexBuilder
NewIndexBuilder creates an index builder.
type IndexEntry ¶
type IndexEntry struct {
Key []byte // First key in the block (separator key)
BlockOffset uint64 // File offset to the block
BlockSize uint32 // Size of the compressed block
}
IndexEntry represents a sparse index entry pointing to a data block.
type LRUCache ¶
type LRUCache struct {
// contains filtered or unexported fields
}
LRUCache is a thread-safe LRU block cache.
func NewLRUCache ¶
NewLRUCache creates a new LRU cache with the given capacity in bytes. If capacity is 0, the cache is disabled.
func (*LRUCache) Get ¶
Get retrieves a block from the cache. Returns the block and true if found, nil and false otherwise.
func (*LRUCache) RemoveByFileID ¶
RemoveByFileID removes all entries for a given file ID. Useful when an SSTable is deleted during compaction.
type LevelStats ¶
LevelStats contains statistics for a single level.
type Memtable ¶
type Memtable struct {
// contains filtered or unexported fields
}
Memtable is an in-memory sorted buffer using a skiplist. It is safe for concurrent reads but requires external synchronization for writes.
func (*Memtable) Get ¶
Get retrieves an entry by key. Returns the entry and true if found, or an empty entry and false if not found.
func (*Memtable) Iterator ¶
func (m *Memtable) Iterator() *MemtableIterator
Iterator returns an iterator over all entries in sorted order. The caller must call Close() when done.
func (*Memtable) MinSequence ¶
MinSequence returns the minimum sequence number in this memtable.
type MemtableIterator ¶
type MemtableIterator struct {
// contains filtered or unexported fields
}
MemtableIterator iterates over memtable entries in sorted order.
func (*MemtableIterator) Close ¶
func (it *MemtableIterator) Close()
Close releases resources held by the iterator.
func (*MemtableIterator) Entry ¶
func (it *MemtableIterator) Entry() Entry
Entry returns the current entry. Only valid after a successful call to Next().
func (*MemtableIterator) Key ¶
func (it *MemtableIterator) Key() []byte
Key returns the current key.
func (*MemtableIterator) Next ¶
func (it *MemtableIterator) Next() bool
Next advances to the next entry. Returns true if there is a next entry, false if iteration is complete.
func (*MemtableIterator) Seek ¶
func (it *MemtableIterator) Seek(target []byte) bool
Seek positions the iterator at the first entry with key >= target.
func (*MemtableIterator) Valid ¶
func (it *MemtableIterator) Valid() bool
Valid returns true if the iterator is positioned at a valid entry.
func (*MemtableIterator) Value ¶
func (it *MemtableIterator) Value() Value
Value returns the current value.
type Options ¶
type Options struct {
// Dir is the base directory for all data files.
Dir string
// MemtableSize is the max memtable size in bytes before flush.
// Default: 4MB
MemtableSize int64
// BlockCacheSize is the LRU cache size in bytes.
// Set to 0 for minimal memory usage (no caching).
// Default: 64MB
BlockCacheSize int64
// BlockSize is the target block size before compression.
// Default: 4KB
BlockSize int
// CompressionLevel is the zstd compression level.
// 1 = fastest, 3 = default, higher = better compression.
// Default: 1 (fastest)
CompressionLevel int
// BloomFPRate is the target false positive rate for bloom filters.
// Default: 0.01 (1%)
BloomFPRate float64
// CompactionStyle determines the compaction strategy.
// Default: CompactionStyleLeveled
CompactionStyle CompactionStyle
// L0CompactionTrigger is the number of L0 files that triggers compaction.
// Default: 4
L0CompactionTrigger int
// MaxLevels is the maximum number of LSM levels.
// Default: 7
MaxLevels int
// LevelSizeMultiplier is the size ratio between adjacent levels.
// Default: 10
LevelSizeMultiplier int
// WALSyncMode determines when WAL is synced to disk.
// Default: WALSyncPerBatch
WALSyncMode WALSyncMode
// FlushInterval is the automatic flush interval.
// Default: 30s
FlushInterval time.Duration
// CompactionInterval is how often to check for compaction.
// Default: 1s
CompactionInterval time.Duration
// VerifyChecksums enables checksum verification on reads.
// Default: true
VerifyChecksums bool
// DisableBloomFilter disables bloom filters for minimal memory.
// Default: false
DisableBloomFilter bool
}
Options configures the Store behavior.
func DefaultOptions ¶
DefaultOptions returns production-ready defaults for the given directory.
func HighPerformanceOptions ¶
HighPerformanceOptions returns options optimized for performance.
func LowMemoryOptions ¶
LowMemoryOptions returns options for memory-constrained environments. Suitable for running billions of records on systems with <1GB RAM.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader coordinates lookups across memtable and SSTables.
func (*Reader) AddImmutable ¶
AddImmutable adds an immutable memtable.
func (*Reader) AddSSTable ¶
AddSSTable adds an SSTable to a level.
func (*Reader) RemoveImmutable ¶
RemoveImmutable removes an immutable memtable after it's been flushed.
func (*Reader) ScanPrefix ¶
ScanPrefix iterates over all keys with the given prefix in sorted order. Keys are deduplicated (newest version wins) and tombstones are skipped. Return false from the callback to stop iteration early.
func (*Reader) SetMemtable ¶
SetMemtable updates the active memtable.
type SSTable ¶
type SSTable struct {
ID uint32
Path string
Level int
Meta SSTableMeta
Index *Index
BloomFilter *BloomFilter
// contains filtered or unexported fields
}
SSTable represents an on-disk sorted string table.
func OpenSSTable ¶
OpenSSTable opens an existing SSTable file.
func (*SSTable) Get ¶
Get retrieves a value from the SSTable. Returns the entry, whether it was found, and any error.
type SSTableFooter ¶
type SSTableFooter struct {
}
SSTableFooter is the fixed-size footer at the end of each SSTable.
type SSTableMeta ¶
type SSTableMeta struct {
Level int
MinSequence uint64
MaxSequence uint64
NumTombstones uint64
CreatedAt int64
}
SSTableMeta contains metadata about the SSTable.
type SSTableWriter ¶
type SSTableWriter struct {
// contains filtered or unexported fields
}
SSTableWriter builds an SSTable file.
func NewSSTableWriter ¶
NewSSTableWriter creates a new SSTable writer.
func (*SSTableWriter) Abort ¶
func (w *SSTableWriter) Abort() error
Abort closes and removes the incomplete SSTable file.
func (*SSTableWriter) Add ¶
func (w *SSTableWriter) Add(entry Entry) error
Add adds an entry to the SSTable.
func (*SSTableWriter) Close ¶
func (w *SSTableWriter) Close() error
Close closes the writer without finishing.
func (*SSTableWriter) Finish ¶
func (w *SSTableWriter) Finish(level int) error
Finish completes the SSTable and writes the footer.
func (*SSTableWriter) Path ¶
func (w *SSTableWriter) Path() string
Path returns the SSTable file path.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the main key-value store.
func (*Store) Compact ¶
Compact forces compaction of all L0 tables to L1. This makes reads faster by converting overlapping L0 tables to disjoint L1 tables.
func (*Store) GetFloat64 ¶
GetFloat64 retrieves a float64 value by key.
func (*Store) PutFloat64 ¶
PutFloat64 stores a float64 value.
func (*Store) ScanPrefix ¶
ScanPrefix iterates over all keys with the given prefix in sorted order. The callback receives the key and value bytes directly (zero-copy). Return false from the callback to stop iteration. Keys are deduplicated (newest version wins) and tombstones are skipped.
type StoreStats ¶
type StoreStats struct {
MemtableSize int64
MemtableCount int64
CacheStats CacheStats
Levels []LevelStats
}
StoreStats contains store statistics.
type Value ¶
type Value struct {
Type ValueType
// Inline storage for primitives
Int64 int64
Float64 float64
Bool bool
// For strings/bytes - either inline data or pointer to block
Bytes []byte // Used for inline storage (small values)
Pointer *DataPointer // Used for large values stored in data blocks
}
Value represents a typed value in the store.
func DecodeValue ¶
DecodeValue deserializes a value from bytes. Returns the value and number of bytes consumed.
func DecodeValueZeroCopy ¶
DecodeValueZeroCopy deserializes a value without copying byte data. The returned Value's Bytes field points into the input data slice. Caller must ensure data outlives the returned Value. This is faster but the Value is only valid while data is valid.
func Float64Value ¶
Float64Value creates a Value containing a float64.
func StringValue ¶
StringValue creates a Value containing a string.
func TombstoneValue ¶
func TombstoneValue() Value
TombstoneValue creates a tombstone Value for deletions.
func (*Value) EncodedSize ¶
EncodedSize returns the serialized size of a value.
func (Value) IsTombstone ¶
IsTombstone returns true if this value represents a deletion.
type WAL ¶
type WAL struct {
// contains filtered or unexported fields
}
WAL implements write-ahead logging for durability.
func OpenWAL ¶
func OpenWAL(path string, syncMode WALSyncMode) (*WAL, error)
OpenWAL opens or creates a WAL file.
func (*WAL) TruncateBefore ¶
TruncateBefore removes WAL entries with sequence < minSeq. This is used for partial WAL cleanup when some memtables are still pending flush.
type WALSyncMode ¶
type WALSyncMode int
WALSyncMode determines when WAL is synced to disk.
const ( // WALSyncNone never syncs. Fastest but may lose data on crash. WALSyncNone WALSyncMode = iota // WALSyncPerBatch syncs after each batch of writes. Good balance. WALSyncPerBatch // WALSyncPerWrite syncs after each write. Slowest but safest. WALSyncPerWrite )
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer handles all write operations including flushes and compaction.
func (*Writer) ForceCompact ¶
ForceCompact forces compaction of all L0 tables to L1.
func (*Writer) SetSequence ¶
SetSequence sets the sequence number (for recovery).