command

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: 49 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 command holds the command table and the dispatcher (Engine.Execute).

Each command group lives in its own file and registers its commands from init(). A handler receives a *Ctx with the parsed arguments; the dispatcher has already checked arity, auth/ACL, MULTI queuing, namespaces, cluster slots, memory limits, and locked the shards of the command's keys.

Index

Constants

View Source
const RedisVersion = "7.2.0"

RedisVersion is reported as redis_version in INFO; client libraries check it for feature support.

Variables

View Source
var (
	ErrSyntax   = resp.Err("ERR syntax error")
	ErrNotInt   = resp.Err("ERR value is not an integer or out of range")
	ErrNotFloat = resp.Err("ERR value is not a valid float")
	ErrWrongTyp = resp.Err("WRONGTYPE Operation against a key holding the wrong kind of value")
	ErrNoKey    = resp.Err("ERR no such key")
	ErrOverflow = resp.Err("ERR increment or decrement would overflow")
)
View Source
var OnShutdown func(save bool) error

OnShutdown is set by main; it saves (if asked) and exits the process.

View Source
var Version = "0.1.0-dev"

Version is the cache-boy release; release builds set it with -ldflags "-X github.com/shamim3696/cache-boy/internal/command.Version=x.y.z".

Functions

func ParseFloat

func ParseFloat(s string) (float64, bool)

func ParseInt

func ParseInt(s string) (int64, bool)

func Register

func Register(specs ...*Spec)

Register adds commands to the table. Call it from init().

func SetRaft

func SetRaft(e *Engine, r RaftStatus)

SetRaft makes a Raft node visible to RAFT.STATUS (nil removes it).

Types

type Client

type Client struct {
	ID      int64
	Addr    string
	Created time.Time
	Kind    string // "tcp", "http", "ws", "internal", "master"

	// Fields below are only touched by the goroutine running this client's
	// commands, except where atomic.
	User      string // authenticated user name; "" = not authenticated
	Namespace string
	Multi     *transaction.Queue
	Watcher   *transaction.Watcher
	IsMaster  bool // replication link from our leader: bypasses READONLY
	Tracking  bool

	// Hijack, when set by a handler, is called by the TCP server after the
	// reply is flushed; it then owns the connection (used by replication SYNC).
	Hijack func(conn net.Conn, r *resp.Reader)
	// CloseAfterReply makes the server close the connection after the reply (QUIT).
	CloseAfterReply bool
	// contains filtered or unexported fields
}

Client is the state of one connection (TCP, HTTP request, WebSocket, or internal: AOF loading, replication link, scripts).

func (*Client) Authenticated

func (c *Client) Authenticated() bool

Authenticated reports whether the client may run normal commands.

func (*Client) ClientID

func (c *Client) ClientID() int64

func (*Client) Close

func (c *Client) Close()

Close disconnects the client. Safe to call more than once.

func (*Client) Closed

func (c *Client) Closed() bool

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done is closed when the client disconnects.

func (*Client) Idle

func (c *Client) Idle() time.Duration

func (*Client) LastCommand

func (c *Client) LastCommand() string

func (*Client) Name

func (c *Client) Name() string

func (*Client) Out

func (c *Client) Out() <-chan resp.Value

Out is the stream of replies and pushes to write to the connection.

func (*Client) Proto

func (c *Client) Proto() int

func (*Client) Push

func (c *Client) Push(v resp.Value) bool

Push queues an out-of-band message (pub/sub, invalidation, monitor). It never blocks: a client that can't keep up is disconnected.

func (*Client) Reply

func (c *Client) Reply(v resp.Value)

Reply queues a command reply; it waits if the buffer is full.

func (*Client) SetCloser

func (c *Client) SetCloser(fn func())

SetCloser sets the function that closes the underlying connection.

func (*Client) SetName

func (c *Client) SetName(n string)

func (*Client) SetProto

func (c *Client) SetProto(p int)

type ClusterRouter

type ClusterRouter interface {
	Enabled() bool
	// Check returns a MOVED or CROSSSLOT error if keys are not served here.
	Check(keys []string) error
	// Command runs a CLUSTER subcommand (args excludes "CLUSTER").
	Command(args []string) resp.Value
	Info() [][2]string
}

ClusterRouter is implemented by the cluster package.

type Ctx

type Ctx struct {
	E    *Engine
	C    *Client
	Args []string // Args[0] is the command name as sent; key args are already namespaced
	Name string   // lowercase command name
	Keys []string // key arguments (namespaced), locked by the dispatcher

	// InExec is true inside MULTI/EXEC and scripts (all shards already locked).
	InExec bool

	// Blocking support (see Block).
	WouldBlock   bool
	BlockTimeout time.Duration // 0 = forever
	BlockOn      []string      // keys to wait on; defaults to Keys
	// TimedOut is set when the handler is re-run after the block timeout.
	TimedOut bool
	// contains filtered or unexported fields
}

Ctx is passed to command handlers.

func (*Ctx) Arg

func (x *Ctx) Arg(i int) string

