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
- Variables
- func ParseFloat(s string) (float64, bool)
- func ParseInt(s string) (int64, bool)
- func Register(specs ...*Spec)
- func SetRaft(e *Engine, r RaftStatus)
- type Client
- func (c *Client) Authenticated() bool
- func (c *Client) ClientID() int64
- func (c *Client) Close()
- func (c *Client) Closed() bool
- func (c *Client) Done() <-chan struct{}
- func (c *Client) Idle() time.Duration
- func (c *Client) LastCommand() string
- func (c *Client) Name() string
- func (c *Client) Out() <-chan resp.Value
- func (c *Client) Proto() int
- func (c *Client) Push(v resp.Value) bool
- func (c *Client) Reply(v resp.Value)
- func (c *Client) SetCloser(fn func())
- func (c *Client) SetName(n string)
- func (c *Client) SetProto(p int)
- type ClusterRouter
- type Ctx
- func (x *Ctx) Arg(i int) string
- func (x *Ctx) ArgLower(i int) string
- func (x *Ctx) Block(timeout time.Duration, keys ...string) resp.Value
- func (x *Ctx) DB() *store.DB
- func (x *Ctx) Emit(key string)
- func (x *Ctx) Float(i int) (float64, bool)
- func (x *Ctx) Int(i int) (int64, bool)
- func (x *Ctx) NArgs() int
- func (x *Ctx) NoChange()
- func (x *Ctx) Now() int64
- func (x *Ctx) Propagate(args ...string)
- func (x *Ctx) PropagateNow(args ...string)
- func (x *Ctx) Proto() int
- func (x *Ctx) StoredKey(user string) string
- func (x *Ctx) UserKey(stored string) (string, bool)
- type Dumper
- type Engine
- func (e *Engine) AddPropagator(p Propagator)
- func (e *Engine) ClientByID(id int64) *Client
- func (e *Engine) Clients() []*Client
- func (e *Engine) DumpModules(emit func(args []string))
- func (e *Engine) ExecLocked(c *Client, args []string) resp.Value
- func (e *Engine) Execute(c *Client, args []string) resp.Value
- func (e *Engine) InfoSections() []InfoSection
- func (e *Engine) InternalClient(kind string, master bool) *Client
- func (e *Engine) Loading() bool
- func (e *Engine) NewClient(kind, addr string) *Client
- func (e *Engine) OnClientClose(fn func(*Client))
- func (e *Engine) RemoveClient(c *Client)
- func (e *Engine) RemovePropagator(p Propagator)
- func (e *Engine) SetConfig(name, value string) error
- func (e *Engine) SetLoading(b bool)
- func (e *Engine) Start()
- func (e *Engine) Stop()
- func (e *Engine) Stopping() <-chan struct{}
- type Flag
- type InfoSection
- type Persister
- type Propagator
- type RaftStatus
- type Replicator
- type Spec
Constants ¶
const RedisVersion = "7.2.0"
RedisVersion is reported as redis_version in INFO; client libraries check it for feature support.
Variables ¶
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") )
var OnShutdown func(save bool) error
OnShutdown is set by main; it saves (if asked) and exits the process.
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 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 ¶
Authenticated reports whether the client may run normal commands.
func (*Client) Close ¶
func (c *Client) Close()
Close disconnects the client. Safe to call more than once.
func (*Client) Done ¶
func (c *Client) Done() <-chan struct{}
Done is closed when the client disconnects.
func (*Client) LastCommand ¶
func (*Client) Push ¶
Push queues an out-of-band message (pub/sub, invalidation, monitor). It never blocks: a client that can't keep up is disconnected.
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) Block ¶
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) Emit ¶
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) 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) Propagate ¶
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 ¶
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).
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 (*Engine) AddPropagator ¶
func (e *Engine) AddPropagator(p Propagator)
AddPropagator registers a receiver of write commands (AOF, replication).
func (*Engine) ClientByID ¶
func (*Engine) DumpModules ¶
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 ¶
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) InfoSections ¶
func (e *Engine) InfoSections() []InfoSection
InfoSections returns INFO data (also used by the HTTP API and dashboard).
func (*Engine) InternalClient ¶
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) OnClientClose ¶
OnClientClose registers cleanup for feature modules. Call before serving.
func (*Engine) RemoveClient ¶
RemoveClient cleans up after a disconnect.
func (*Engine) RemovePropagator ¶
func (e *Engine) RemovePropagator(p Propagator)
RemovePropagator unregisters p.
func (*Engine) SetLoading ¶
SetLoading marks the engine as replaying AOF/snapshot data: writes are not propagated and memory limits are not enforced.
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 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 ¶
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 (*Spec) Categories ¶
Categories returns ACL categories for the command.
func (*Spec) KeyIndexes ¶
KeyIndexes returns the positions of key arguments in args.
Source Files
¶
- alias.go
- auth.go
- bloom.go
- cache.go
- client.go
- cluster.go
- ctx.go
- engine.go
- hash.go
- history.go
- hll.go
- interfaces.go
- json.go
- keys.go
- list.go
- lock.go
- namespace.go
- persistence.go
- pubsub.go
- queue.go
- ratelimit.go
- registry.go
- replication.go
- scripting.go
- semcache.go
- server.go
- set.go
- string.go
- tags.go
- timeseries.go
- transaction.go
- vector.go
- watch.go
- zset.go