kv

package
v0.11.7 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 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 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

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

View Source
var ErrNoScripter = errors.New("state: store does not run scripts")

ErrNoScripter reports a batched script on a store that runs no scripts.

View Source
var ErrNotFound = errors.New("state: key not found")
View Source
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.

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

View Source
var ErrUnavailable = errors.New("state: store unavailable")

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

func ExecInOrder added in v0.11.7

func ExecInOrder(ctx context.Context, s Store, ops []BatchOp)

ExecInOrder runs ops one at a time through s, which is how a batch runs on a store that is not a Batcher. kv.Mem is deliberately not one, so a test double wrapping it still sees every command.

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

func NewBatch(s Store) *Batch

NewBatch returns an empty batch on s.

func (*Batch) Exec added in v0.11.7

func (b *Batch) Exec(ctx context.Context)

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

type BatchResult struct {
	Value []byte
	Int   int64
	Err   error
}

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

type Batcher interface {
	ExecBatch(ctx context.Context, ops []BatchOp)
}

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 Entry

type Entry struct {
	Key   string
	Value []byte
}

type Mem

type Mem struct {
	// contains filtered or unexported fields
}

Mem is an in-memory Store backed by sync.Map.

func NewMem

func NewMem() *Mem

NewMem constructs a Mem and starts the TTL janitor.

func (*Mem) Close

func (m *Mem) Close() error

func (*Mem) Del

func (m *Mem) Del(_ context.Context, key string) error

func (*Mem) Expire

func (m *Mem) Expire(_ context.Context, key string, ttl time.Duration) error

func (*Mem) ExpireNX added in v0.11.7

func (m *Mem) ExpireNX(_ context.Context, key string, ttl time.Duration) (bool, error)

ExpireNX is Redis EXPIRE NX: it sets ttl only on a live key with no expiry and reports whether it did.

func (*Mem) Get

func (m *Mem) Get(_ context.Context, key string) ([]byte, error)

func (*Mem) HGet

func (m *Mem) HGet(_ context.Context, key, field string) ([]byte, error)

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

func (m *Mem) HSet(_ context.Context, key, field string, value []byte, ttl time.Duration) error

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

func (m *Mem) Incr(_ context.Context, key string, delta int64) (int64, error)

func (*Mem) Range

func (m *Mem) Range(_ context.Context, prefix string) ([]Entry, error)

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.

func (*Mem) Set

func (m *Mem) Set(_ context.Context, key string, value []byte, ttl time.Duration) error

func (*Mem) WithLock

func (m *Mem) WithLock(ctx context.Context, keys []string, fn func(context.Context) error) error

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

func (r *Redis) Close() error

func (*Redis) Del

func (r *Redis) Del(ctx context.Context, key string) error

func (*Redis) ExecBatch added in v0.11.7

func (r *Redis) ExecBatch(ctx context.Context, ops []BatchOp)

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

func (r *Redis) ExecBatchOrShed(ctx context.Context, ops []BatchOp)

ExecBatchOrShed implements PoolShedder.

func (*Redis) Expire

func (r *Redis) Expire(ctx context.Context, key string, ttl time.Duration) error

func (*Redis) ExpireNX added in v0.11.7

func (r *Redis) ExpireNX(ctx context.Context, key string, ttl time.Duration) (bool, error)

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

func (r *Redis) Get(ctx context.Context, key string) ([]byte, error)

func (*Redis) Incr

func (r *Redis) Incr(ctx context.Context, key string, delta int64) (int64, error)

func (*Redis) Ping

func (r *Redis) Ping(ctx context.Context) error

Ping checks the connection.

func (*Redis) PoolBusy added in v0.11.7

func (r *Redis) PoolBusy() bool

PoolBusy implements PoolShedder.

func (*Redis) Range

func (r *Redis) Range(ctx context.Context, prefix string) ([]Entry, error)

TODO(kv): Cluster-unsafe — SCAN only covers one shard.

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

func (r *Redis) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

func (*Redis) WithLock

func (r *Redis) WithLock(ctx context.Context, keys []string, fn func(context.Context) error) error

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

type ScriptCall struct {
	Name   string
	Script string
	Keys   []string
	Args   []any
}

ScriptCall describes one script invocation for a batch.

type ScriptImpl

type ScriptImpl func(ctx context.Context, store *Mem, keys []string, args []any) ([]byte, error)

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

type ScriptResult struct {
	Value []byte
	Err   error
}

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

type SentinelConfig struct {
	MasterName       string
	SentinelAddrs    []string
	SentinelPassword string
}

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.

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.

Jump to

Keyboard shortcuts

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