Arg returns argument i ("" if out of range).

func (*Ctx) ArgLower

func (x *Ctx) ArgLower(i int) string

ArgLower returns argument i in lower case (for option names).

func (*Ctx) Block

func (x *Ctx) Block(timeout time.Duration, keys ...string) resp.Value

Block asks the dispatcher to wait until one of keys (default: the command's keys) is written or timeout passes, then call the handler again. When the timeout passes the handler runs once more with TimedOut set and must return a final reply. Typical use:

if v, ok := tryPop(); ok { return v }
if ctx.TimedOut { return resp.NullArray() }
return ctx.Block(timeout)

func (*Ctx) DB

func (x *Ctx) DB() *store.DB

func (*Ctx) Emit

func (x *Ctx) Emit(key string)

Emit sends a key event for a key that isn't one of the command's key arguments (e.g. keys deleted by TAG.INVALIDATE or FLUSHALL).

func (*Ctx) Float

func (x *Ctx) Float(i int) (float64, bool)

func (*Ctx) Int

func (x *Ctx) Int(i int) (int64, bool)

func (*Ctx) NArgs

func (x *Ctx) NArgs() int

func (*Ctx) NoChange

func (x *Ctx) NoChange()

NoChange tells the dispatcher the write command changed nothing (SETNX on an existing key, DEL of a missing key): no key events, nothing propagated.

func (*Ctx) Now

func (x *Ctx) Now() int64

Now returns the current time in unix milliseconds.

func (*Ctx) Propagate

func (x *Ctx) Propagate(args ...string)

Propagate replaces what is written to AOF/replicas for this command (may be called several times to emit several commands). Use it to make non-deterministic or relative commands safe to replay, e.g. turning "EXPIRE k 10" into "PEXPIREAT k <abs ms>".

func (*Ctx) PropagateNow

func (x *Ctx) PropagateNow(args ...string)

PropagateNow writes a command to AOF/replicas immediately. For FlagAllKeys commands that touch keys not in their arguments; call it while still holding the locks (i.e. inside the handler).

func (*Ctx) Proto

func (x *Ctx) Proto() int

Proto returns the client's protocol version (2 or 3).

func (*Ctx) StoredKey

func (x *Ctx) StoredKey(user string) string

StoredKey converts a client key to the stored key (namespace added). Only needed for keys that are not declared key arguments.

func (*Ctx) UserKey

func (x *Ctx) UserKey(stored string) (string, bool)

UserKey converts a stored key to what the client sees (namespace removed). ok is false if the key belongs to another namespace.

type Dumper

type Dumper interface {
	Dump(emit func(args []string))
}

Dumper is a feature module with state outside the keyspace (queues, tags...). Dump emits commands that recreate that state; used by snapshots, AOF rewrite and replica full sync.

type Engine

type Engine struct {
	Cfg      *config.Store
	DB       *store.DB
	Auth     *auth.Store
	PubSub   *pubsub.Hub
	Tx       *transaction.Manager
	Blocking *blocking.Queue
	Tracking *tracking.Table
	Evictor  *eviction.Evictor
	Metrics  *observability.Metrics
	Slowlog  *observability.Slowlog
	Monitor  *observability.Monitor

	Tags      *tags.Index
	RateLimit *ratelimit.Limiter
	Locks     *lock.Manager
	Queues    *queue.Manager
	Watch     *watch.Hub
	Flight    *singleflight.Group
	History   *history.Store
	Scripts   *scripting.Scripts
	SemCache  *semcache.Manager

	// Optional subsystems, set by main before serving (nil = disabled).
	Persist Persister
	Repl    Replicator
	Cluster ClusterRouter

	StartTime time.Time
	RunID     string
	// contains filtered or unexported fields
}

Engine owns the dataset and every subsystem, and executes commands.

func New

func New(cfg *config.Store) *Engine

func (*Engine) AddPropagator

func (e *Engine) AddPropagator(p Propagator)

AddPropagator registers a receiver of write commands (AOF, replication).

func (*Engine) ClientByID

func (e *Engine) ClientByID(id int64) *Client

func (*Engine) Clients

func (e *Engine) Clients() []*Client

Clients returns connected clients sorted by ID.

func (*Engine) DumpModules

func (e *Engine) DumpModules(emit func(args []string))

DumpModules emits commands that recreate the state feature modules keep outside the keyspace (queues, tags, webhooks...). Snapshots store keys in binary form and append these commands. The caller must hold DB.LockAll().

func (*Engine) ExecLocked

func (e *Engine) ExecLocked(c *Client, args []string) resp.Value

ExecLocked runs a command while the caller already holds DB.LockAll() (inside EXEC and scripts). Blocking commands behave as if they timed out.

func (*Engine) Execute

func (e *Engine) Execute(c *Client, args []string) resp.Value

Execute runs one command for a client and returns the reply.

func (*Engine) InfoSections

func (e *Engine) InfoSections() []InfoSection

InfoSections returns INFO data (also used by the HTTP API and dashboard).

func (*Engine) InternalClient

func (e *Engine) InternalClient(kind string, master bool) *Client

InternalClient returns an authenticated client that is not listed in CLIENT LIST, for AOF loading, scripts and the replication link. With master=true it may write even on a read-only replica.

func (*Engine) Loading

func (e *Engine) Loading() bool

func (*Engine) NewClient

func (e *Engine) NewClient(kind, addr string) *Client

NewClient registers a client. kind is "tcp", "http" or "ws".

func (*Engine) OnClientClose

func (e *Engine) OnClientClose(fn func(*Client))

OnClientClose registers cleanup for feature modules. Call before serving.

func (*Engine) RemoveClient

func (e *Engine) RemoveClient(c *Client)

RemoveClient cleans up after a disconnect.

func (*Engine) RemovePropagator

func (e *Engine) RemovePropagator(p Propagator)

RemovePropagator unregisters p.

func (*Engine) SetConfig

func (e *Engine) SetConfig(name, value string) error

SetConfig changes a parameter and applies side effects.

func (*Engine) SetLoading

func (e *Engine) SetLoading(b bool)

SetLoading marks the engine as replaying AOF/snapshot data: writes are not propagated and memory limits are not enforced.

func (*Engine) Start

func (e *Engine) Start()

Start launches background jobs (active expiry).

func (*Engine) Stop

func (e *Engine) Stop()

Stop ends background jobs and wakes blocked clients.

func (*Engine) Stopping

func (e *Engine) Stopping() <-chan struct{}

Stopping is closed when the server shuts down.

type Flag

type Flag uint32
const (
	FlagWrite       Flag = 1 << iota // modifies data: emits key events, goes to AOF/replicas
	FlagReadOnly                     // reads data: client-side caching remembers its keys
	FlagAdmin                        // server administration
	FlagNoAuth                       // allowed before AUTH (AUTH, HELLO, QUIT)
	FlagAllKeys                      // locks every shard (KEYS, FLUSHALL, EXEC, EVAL...)
	FlagBlocking                     // may wait for a key to change (BLPOP)
	FlagNoMulti                      // runs immediately even inside MULTI (EXEC, DISCARD, WATCH)
	FlagPubSub                       // allowed in RESP2 subscriber mode
	FlagDenyOOM                      // may grow memory: refused/evicts when over maxmemory
	FlagNoPropagate                  // never written to AOF/replicas (EXEC, EVAL propagate their effects)
	FlagNoScript                     // not callable from scripts
	FlagLoading                      // allowed while loading data
)

type InfoSection

type InfoSection struct {
	Name   string
	Fields [][2]string
}

type Persister

type Persister interface {
	Save() error
	BgSave() error
	BgRewriteAOF() error
	LastSave() time.Time
	Info() [][2]string
}

Persister is implemented by the persistence package.

type Propagator

type Propagator interface {
	Propagate(args []string)
}

Propagator receives every write command after it runs (AOF, replicas).

type RaftStatus

type RaftStatus interface {
	Status() (id, state string, term uint64, leader string)
}

RaftStatus is implemented by *raft.Node.

type Replicator

type Replicator interface {
	IsReplica() bool
	// ReplicaOf starts following a leader at "host:port"; "" makes this node a leader.
	ReplicaOf(addr string) error
	Role() resp.Value
	// Sync handles SYNC/PSYNC from a replica. It usually hijacks the connection.
	Sync(c *Client, args []string) resp.Value
	ReplConf(c *Client, args []string) resp.Value
	// Wait blocks until n replicas acknowledged all writes so far, or timeout.
	Wait(n int, timeout time.Duration) int
	Info() [][2]string
}

Replicator is implemented by the replication package.

type Spec

type Spec struct {
	Name  string // lowercase
	Arity int    // Redis style, counting the name: N = exactly N args, -N = at least N
	Flags Flag
	Group string // string, list, hash, set, sortedset, json, timeseries, vector, keyspace,

	// Key positions in Args (Args[0] is the command name). LastKey -1 means
	// the last argument, -2 the one before. FirstKey 0 means no keys.
	FirstKey, LastKey, KeyStep int
	// KeysFn overrides the positions above for commands like EVAL or ZUNION
	// where key positions depend on a numkeys argument.
	KeysFn func(args []string) []int

	Summary string
	Handler func(*Ctx) resp.Value
	// contains filtered or unexported fields
}

Spec describes one command.

func All

func All() []*Spec

All returns every command, sorted by name.

func Lookup

func Lookup(name string) *Spec

Lookup returns the spec of a command (case-insensitive) or nil.

func (*Spec) Calls

func (s *Spec) Calls() int64

Calls returns how many times the command ran.

func (*Spec) Categories

func (s *Spec) Categories() []string

Categories returns ACL categories for the command.

func (*Spec) FlagNames

func (s *Spec) FlagNames() []string

FlagNames lists flags for COMMAND INFO.

func (*Spec) KeyIndexes

func (s *Spec) KeyIndexes(args []string) []int

KeyIndexes returns the positions of key arguments in args.

Jump to

Keyboard shortcuts

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