store

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

View Source
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 New

func New(n int) *DB

New creates a DB with n shards (rounded up to a power of two).

func (*DB) ActiveExpireCycle

func (db *DB) ActiveExpireCycle(budget int) (expired int, more bool)

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) Delete

func (db *DB) Delete(key string) bool

Delete removes key. It does not emit an event.

func (*DB) Dirty

func (db *DB) Dirty() int64

Dirty returns the number of changes since the last ResetDirty (for save rules).

func (*DB) Emit

func (db *DB) Emit(ev Event)

Emit sends an event to all listeners.

func (*DB) Evict

func (db *DB) Evict(key string) bool

Evict deletes key and emits an "evicted" event. Self-locking.

func (*DB) Flush

func (db *DB) Flush()

Flush deletes every key. Requires LockAll. Emits a "flushall" event.

func (*DB) ForEach

func (db *DB) ForEach(fn func(key string, e *Entry) bool)

ForEach visits every live key until fn returns false. Requires LockAll.

func (*DB) Get

func (db *DB) Get(key string) *Entry

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) GetKind

func (db *DB) GetKind(key string, kind Kind) (*Entry, error)

GetKind is Get plus a type check. Returns (nil, nil) if the key is missing.

func (*DB) Len

func (db *DB) Len() int64

Len returns the number of keys (may include expired keys not yet removed).

func (*DB) Lock

func (db *DB) Lock(keys ...string) func()

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

func (db *DB) NewStringValue(b []byte) *Entry

NewStringValue creates a string entry honouring the compression threshold.

func (*DB) NumShards

func (db *DB) NumShards() int

NumShards returns the shard count.

func (*DB) Peek

func (db *DB) Peek(key string) *Entry

Peek looks up key without touching access info or stats.

func (*DB) Put

func (db *DB) Put(key string, e *Entry)

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) RandomKey

func (db *DB) RandomKey() (string, bool)

RandomKey returns a random live key. Requires LockAll.

func (*DB) Recheck

func (db *DB) Recheck(key string) (Candidate, bool)

Recheck returns the current eviction data of key, for candidates that waited in an eviction pool. Self-locking.

func (*DB) ResetDirty

func (db *DB) ResetDirty(n int64)

func (*DB) Sample

func (db *DB) Sample(shardIdx, n int, volatileOnly bool) []Candidate

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

func (db *DB) SetExpire(key string, atMs int64) bool

SetExpire sets an absolute expiry in unix ms (0 removes it). Returns false if key is missing.

func (*DB) Subscribe

func (db *DB) Subscribe(fn func(Event))

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

func (db *DB) Updated(key string)

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

func (db *DB) UsedMemory() int64

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 NewEntry

func NewEntry(kind Kind, v sizer) *Entry

func (*Entry) Bloom

func (e *Entry) Bloom() *bloom.Filter

func (*Entry) Freq

func (e *Entry) Freq() uint8

Freq returns the LFU counter (for OBJECT FREQ).

func (*Entry) HLL

func (e *Entry) HLL() *hll.HLL

func (*Entry) Hash

func (e *Entry) Hash() *Hash

func (*Entry) JSON

func (e *Entry) JSON() *jsondoc.Doc

func (*Entry) LastAccess

func (e *Entry) LastAccess() int64

LastAccess returns the last access time in unix ms (for OBJECT IDLETIME).

func (*Entry) List

func (e *Entry) List() *deque.Deque

func (*Entry) Series

func (e *Entry) Series() *timeseries.Series

func (*Entry) Set

func (e *Entry) Set() *Set

func (*Entry) Size

func (e *Entry) Size() int64

Size returns the bytes accounted for this entry (MEMORY USAGE).

func (*Entry) Str

func (e *Entry) Str() *String

func (*Entry) Vectors

func (e *Entry) Vectors() *vector.Index

func (*Entry) ZSet

func (e *Entry) ZSet() *skiplist.ZSet

type Event

type Event struct {
	Key      string
	Op       string
	ClientID int64
}

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 NewHash

func NewHash() *Hash

func (*Hash) Del

func (h *Hash) Del(field string) bool

func (*Hash) Encoding

func (h *Hash) Encoding() string

Encoding is the OBJECT ENCODING name.

func (*Hash) Get

func (h *Hash) Get(field string) (string, bool)

func (*Hash) Len

func (h *Hash) Len() int

func (*Hash) Map

func (h *Hash) Map() map[string]string

Map returns the contents as a map, for read-only use. Small hashes build a fresh one, so prefer Range.

func (*Hash) MemSize

func (h *Hash) MemSize() int64

func (*Hash) Range

func (h *Hash) Range(fn func(field, value string) bool)

Range calls fn for each field until fn returns false. Order is unspecified. The hash must not be modified during the call.

func (*Hash) Set

func (h *Hash) Set(field, value string) bool

Set returns true if the field is new.

type Kind

type Kind uint8
const (
	KindString Kind = iota + 1
	KindList
	KindHash
	KindSet
	KindZSet
	KindJSON
	KindTimeSeries
	KindVector
	KindBloom
	KindHLL
)

func (Kind) String

func (k Kind) String() string

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.

func NewSet

func NewSet() *Set

func (*Set) Add

func (s *Set) Add(member string) bool

Add returns true if the member is new.

func (*Set) Encoding

func (s *Set) Encoding() string

Encoding is the OBJECT ENCODING name.

func (*Set) Has

func (s *Set) Has(member string) bool

func (*Set) Len

func (s *Set) Len() int

func (*Set) MemSize

func (s *Set) MemSize() int64

func (*Set) Members

func (s *Set) Members() []string

func (*Set) Random

func (s *Set) Random() (string, bool)

Random returns any member.

func (*Set) Range

func (s *Set) Range(fn func(member string) bool)

Range calls fn for each member until fn returns false. Order is unspecified. The set must not be modified during the call.

func (*Set) Remove

func (s *Set) Remove(member string) bool

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 NewInt

func NewInt(v int64) *String

NewInt returns an int-encoded string.

func NewString

func NewString(b []byte, threshold int) *String

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) Bytes

func (s *String) Bytes() []byte

Bytes returns the value. Do not modify the result.

func (*String) Compressed

func (s *String) Compressed() bool

func (*String) Encoding

func (s *String) Encoding() string

Encoding is the OBJECT ENCODING name.

func (*String) Int

func (s *String) Int() (int64, bool)

Int returns the value if it is int-encoded, letting INCR and friends skip parsing and formatting.

func (*String) Len

func (s *String) Len() int

func (*String) MemSize

func (s *String) MemSize() int64

func (*String) SetInt

func (s *String) SetInt(v int64)

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

func (s *String) StoredSize() int

StoredSize is the size of the stored representation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL