Documentation
¶
Overview ¶
Package store is the keyspace: a map of key → Entry split into shards, each with its own mutex, so commands on different keys run in parallel on all CPU cores. (Redis runs commands on a single thread.)
Locking rule: the command dispatcher locks the shards of a command's keys (DB.Lock) or all shards (DB.LockAll) before calling a handler. Methods in this file assume the caller already holds the right lock. Methods in shard.go that say "self-locking" take locks themselves.
Index ¶
- Variables
- type Candidate
- type DB
- func (db *DB) ActiveExpireCycle(budget int) (expired int, more bool)
- func (db *DB) Delete(key string) bool
- func (db *DB) Dirty() int64
- func (db *DB) Emit(ev Event)
- func (db *DB) Evict(key string) bool
- func (db *DB) Flush()
- func (db *DB) ForEach(fn func(key string, e *Entry) bool)
- func (db *DB) Get(key string) *Entry
- func (db *DB) GetKind(key string, kind Kind) (*Entry, error)
- func (db *DB) Len() int64
- func (db *DB) Lock(keys ...string) func()
- func (db *DB) LockAll() func()
- func (db *DB) NewStringValue(b []byte) *Entry
- func (db *DB) NumShards() int
- func (db *DB) Peek(key string) *Entry
- func (db *DB) Put(key string, e *Entry)
- func (db *DB) RandomKey() (string, bool)
- func (db *DB) Recheck(key string) (Candidate, bool)
- func (db *DB) ResetDirty(n int64)
- func (db *DB) Sample(shardIdx, n int, volatileOnly bool) []Candidate
- func (db *DB) Scan(cursor uint64, count int, match func(key string, e *Entry) bool) (uint64, []string)
- func (db *DB) SetExpire(key string, atMs int64) bool
- func (db *DB) Subscribe(fn func(Event))
- func (db *DB) Updated(key string)
- func (db *DB) UsedMemory() int64
- type Entry
- func (e *Entry) Bloom() *bloom.Filter
- func (e *Entry) Freq() uint8
- func (e *Entry) HLL() *hll.HLL
- func (e *Entry) Hash() *Hash
- func (e *Entry) JSON() *jsondoc.Doc
- func (e *Entry) LastAccess() int64
- func (e *Entry) List() *deque.Deque
- func (e *Entry) Series() *timeseries.Series
- func (e *Entry) Set() *Set
- func (e *Entry) Size() int64
- func (e *Entry) Str() *String
- func (e *Entry) Vectors() *vector.Index
- func (e *Entry) ZSet() *skiplist.ZSet
- type Event
- type Hash
- func (h *Hash) Del(field string) bool
- func (h *Hash) Encoding() string
- func (h *Hash) Get(field string) (string, bool)
- func (h *Hash) Len() int
- func (h *Hash) Map() map[string]string
- func (h *Hash) MemSize() int64
- func (h *Hash) Range(fn func(field, value string) bool)
- func (h *Hash) Set(field, value string) bool
- type Kind
- type Set
- func (s *Set) Add(member string) bool
- func (s *Set) Encoding() string
- func (s *Set) Has(member string) bool
- func (s *Set) Len() int
- func (s *Set) MemSize() int64
- func (s *Set) Members() []string
- func (s *Set) Random() (string, bool)
- func (s *Set) Range(fn func(member string) bool)
- func (s *Set) Remove(member string) bool
- type String
Constants ¶
This section is empty.
Variables ¶
var ErrWrongType = errors.New("WRONGTYPE Operation against a key holding the wrong kind of value")
Functions ¶
This section is empty.
Types ¶
type Candidate ¶
type Candidate struct {
Key string
Access int64 // last access, unix ms
Freq uint8 // Redis-style logarithmic LFU counter
Sketch uint8 // TinyLFU estimate of recent accesses, 0..16
ExpireAt int64
}
Candidate is a key sampled for eviction.
type DB ¶
type DB struct {
Hits, Misses, Expired, Evicted atomic.Int64
// CompressThreshold is read when strings are created (see NewStringValue).
CompressThreshold atomic.Int64
// contains filtered or unexported fields
}
func (*DB) ActiveExpireCycle ¶
ActiveExpireCycle deletes expired keys found in the due buckets of each shard's timing wheel. It checks at most budget wheel entries per shard and holds one shard lock at a time, so a mass expiry can't stall the server; the rest waits for the next cycle. It returns the number of keys deleted and whether due entries are left over. Self-locking.
func (*DB) Flush ¶
func (db *DB) Flush()
Flush deletes every key. Requires LockAll. Emits a "flushall" event.
func (*DB) Get ¶
Get looks up key for a command: expired keys are removed, LRU/LFU info and hit/miss stats are updated. Returns nil if missing.
func (*DB) Lock ¶
Lock locks the shards holding keys (in index order, to avoid deadlocks) and returns the unlock function.
func (*DB) LockAll ¶
func (db *DB) LockAll() func()
LockAll locks every shard (KEYS, FLUSHALL, MULTI/EXEC, scripts, snapshots).
func (*DB) NewStringValue ¶
NewStringValue creates a string entry honouring the compression threshold.
func (*DB) Put ¶
Put inserts or replaces key. The entry's ExpireAt is kept as given. A write counts as an access for the frequency sketch.
func (*DB) Recheck ¶
Recheck returns the current eviction data of key, for candidates that waited in an eviction pool. Self-locking.
func (*DB) ResetDirty ¶
func (*DB) Sample ¶
Sample returns up to n random keys from one shard. With volatileOnly only keys that have a TTL are considered. Self-locking.
func (*DB) Scan ¶
func (db *DB) Scan(cursor uint64, count int, match func(key string, e *Entry) bool) (uint64, []string)
Scan iterates shard by shard. The cursor is the next shard index; 0 starts and a returned 0 means done. Every key present for the whole scan is returned at least once. Requires LockAll.
func (*DB) SetExpire ¶
SetExpire sets an absolute expiry in unix ms (0 removes it). Returns false if key is missing.
func (*DB) Subscribe ¶
Subscribe registers a listener for key events. Listeners run synchronously, often while shard locks are held, so they must be fast and must never lock DB shards themselves.
func (*DB) Updated ¶
Updated must be called after a value is modified in place (LPUSH, HSET...). It refreshes memory accounting and deletes containers that became empty.
func (*DB) UsedMemory ¶
UsedMemory is the estimated bytes used by keys and values.
type Entry ¶
type Entry struct {
Kind Kind
Value sizer
ExpireAt int64 // unix ms; 0 = no expiry
// contains filtered or unexported fields
}
Entry is one key's value plus metadata.
Value holds, depending on Kind:
KindString *String KindList *deque.Deque KindHash *Hash KindSet *Set KindZSet *skiplist.ZSet KindJSON *jsondoc.Doc KindTimeSeries *timeseries.Series KindVector *vector.Index KindBloom *bloom.Filter KindHLL *hll.HLL
func (*Entry) LastAccess ¶
LastAccess returns the last access time in unix ms (for OBJECT IDLETIME).
func (*Entry) Series ¶
func (e *Entry) Series() *timeseries.Series
type Event ¶
Event reports a change to a key. Op is the lowercase command name for writes ("set", "lpush"...), or "expired", "evicted", "del" for internal deletions. Op "flushall" has an empty Key and means every key changed. ClientID is the client that made the change (0 = server itself).
type Hash ¶
type Hash struct {
// contains filtered or unexported fields
}
Hash is a field → value map.
Small hashes are a listpack: a single []byte laid out as [count][flen][field][vlen][value]... (see listpack.go). That beats a []string of fields and values: it is one pointer-free allocation the GC never scans, it has no 16-byte header per string, and it doesn't pin the caller's argument strings. A linear scan over at most 128 short entries is about as fast as hashing. Like Redis, a hash that outgrows the listpack converts to a map once and never converts back.
func (*Hash) Map ¶
Map returns the contents as a map, for read-only use. Small hashes build a fresh one, so prefer Range.
type Set ¶
type Set struct {
// contains filtered or unexported fields
}
Set is a set of strings with three encodings, as in Redis:
- intset: while every member is a canonical int64, a sorted array of 2-, 4- or 8-byte little-endian integers (the narrowest width that fits them all), searched by bisection;
- listpack: up to 128 members of at most 64 bytes, packed one after another (see listpack.go) and searched linearly;
- hashtable: a map, for anything bigger. Sets never convert back.
The packed encodings share one []byte whose first byte says which one it is: the integer width, or setListpack. For a listpack the second byte is the member count.
type String ¶
type String struct {
// contains filtered or unexported fields
}
String is a byte string. Canonical integers are stored as an int64 and large values are transparently compressed. The three encodings share two words so a String stays a 32-byte allocation:
data == nil int: the value is n data != nil, n == 0 raw bytes data != nil, n > 0 compressed bytes; n is the uncompressed length
func NewString ¶
NewString stores b, as an integer when it is the canonical form of one, otherwise compressed if threshold > 0 and len(b) >= threshold.
func (*String) Compressed ¶
func (*String) Int ¶
Int returns the value if it is int-encoded, letting INCR and friends skip parsing and formatting.
func (*String) SetInt ¶
SetInt replaces the value with an integer in place. Earlier Bytes results stay valid: they are either fresh copies or byte slices that are dropped, not overwritten.
func (*String) StoredSize ¶
StoredSize is the size of the stored representation.