Documentation
¶
Overview ¶
Package kv is the key-value store for short-lived operational state (counters, breaker state, locks, sessions), with an in-memory backend and a Redis-protocol backend behind the same Store interface. Persistent data belongs in Postgres.
Index ¶
- Constants
- Variables
- func ExecInOrder(ctx context.Context, s Store, ops []BatchOp)
- type Batch
- func (b *Batch) Exec(ctx context.Context)
- func (b *Batch) ExpireNX(key string, ttl time.Duration) *BatchResult
- func (b *Batch) Get(key string) *BatchResult
- func (b *Batch) Incr(key string, delta int64) *BatchResult
- func (b *Batch) Script(call ScriptCall) *BatchResult
- func (b *Batch) ShedWhenPoolBusy()
- type BatchOp
- type BatchOpKind
- type BatchResult
- type BatchScripter
- type Batcher
- type Entry
- type Mem
- func (m *Mem) Close() error
- func (m *Mem) Del(_ context.Context, key string) error
- func (m *Mem) Expire(_ context.Context, key string, ttl time.Duration) error
- func (m *Mem) ExpireNX(_ context.Context, key string, ttl time.Duration) (bool, error)
- func (m *Mem) Get(_ context.Context, key string) ([]byte, error)
- func (m *Mem) HGet(_ context.Context, key, field string) ([]byte, error)
- func (m *Mem) HSet(_ context.Context, key, field string, value []byte, ttl time.Duration) error
- func (m *Mem) Incr(_ context.Context, key string, delta int64) (int64, error)
- func (m *Mem) Range(_ context.Context, prefix string) ([]Entry, error)
- func (m *Mem) RegisterScript(name string, fn ScriptImpl)
- func (m *Mem) RunScript(ctx context.Context, name, _ string, keys []string, args ...any) ([]byte, error)
- func (m *Mem) RunScriptBatch(ctx context.Context, calls []ScriptCall) []ScriptResult
- func (m *Mem) Set(_ context.Context, key string, value []byte, ttl time.Duration) error
- func (m *Mem) WithLock(ctx context.Context, keys []string, fn func(context.Context) error) error
- type PoolShedder
- type Redis
- func (r *Redis) Close() error
- func (r *Redis) Del(ctx context.Context, key string) error
- func (r *Redis) ExecBatch(ctx context.Context, ops []BatchOp)
- func (r *Redis) ExecBatchOrShed(ctx context.Context, ops []BatchOp)
- func (r *Redis) Expire(ctx context.Context, key string, ttl time.Duration) error
- func (r *Redis) ExpireNX(ctx context.Context, key string, ttl time.Duration) (bool, error)
- func (r *Redis) Get(ctx context.Context, key string) ([]byte, error)
- func (r *Redis) Incr(ctx context.Context, key string, delta int64) (int64, error)
- func (r *Redis) Ping(ctx context.Context) error
- func (r *Redis) PoolBusy() bool
- func (r *Redis) Range(ctx context.Context, prefix string) ([]Entry, error)
- func (r *Redis) RunScript(ctx context.Context, name, script string, keys []string, args ...any) ([]byte, error)
- func (r *Redis) RunScriptBatch(ctx context.Context, calls []ScriptCall) []ScriptResult
- func (r *Redis) RunScriptOrShed(ctx context.Context, name, script string, keys []string, args ...any) ([]byte, error)
- func (r *Redis) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (r *Redis) WithLock(ctx context.Context, keys []string, fn func(context.Context) error) error
- type RedisConfig
- type ScriptCall
- type ScriptImpl
- type ScriptResult
- type Scripter
- type SentinelConfig
- type Store
Constants ¶
const ( DefaultDialTimeout = 2 * time.Second DefaultReadTimeout = 1 * time.Second DefaultWriteTimeout = 500 * time.Millisecond DefaultPoolTimeout = 250 * time.Millisecond )
Client defaults: short enough that a stalled server costs a request about a second instead of the library's multi-second defaults. The read bound outlasts two TCP retransmit timeouts (~420–600 ms), so one lost packet doesn't close the connection and force a redial.
Variables ¶
var ErrNoScripter = errors.New("state: store does not run scripts")
ErrNoScripter reports a batched script on a store that runs no scripts.
var ErrNotFound = errors.New("state: key not found")
var ErrNotRun = errors.New("state: command not run")
ErrNotRun marks a failed call the server did not run: it never left relay (no pooled connection, a failed dial, a closed client), or the server refused it with a reply it cannot serve now.
var ErrPoolBusy = fmt.Errorf("%w: %w: connection wait queue full", ErrUnavailable, ErrNotRun)
ErrPoolBusy fails a call refused unsent because the store's connection wait queue was at its bound. It is an ErrUnavailable whose command certainly did not run.
ErrUnavailable marks a call the store could not serve: no reply in time or at all (timeout, exhausted pool, refused or dropped connection), or a reply that the server cannot serve right now (LOADING, READONLY, BUSY, ...). Other error replies are the command's own failure and stay unwrapped. Whether the command ran on the server is unknown unless the error also matches ErrNotRun.
Functions ¶
Types ¶
type Batch ¶ added in v0.11.7
type Batch struct {
// contains filtered or unexported fields
}
Batch queues independent commands and runs them together: one round trip on Redis (a pipeline; on Cluster one per node holding a key, sent concurrently), one call at a time on any other store.
It is not a transaction: each command is atomic on its own, a failed command does not undo the others, and no command sees another's result. Each script's keys must share a hash tag; keys of different commands need not.
func NewBatch ¶ added in v0.11.7
NewBatch returns an empty batch on s with room for size commands; more may be queued.
func (*Batch) Exec ¶ added in v0.11.7
Exec runs the queued commands and empties the batch. Each result carries its own outcome; there is no batch-level error.
func (*Batch) ExpireNX ¶ added in v0.11.7
func (b *Batch) ExpireNX(key string, ttl time.Duration) *BatchResult
ExpireNX queues an EXPIRE NX: key gets ttl only when it has none, so a key's existing deadline is never pushed out.
func (*Batch) Get ¶ added in v0.11.7
func (b *Batch) Get(key string) *BatchResult
Get queues a GET of key.
func (*Batch) Incr ¶ added in v0.11.7
func (b *Batch) Incr(key string, delta int64) *BatchResult
Incr queues an INCRBY of key by delta.
func (*Batch) Script ¶ added in v0.11.7
func (b *Batch) Script(call ScriptCall) *BatchResult
Script queues a script call.
func (*Batch) ShedWhenPoolBusy ¶ added in v0.11.7
func (b *Batch) ShedWhenPoolBusy()
ShedWhenPoolBusy makes every later Exec of b refuse at once, each result failing with ErrPoolBusy and nothing sent, while the store is a PoolShedder whose connection wait queue is at its bound.
type BatchOp ¶ added in v0.11.7
type BatchOp struct {
Kind BatchOpKind
Key string // Get, Incr, ExpireNX
Delta int64 // Incr
TTL time.Duration // ExpireNX
Script ScriptCall // Script
Result *BatchResult
}
BatchOp is one queued command, exported so a store can run a batch its own way (see Batcher).
type BatchOpKind ¶ added in v0.11.7
type BatchOpKind uint8
BatchOpKind names the command a BatchOp runs.
const ( OpGet BatchOpKind = iota OpIncr OpExpireNX OpScript )
type BatchResult ¶ added in v0.11.7
BatchResult is one command's outcome, filled by Exec. Get reports a missing key as ErrNotFound; Incr fills Int; ExpireNX sets Int to 1 when it set the TTL; Script fills Value as RunScript would. A transport failure lands in every result's Err.
type BatchScripter ¶ added in v0.9.8
type BatchScripter interface {
RunScriptBatch(ctx context.Context, calls []ScriptCall) []ScriptResult
}
BatchScripter is an optional interface implemented by stores that can run several independent scripts in a single network round trip (a Redis pipeline). Consumers type-assert to opt in.
Atomicity: each call is individually atomic on its own Cluster slot; the batch provides NO cross-call atomicity. Keys of DIFFERENT calls may live on different slots (each call's own keys must still share a hash tag). Use it only for independent operations — e.g. committing two rate-limit reservations that live under different hash tags and therefore cannot share one CROSSSLOT-safe script.
Results are positional (one per input call, same order); a per-call failure is carried in ScriptResult.Err rather than aborting the batch.
type Batcher ¶ added in v0.11.7
Batcher is implemented by a store that runs a batch in fewer round trips than one per command. ExecBatch fills every op's Result and keeps no reference to ops.
type Mem ¶
type Mem struct {
// contains filtered or unexported fields
}
Mem is an in-memory Store backed by sync.Map.
func (*Mem) ExpireNX ¶ added in v0.11.7
ExpireNX is Redis EXPIRE NX: it sets ttl only on a live key with no expiry and reports whether it did.
func (*Mem) HGet ¶
HGet reads one field of a hash stored as synthetic keys "key\x00field". Returns ErrNotFound when either the hash key or the field is absent.
func (*Mem) HSet ¶
HSet writes one field of a hash stored as synthetic keys "key\x00field". When ttl > 0 the field entry gets that TTL; ttl == 0 preserves existing TTL.
func (*Mem) RegisterScript ¶
func (m *Mem) RegisterScript(name string, fn ScriptImpl)
RegisterScript registers a Go emulator for a named script.
func (*Mem) RunScript ¶
func (m *Mem) RunScript(ctx context.Context, name, _ string, keys []string, args ...any) ([]byte, error)
RunScript looks up the named emulator and invokes it.
func (*Mem) RunScriptBatch ¶ added in v0.9.8
func (m *Mem) RunScriptBatch(ctx context.Context, calls []ScriptCall) []ScriptResult
RunScriptBatch runs each call sequentially. Mem is in-process, so there is no round-trip to batch away; running the emulators in order is semantically identical to a Redis pipeline of independent single-slot scripts.
type PoolShedder ¶ added in v0.11.7
type PoolShedder interface {
// ExecBatchOrShed is ExecBatch, except that while the wait queue is at its bound every op fails with ErrPoolBusy and nothing is sent.
ExecBatchOrShed(ctx context.Context, ops []BatchOp)
// RunScriptOrShed is RunScript, except that while the wait queue is at its bound it fails with ErrPoolBusy and sends nothing.
RunScriptOrShed(ctx context.Context, name, script string, keys []string, args ...any) ([]byte, error)
// PoolBusy reports whether an OrShed call made now would be refused. A lock-free snapshot that reserves nothing, for refusing work before it reaches the store.
PoolBusy() bool
}
PoolShedder is implemented by a store whose calls can queue for a pooled connection. Every call counts toward the queue; only the OrShed calls are refused past its bound, so admission answers at once instead of waiting out the pool timeout to be refused anyway.
type Redis ¶
type Redis struct {
// contains filtered or unexported fields
}
Redis implements Store (and Scripter) backed by Redis/Valkey.
func NewRedis ¶
func NewRedis(ctx context.Context, cfg RedisConfig) (*Redis, error)
NewRedis constructs a Redis and pings the server. Precedence: ClusterAddrs > Sentinel > Addr (single-node).
Each command sent is bounded by PoolTimeout + WriteTimeout + ReadTimeout, plus one DialTimeout on a pool miss: the caller waits on the dial itself, which PoolTimeout does not cover, so dial retries are off. A script call sends one EVALSHA when its SHA is cached, but a SCRIPT LOAD on a cold cache and the NOSCRIPT reload (SCRIPT LOAD, EVALSHA, then EVAL) add commands, up to five bounds in all. The cluster client also resends through its redirect loop (MaxRedirects), which MaxRetries does not govern, so there a script can run twice.
func (*Redis) ExecBatch ¶ added in v0.11.7
ExecBatch implements Batcher with one pipeline: one round trip on a single node, one per involved node on Cluster (go-redis sends those concurrently).
func (*Redis) ExecBatchOrShed ¶ added in v0.11.7
ExecBatchOrShed implements PoolShedder.
func (*Redis) ExpireNX ¶ added in v0.11.7
ExpireNX sets ttl on key only when it has no expiry (EXPIRE NX, Redis 7.0+ and every Valkey) and reports whether it did.
func (*Redis) RunScript ¶
func (r *Redis) RunScript(ctx context.Context, name, script string, keys []string, args ...any) ([]byte, error)
RunScript implements Scripter.
func (*Redis) RunScriptBatch ¶ added in v0.9.8
func (r *Redis) RunScriptBatch(ctx context.Context, calls []ScriptCall) []ScriptResult
RunScriptBatch implements BatchScripter: it issues every call in a single pipeline (one network round trip on single-node; one per involved node on Cluster, dispatched together). Each call is an independent EVALSHA — the batch is NOT a transaction, so a per-call failure does not roll back the others. Keys within one call must share a hash tag; keys ACROSS calls may differ (that is the point — it batches away sequential round trips for operations that cannot share a CROSSSLOT-safe script).
func (*Redis) RunScriptOrShed ¶ added in v0.11.7
func (r *Redis) RunScriptOrShed(ctx context.Context, name, script string, keys []string, args ...any) ([]byte, error)
RunScriptOrShed implements PoolShedder.
func (*Redis) WithLock ¶
WithLock implements the blocking Store contract over SET NX PX: acquisition is retried with jittered backoff (5-25ms) until it succeeds or ctx is done, matching Mem's block-until-acquired semantics. The all-or-nothing Lua acquire (partial holds are rolled back before returning 0) keeps opposite key orders deadlock-free while polling. Cluster safety: all keys must share the same hash tag, else CROSSSLOT.
type RedisConfig ¶
type RedisConfig struct {
Addr string
Sentinel *SentinelConfig
ClusterAddrs []string // non-empty → Cluster mode (redis.NewClusterClient)
DB int
Password string
PoolSize int
MinIdleConns int
// Zero durations take the Default* values below.
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
PoolTimeout time.Duration
// MaxRetries is how many times a failed command is resent; 0 sends it once.
MaxRetries int
// MaxPoolWaiters is how many calls may wait for a connection before the PoolShedder calls refuse; other calls queue regardless. Zero sets no bound.
MaxPoolWaiters int
// Pool names this client in the slow-op log, so a process with more than one pool shows which one ran out.
Pool string
}
RedisConfig configures a Redis store. Exactly one of Addr, Sentinel, or ClusterAddrs should be set. When ClusterAddrs is non-empty, a redis.ClusterClient is used and all multi-key operations (RunScript, WithLock) require keys to share the same hash tag to avoid CROSSSLOT errors.
type ScriptCall ¶ added in v0.9.8
ScriptCall describes one script invocation for a batch.
type ScriptImpl ¶
ScriptImpl is the Go-emulator function registered on MemStore. It receives the store so it can call Get/Set/Incr etc. directly.
type ScriptResult ¶ added in v0.9.8
ScriptResult is the positional result of one ScriptCall in a batch.
type Scripter ¶
type Scripter interface {
RunScript(ctx context.Context, name, script string, keys []string, args ...any) ([]byte, error)
}
ScriptRunner is an optional interface implemented by stores that support named Lua (or equivalent) scripts. Consumers type-assert to opt in.
type SentinelConfig ¶
SentinelConfig configures Sentinel-mode failover.
type Store ¶
type Store interface {
Get(ctx context.Context, key string) ([]byte, error)
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
// Del removes a key. It is a no-op (no error) when the key does not exist.
Del(ctx context.Context, key string) error
Incr(ctx context.Context, key string, delta int64) (int64, error)
Expire(ctx context.Context, key string, ttl time.Duration) error
Range(ctx context.Context, prefix string) ([]Entry, error)
// WithLock runs fn while holding an advisory lock over all keys.
// BLOCKING contract: under contention the call waits (retrying with
// backoff on distributed backends) until the lock is acquired — every
// contender eventually runs fn, or returns the ctx error if ctx is
// cancelled/expires while waiting. It never returns a "busy" error
// without running fn. Mutual exclusion holds across all keys for the
// duration of fn.
WithLock(ctx context.Context, keys []string, fn func(context.Context) error) error
Close() error
}
Store is the operational-state adapter. M1 ships MemStore; M5 will add a Redis-backed implementation.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package kvtest holds kv fixtures for tests: a Recording store that pins the scripts a caller runs, and (integration builds) a Redis/Valkey keyspace of its own per test on the server named by RELAY_TEST_REDIS_ADDR, so test packages run in parallel against one server despite fixed key names and prefix scans.
|
Package kvtest holds kv fixtures for tests: a Recording store that pins the scripts a caller runs, and (integration builds) a Redis/Valkey keyspace of its own per test on the server named by RELAY_TEST_REDIS_ADDR, so test packages run in parallel against one server despite fixed key names and prefix scans. |