Documentation
¶
Index ¶
- Constants
- Variables
- func ClearPubSubBroker()
- func ClearScriptingEngine()
- func CommandCount() int
- func CommandHasCategory(cmd CommandType, cat CommandCategory) bool
- func CommandNamesList(fn func(name string, cmd CommandType) bool)
- func EncodeElementID(hlc time.Time, nodeID pb.NodeID) []byte
- func GetAllCategoryNames() []string
- func GetCategoryName(cat CommandCategory) string
- func GetDataBuf(n int) []byte
- func GetDefaultIDMPDuration() int64
- func GetDefaultIDMPMaxSize() int64
- func GetNodeID() pb.NodeID
- func GetProtoMaxBulkLen() int64
- func GetStreamNodeMaxEntries() int64
- func HLLHash(data []byte) uint64
- func HLLRho(bits uint64) uint8
- func InitEffectsGlobals(nodeID pb.NodeID)
- func KeysAfterStreams(cmd *Command) []string
- func KeysAll(cmd *Command) []string
- func KeysAllButLast(cmd *Command) []string
- func KeysFirst(cmd *Command) []string
- func KeysFirstTwo(cmd *Command) []string
- func KeysMSetStyle(cmd *Command) []string
- func KeysNumkeysAtOffset(cmd *Command, offset int) []string
- func KeysSortCmd(cmd *Command) []string
- func NextHLC() time.Time
- func NextToken(b []byte) (token, rest []byte)
- func ParseBlockingTimeout(s string) (float64, string)
- func ParseFloat64(b []byte) (float64, bool)
- func ParseInt64(b []byte) (int64, bool)
- func ParseUint64(b []byte) (uint64, bool)
- func PutCommand(cmd *Command)
- func PutDataBuf(buf []byte)
- func PutWriter(w *Writer)
- func ReconstructBytes(snap *pb.ReducedEffect) ([]byte, bool)
- func RegisterBytesReconstructor(vt pb.ValueType, fn BytesReconstructor)
- func RegisterModuleCommands(entries ...ModuleEntry)
- func SetDefaultIDMPDuration(v int64)
- func SetDefaultIDMPMaxSize(v int64)
- func SetProtoMaxBulkLen(v int64)
- func SetPubSubBroker(b PubSubBroker)
- func SetPubSubClusterRouter(r PubSubClusterRouter)
- func SetScriptingEngine(e ScriptingEngine)
- func SetServerStats(s *Stats)
- func SetStreamNodeMaxEntries(v int64)
- func ToUpper(b []byte) []byte
- type ACLSelector
- type ACLUser
- type BytesReconstructor
- type Command
- type CommandCategory
- type CommandEntry
- type CommandExecutor
- type CommandFlags
- type CommandHandler
- type CommandRunner
- type CommandStats
- type CommandStatsSnapshot
- type CommandType
- type ConnHandlerFunc
- type Connection
- func (c *Connection) Block(timeout float64) (context.Context, func())
- func (c *Connection) ClearWatches()
- func (c *Connection) InPubSubMode() bool
- func (c *Connection) IsBlocked() bool
- func (c *Connection) IsRESP3() bool
- func (c *Connection) ResetTransaction()
- func (c *Connection) Unblock(withError bool) bool
- func (c *Connection) WasUnblockedWithError() bool
- type Consumer
- type ConsumerGroup
- type Database
- type DatabaseManager
- type HLLValue
- type HandlerFunc
- type HashValue
- type KeyExtractFunc
- type KeyPattern
- type KeyPatternType
- type ListValue
- type ModuleEntry
- type Parser
- type PendingEntry
- type ProtocolVersion
- type PubSubBroker
- type PubSubClient
- type PubSubClusterRouter
- type PubSubMessage
- type QueuedCommand
- type RedisValue
- type RefMode
- type Registration
- type Registry
- type ScriptingEngine
- type SetValue
- type Snapshot
- type Stats
- func (s *Stats) ClientBlocked()
- func (s *Stats) ClientUnblocked()
- func (s *Stats) CmdLatencyP50() time.Duration
- func (s *Stats) CmdLatencyP99() time.Duration
- func (s *Stats) ConnectionClosed()
- func (s *Stats) ConnectionOpened()
- func (s *Stats) GetCommandStats() map[string]CommandStatsSnapshot
- func (s *Stats) GetErrorStats() map[string]uint64
- func (s *Stats) GetLatencyP50() time.Duration
- func (s *Stats) GetLatencyP99() time.Duration
- func (s *Stats) HitRate() float64
- func (s *Stats) RecordCommand(cmd CommandType, usec uint64, failed bool)
- func (s *Stats) RecordError(prefix string)
- func (s *Stats) RecordGetLatency(d time.Duration)
- func (s *Stats) RecordSetLatency(d time.Duration)
- func (s *Stats) Reset()
- func (s *Stats) SetLatencyP50() time.Duration
- func (s *Stats) SetLatencyP99() time.Duration
- func (s *Stats) Snapshot() Snapshot
- func (s *Stats) Uptime() time.Duration
- type StreamEntry
- type StreamID
- type StreamValue
- type SubscriptionManager
- func (m *SubscriptionManager[T]) BlockingKeyCount() int64
- func (m *SubscriptionManager[T]) BlockingKeyCounts() (total int64, nokey int64)
- func (m *SubscriptionManager[T]) Enqueue(channel []byte, _ T) bool
- func (m *SubscriptionManager[T]) Notify(channel []byte) bool
- func (m *SubscriptionManager[T]) NotifyAll()
- func (m *SubscriptionManager[T]) NotifyAllWaiters(channel []byte)
- func (m *SubscriptionManager[T]) Register(ctx context.Context, channels ...[]byte) (*Registration[T], error)
- func (m *SubscriptionManager[T]) RegisterWithNoKey(ctx context.Context, channels ...[]byte) (*Registration[T], error)
- func (m *SubscriptionManager[T]) RegisterWithOptions(ctx context.Context, unblockOnNoKey bool, channels ...[]byte) (*Registration[T], error)
- type Topic
- type TrimOptions
- type TxnPrepareFunc
- type ValueType
- type Waiter
- type WatchedKey
- type Writer
- func (w *Writer) Buffer() *bytes.Buffer
- func (w *Writer) Protocol() ProtocolVersion
- func (w *Writer) Reset(buf *bytes.Buffer)
- func (w *Writer) ResetErrorFlag()
- func (w *Writer) Scratch() *bytes.Buffer
- func (w *Writer) SetProtocol(p ProtocolVersion)
- func (w *Writer) SetStats(s *Stats)
- func (w *Writer) WriteArray(count int)
- func (w *Writer) WriteAttribute(count int)
- func (w *Writer) WriteBigNumber(n string)
- func (w *Writer) WriteBlobError(errType, msg string)
- func (w *Writer) WriteBoolean(b bool)
- func (w *Writer) WriteBulkString(b []byte)
- func (w *Writer) WriteBulkStringStr(s string)
- func (w *Writer) WriteDouble(f float64)
- func (w *Writer) WriteError(msg string)
- func (w *Writer) WriteErrorf(format string, args ...any)
- func (w *Writer) WriteInteger(n int64)
- func (w *Writer) WriteMap(count int)
- func (w *Writer) WriteNoAuth()
- func (w *Writer) WriteNotInteger()
- func (w *Writer) WriteNull()
- func (w *Writer) WriteNullArray()
- func (w *Writer) WriteNullBulkString()
- func (w *Writer) WriteOK()
- func (w *Writer) WriteOne()
- func (w *Writer) WriteOutOfRange()
- func (w *Writer) WritePong()
- func (w *Writer) WritePush(count int)
- func (w *Writer) WriteQueued()
- func (w *Writer) WriteRaw(data []byte)
- func (w *Writer) WriteScore(f float64)
- func (w *Writer) WriteSet(count int)
- func (w *Writer) WriteSimpleString(s string)
- func (w *Writer) WriteSyntaxError()
- func (w *Writer) WriteUnknownCommand(cmd string, args [][]byte)
- func (w *Writer) WriteVerbatimString(encoding string, data []byte)
- func (w *Writer) WriteWrongNumArgs(cmd string)
- func (w *Writer) WriteWrongNumArguments(cmd string)
- func (w *Writer) WriteWrongType()
- func (w *Writer) WriteZero()
- func (w *Writer) WroteError() bool
- type ZSetEntry
- type ZSetValue
- func (z *ZSetValue) Sorted() []ZSetEntry
- func (z *ZSetValue) SortedReverse() []ZSetEntry
- func (z *ZSetValue) ZAdd(members map[string]float64) int
- func (z *ZSetValue) ZAddWithOptions(member string, score float64, nx, xx, gt, lt bool) (added, changed bool)
- func (z *ZSetValue) ZCard() int
- func (z *ZSetValue) ZCount(min, max float64, minExclusive, maxExclusive bool) int
- func (z *ZSetValue) ZIncrBy(member string, delta float64) float64
- func (z *ZSetValue) ZPopMax() (ZSetEntry, bool)
- func (z *ZSetValue) ZPopMaxN(n int) []ZSetEntry
- func (z *ZSetValue) ZPopMin() (ZSetEntry, bool)
- func (z *ZSetValue) ZPopMinN(n int) []ZSetEntry
- func (z *ZSetValue) ZRange(start, stop int, reverse bool) []ZSetEntry
- func (z *ZSetValue) ZRangeByScore(min, max float64, minExclusive, maxExclusive, reverse bool, offset, count int) []ZSetEntry
- func (z *ZSetValue) ZRank(member string) int
- func (z *ZSetValue) ZRem(members ...string) int
- func (z *ZSetValue) ZRevRank(member string) int
- func (z *ZSetValue) ZScore(member string) (float64, bool)
Constants ¶
const ( DefaultBufSize = 32768 // 32KB for write buffers - reduces write syscalls ReadBufSize = 65536 // 64KB read buffer - better pipelining support ResponseBufSize = 8192 // 8KB response buffer initial size )
Buffer sizes for optimal performance Larger buffers reduce syscall frequency at the cost of memory per connection
const ( RESPSimpleString = '+' RESPError = '-' RESPInteger = ':' RESPBulkString = '$' RESPArray = '*' )
RESP2 data type prefixes
const ( RESP3Null = '_' // Null: _\r\n RESP3Double = ',' // Double: ,1.23\r\n RESP3Boolean = '#' // Boolean: #t\r\n or #f\r\n RESP3BlobError = '!' // Blob Error: !<len>\r\n<data>\r\n RESP3VerbatimString = '=' // Verbatim: =<len>\r\n<encoding>:<data>\r\n RESP3BigNumber = '(' // Big Number: (<number>\r\n RESP3Map = '%' // Map: %<count>\r\n<key><value>... RESP3Set = '~' // Set: ~<count>\r\n<elements>... RESP3Push = '>' // Push: ><count>\r\n<elements>... RESP3Attribute = '|' // Attribute: |<count>\r\n<key><value>...<actual_reply> )
RESP3 data type prefixes
const (
// PubsubMsgChanSize is the buffer size for the pub/sub message channel
PubsubMsgChanSize = 1000
)
Variables ¶
var ( EffectsNodeID pb.NodeID HlcClock *crdt.HLC )
var ( ErrInvalidProtocol = errors.New("ERR invalid protocol") ErrInvalidBulkLength = errors.New("ERR invalid bulk length") ErrInvalidArrayCount = errors.New("ERR invalid array count") ErrLineTooLong = errors.New("ERR line too long") ErrUnexpectedEOF = errors.New("ERR unexpected end of input") )
Protocol errors
var ( // MinStreamID is the minimum possible stream ID MinStreamID = StreamID{Ms: 0, Seq: 0} // MaxStreamID is the maximum possible stream ID MaxStreamID = StreamID{Ms: ^uint64(0), Seq: ^uint64(0)} ErrInvalidStreamID = errors.New("invalid stream ID specified as stream command argument") ErrStreamIDTooSmall = errors.New("the ID specified in XADD is equal or smaller than the target stream top item") )
var ErrNoChannels = errors.New("register called with zero channels")
Functions ¶
func ClearPubSubBroker ¶
func ClearPubSubBroker()
ClearPubSubBroker fully clears the global pub/sub broker pointer.
func ClearScriptingEngine ¶
func ClearScriptingEngine()
ClearScriptingEngine fully clears the global scripting engine pointer.
func CommandCount ¶
func CommandCount() int
CommandCount returns the number of registered command names.
func CommandHasCategory ¶
func CommandHasCategory(cmd CommandType, cat CommandCategory) bool
CommandHasCategory checks if a command belongs to a category
func CommandNamesList ¶
func CommandNamesList(fn func(name string, cmd CommandType) bool)
CommandNamesList calls fn for each registered command name (uppercase) and its type. If fn returns false, iteration stops.
func EncodeElementID ¶
EncodeElementID encodes an (hlc, nodeID) pair into a 16-byte element ID.
func GetAllCategoryNames ¶
func GetAllCategoryNames() []string
GetAllCategoryNames returns all category names
func GetCategoryName ¶
func GetCategoryName(cat CommandCategory) string
GetCategoryName returns the name of a category
func GetDataBuf ¶
GetDataBuf gets a byte buffer of at least size n from the appropriate pool
func GetDefaultIDMPDuration ¶
func GetDefaultIDMPDuration() int64
func GetDefaultIDMPMaxSize ¶
func GetDefaultIDMPMaxSize() int64
func GetProtoMaxBulkLen ¶
func GetProtoMaxBulkLen() int64
GetProtoMaxBulkLen returns the current proto-max-bulk-len value.
func GetStreamNodeMaxEntries ¶
func GetStreamNodeMaxEntries() int64
GetStreamNodeMaxEntries returns the current stream-node-max-entries value.
func HLLRho ¶
HLLRho counts the number of leading zeros + 1 in the given bits This is used to determine the register value for HyperLogLog
func InitEffectsGlobals ¶
InitEffectsGlobals initializes the global HLC clock and node ID. Must be called at server startup before any commands are processed.
func KeysAfterStreams ¶
KeysAfterStreams extracts keys after the STREAMS keyword. Used by XREAD and XREADGROUP.
func KeysAll ¶
KeysAll extracts all args as keys. Used by DEL, DELEX, PFMERGE, SINTERSTORE, SUNIONSTORE, SDIFFSTORE.
func KeysAllButLast ¶
KeysAllButLast extracts keys from all args except the last (timeout). Used by BLPOP, BRPOP, BZPOPMIN, BZPOPMAX.
func KeysFirstTwo ¶
KeysFirstTwo extracts the first two args as keys (source, destination). Used by BLMOVE, BRPOPLPUSH.
func KeysMSetStyle ¶
KeysMSetStyle extracts keys from MSET-style commands where args are key-value pairs. Every other arg starting at index 0 is a key.
func KeysNumkeysAtOffset ¶
KeysNumkeysAtOffset extracts keys using a numkeys argument at a given offset. Used by BLMPOP (offset=1), BZMPOP (offset=1), EVAL/EVALSHA/FCALL (offset=1).
func KeysSortCmd ¶
KeysSortCmd extracts keys from SORT/SORT_RO (source key + optional STORE destination).
func ParseBlockingTimeout ¶
ParseBlockingTimeout parses a timeout string for blocking commands. Returns the timeout in seconds and an error message if invalid. Handles floats, integers, and hex values (0x...).
func ParseFloat64 ¶
ParseFloat64 parses a float64 from a byte slice
func ParseInt64 ¶
ParseInt64 parses an int64 from a byte slice without allocation, rejecting overflow.
func ParseUint64 ¶
ParseUint64 parses a uint64 from a byte slice without allocation
func PutDataBuf ¶
func PutDataBuf(buf []byte)
PutDataBuf returns a byte buffer to the appropriate pool. The caller yields ownership of buf's full capacity.
func ReconstructBytes ¶
func ReconstructBytes(snap *pb.ReducedEffect) ([]byte, bool)
ReconstructBytes attempts to convert a snapshot to raw bytes. Returns (bytes, true) if a reconstructor exists, (nil, false) otherwise.
func RegisterBytesReconstructor ¶
func RegisterBytesReconstructor(vt pb.ValueType, fn BytesReconstructor)
func RegisterModuleCommands ¶
func RegisterModuleCommands(entries ...ModuleEntry)
RegisterModuleCommands appends command entries from an external module. Called from init() functions in module packages (e.g., redis/zset).
func SetDefaultIDMPDuration ¶
func SetDefaultIDMPDuration(v int64)
func SetDefaultIDMPMaxSize ¶
func SetDefaultIDMPMaxSize(v int64)
func SetProtoMaxBulkLen ¶
func SetProtoMaxBulkLen(v int64)
SetProtoMaxBulkLen updates the proto-max-bulk-len value atomically.
func SetPubSubBroker ¶
func SetPubSubBroker(b PubSubBroker)
SetPubSubBroker sets the pub/sub broker instance.
func SetPubSubClusterRouter ¶ added in v0.3.0
func SetPubSubClusterRouter(r PubSubClusterRouter)
SetPubSubClusterRouter installs the cluster router. Called by the cluster wiring at startup; pass nil to clear.
func SetScriptingEngine ¶
func SetScriptingEngine(e ScriptingEngine)
SetScriptingEngine sets the scripting engine instance.
func SetServerStats ¶
func SetServerStats(s *Stats)
SetServerStats sets the server stats instance atomically.
func SetStreamNodeMaxEntries ¶
func SetStreamNodeMaxEntries(v int64)
SetStreamNodeMaxEntries updates the stream-node-max-entries value atomically.
Types ¶
type ACLSelector ¶
type ACLSelector struct {
Commands map[CommandType]bool
Categories map[CommandCategory]bool
AllCommands bool
KeyPatterns []KeyPattern
AllKeys bool
}
ACLSelector represents an additional permission set that can be applied conditionally
type ACLUser ¶
type ACLUser struct {
Name string
Enabled bool
PasswordHashes [][]byte // bcrypt hashes (includes salt)
NoPass bool // allow without password
// Command permissions
AllCommands bool // +@all
Categories map[CommandCategory]bool // +@read, -@write, etc.
Commands map[CommandType]bool // +get, -set, etc.
Subcommands map[CommandType]map[string]bool // +config|get, etc.
// Key permissions
AllKeys bool // ~*
KeyPatterns []KeyPattern // ~pattern, %R~pattern, %W~pattern
// Channel permissions (for pub/sub)
AllChannels bool // &*
ChannelPatterns []string // &pattern
// Selectors (additional permission sets, Redis 7.0+)
Selectors []*ACLSelector
}
ACLUser represents a Redis ACL user
func (*ACLUser) GetUserForDisplay ¶
GetUserForDisplay returns user info suitable for ACL GETUSER
type BytesReconstructor ¶
type BytesReconstructor func(snap *pb.ReducedEffect) []byte
BytesReconstructor converts a non-SCALAR snapshot into raw bytes. Registered per ValueType by modules (bitmap, hll) at init time.
type Command ¶
type Command struct {
Type CommandType
Args [][]byte // All arguments after the command name
RawName []byte // Original command name (preserved for unknown commands)
Transaction any
Context *effects.Context
Runtime *effects.Engine
// contains filtered or unexported fields
}
Command represents a parsed Redis command
func (*Command) Reset ¶
func (c *Command) Reset()
Reset clears the command for reuse, preserving slice capacity
func (*Command) SetSingleKey ¶ added in v1.3.0
SetSingleKey records arg as this command's one-key scratch value without copying the pooled parser bytes. The returned string and SingleKeySlice are valid only until the command is reset or returned to the pool. Code that retains a key beyond command execution must clone it first.
func (*Command) SingleKeySlice ¶ added in v1.3.0
SingleKeySlice returns allocation-free one-key scratch storage.
func (*Command) SingleKeyValue ¶ added in v1.3.0
SingleKeyValue returns the value installed by SetSingleKey.
type CommandCategory ¶
type CommandCategory int
CommandCategory represents a category of Redis commands
const ( CatRead CommandCategory = 1 << iota CatWrite CatSet CatSortedSet CatList CatHash CatString CatBitmap CatHyperLogLog CatGeo CatStream CatPubSub CatAdmin CatFast CatSlow CatBlocking CatDangerous CatConnection CatTransaction CatScripting CatKeyspace CatAll // Special: represents all commands )
func GetCategoryByName ¶
func GetCategoryByName(name string) (CommandCategory, bool)
GetCategoryByName returns a category by name
func GetCommandCategories ¶
func GetCommandCategories(cmd CommandType) []CommandCategory
GetCommandCategories returns the categories for a command
type CommandEntry ¶
type CommandEntry struct {
// Handler is the standard handler: validate → return keys and a runner closure.
// Used for both live execution and transaction queueing (when TxnPrepare is nil).
Handler HandlerFunc
// ConnHandler is for commands needing connection state (blocking, auth, pubsub, scripting).
// When set, live dispatch calls this instead of Handler.
ConnHandler ConnHandlerFunc
// TxnPrepare overrides Handler for transaction queueing.
// Used for blocking→non-blocking fallbacks and conn-needing commands in transactions.
// If nil, Handler is used for transaction queueing.
// Commands with neither Handler nor TxnPrepare cannot be queued (aborts transaction).
TxnPrepare TxnPrepareFunc
// Keys extracts data keys from a command for per-key ACL enforcement.
// Required for ConnHandler entries that touch data keys (blocking commands, SORT, scripting).
// Nil means the command does not touch data keys (auth, pubsub channels, server commands).
Keys KeyExtractFunc
Flags CommandFlags
}
CommandEntry holds everything needed to dispatch a command.
type CommandExecutor ¶
type CommandExecutor func(cmd *Command, w *Writer, conn *Connection)
CommandExecutor dispatches a command for execution (used by scripting for redis.call/pcall).
type CommandFlags ¶
type CommandFlags uint16
CommandFlags describes command behavior for dispatch.
const ( FlagWrite CommandFlags = 1 << iota // Mutates data FlagNoAuth // Allowed without authentication (AUTH, QUIT, HELLO) FlagNoQueue // Not queueable in MULTI (MULTI, EXEC, DISCARD, WATCH, UNWATCH, QUIT) FlagPubSub // Allowed in RESP2 pub/sub mode FlagTrackGet // Track GET latency FlagTrackSet // Track SET latency )
type CommandHandler ¶
type CommandHandler interface {
// ExecuteInto processes a command and writes the response to the writer
ExecuteInto(cmd *Command, w *Writer, conn *Connection)
// Close releases resources used by the handler
Close()
// SetStats sets the shared stats tracker
SetStats(stats *Stats)
// GetAdaptiveStats returns per-shard adaptive cache statistics
GetAdaptiveStats() []cache.AdaptiveStats
// GetCacheBytes returns current bytes used by cached items
GetCacheBytes() int64
// GetItemCount returns the number of keys resident in the index (the set
// eviction operates on), distinct from GetVertexCount
GetItemCount() int
// GetReleaseQueueDepth returns the number of cold-evicted keys whose
// deferred ref-release walk has not yet run; a persistently deep queue
// means reclaim is falling behind eviction
GetReleaseQueueDepth() int
// GetArenaBytes returns the critbit index's slot-array footprint (trie
// skeleton), distinct from GetCacheBytes (vertex pool effect bytes)
GetArenaBytes() int64
// GetVertexCount returns the number of effects resident in the vertex pool
GetVertexCount() int
// GetCacheEvictions returns keys evicted under memory pressure (evicted_keys)
GetCacheEvictions() uint64
// GetVerticesReclaimed returns vertices freed by reclaim (storage churn)
GetVerticesReclaimed() uint64
// RequiresAuth returns true if authentication is required
RequiresAuth() bool
// DebugEnabled returns true if debug logging is enabled
DebugEnabled() bool
}
CommandHandler defines the interface for Redis command handlers. Implementations can use different storage backends:
- Handler: in-memory CloxCache (fast, volatile)
- CRDTHandler: persistent CRDT data plane (durable, replicated) [future]
type CommandRunner ¶
type CommandRunner func()
CommandRunner is a closure that executes a pre-validated command.
type CommandStats ¶
type CommandStats struct {
Calls atomic.Uint64
Usec atomic.Uint64
RejectedCalls atomic.Uint64
FailedCalls atomic.Uint64
}
CommandStats tracks statistics for a single command
type CommandStatsSnapshot ¶
type CommandStatsSnapshot struct {
Calls uint64
Usec uint64
RejectedCalls uint64
FailedCalls uint64
}
CommandStatsSnapshot is a non-atomic snapshot of command stats
type CommandType ¶
type CommandType int
CommandType represents the type of Redis command
const ( CmdUnknown CommandType = iota CmdNoop // Connection commands CmdPing CmdEcho CmdAuth CmdSelect CmdQuit CmdHello // String commands CmdGet CmdSet CmdDel CmdDelEx CmdExists CmdExpire CmdExpireAt CmdPExpire CmdPExpireAt CmdTTL CmdPTTL CmdExpireTime CmdPExpireTime CmdPersist CmdRename CmdRenameNX CmdIncr CmdDecr CmdIncrBy CmdDecrBy CmdIncrByFloat CmdAppend CmdGetSet CmdGetDel CmdGetEx CmdMGet CmdMSet CmdMSetNX CmdMSetEX CmdSetNX CmdSetEX CmdPSetEX CmdStrLen CmdSetRange CmdGetRange CmdSubstr // Alias for GETRANGE (deprecated) CmdLcs // Longest Common Subsequence CmdDigest // XXH3 hash digest of string value CmdType // Bitmap commands CmdSetBit CmdGetBit CmdBitCount CmdBitPos CmdBitOp CmdBitField CmdBitFieldRO // List commands CmdLPush CmdLPushX CmdRPush CmdRPushX CmdLPop CmdRPop CmdBLPop CmdBRPop CmdLMPop CmdBLMPop CmdLMove CmdBLMove CmdRPopLPush CmdBRPopLPush CmdLLen CmdLRange CmdLIndex CmdLSet CmdLRem CmdLTrim CmdLInsert CmdLPos // Hash commands CmdHGet CmdHSet CmdHSetNX CmdHDel CmdHExists CmdHGetAll CmdHKeys CmdHVals CmdHLen CmdHMGet CmdHMSet CmdHIncrBy CmdHIncrByFloat CmdHStrLen CmdHRandField CmdHScan CmdHGetDel CmdHExpire CmdHPExpire CmdHExpireAt CmdHPExpireAt CmdHTTL CmdHPTTL CmdHExpireTime CmdHPExpireTime CmdHPersist CmdHSetEx CmdHGetEx // Set commands CmdSAdd CmdSCard CmdSIsMember CmdSMIsMember CmdSMembers CmdSPop CmdSRem CmdSRandMember CmdSInter CmdSInterStore CmdSInterCard CmdSUnion CmdSUnionStore CmdSDiff CmdSDiffStore CmdSMove // Sorted set commands CmdZAdd CmdZRem CmdZScore CmdZCard CmdZRank CmdZRevRank CmdZRange CmdZRevRange CmdZRangeByScore CmdZRevRangeByScore CmdZCount CmdZIncrBy CmdZPopMin CmdZPopMax CmdZMPop CmdZMScore CmdBZPopMin CmdBZPopMax CmdBZMPop CmdZRangeByLex CmdZRevRangeByLex CmdZLexCount CmdZRemRangeByScore CmdZRemRangeByRank CmdZRemRangeByLex CmdZUnionStore CmdZInterStore CmdZUnion CmdZInter CmdZInterCard CmdZDiff CmdZDiffStore CmdZRangeStore CmdZRandMember // Generic commands CmdCopy CmdMove CmdRandomKey CmdSort CmdSortRO // Server commands CmdInfo CmdDBSize CmdFlushDB CmdFlushAll CmdTime CmdKeys CmdScan CmdCommand CmdConfig CmdClient CmdDebug CmdMemory CmdShutdown // Transaction commands CmdMulti CmdExec CmdDiscard CmdWatch CmdUnwatch // Scripting commands CmdFunction CmdScript CmdEval CmdEvalSha CmdEvalRO CmdEvalShaRO CmdFcall CmdFcallRO // Replication commands (stubbed - replication not supported) CmdSync CmdPSync CmdReplConf CmdWait CmdWaitAof // Pub/Sub commands CmdSubscribe CmdUnsubscribe CmdPSubscribe CmdPUnsubscribe CmdPublish CmdPubSub // Database commands CmdSwapDB // Stream commands CmdXAdd CmdXLen CmdXRange CmdXRevRange CmdXRead CmdXGroup CmdXReadGroup CmdXAck CmdXPending CmdXTrim CmdXDel CmdXInfo CmdXSetId CmdXDelEx CmdXAckDel CmdXClaim CmdXAutoClaim CmdXIdmpRecord CmdXCfgSet // HyperLogLog commands CmdPFAdd CmdPFCount CmdPFMerge CmdPFSelfTest CmdPFDebug // Geo commands CmdGeoAdd CmdGeoDist CmdGeoHash CmdGeoPos CmdGeoRadius CmdGeoRadiusRO CmdGeoRadiusByMember CmdGeoRadiusByMemberRO CmdGeoSearch CmdGeoSearchStore // ACL commands CmdAcl // RedisJSON (JSON.*) commands CmdJSONSet CmdJSONGet CmdJSONMGet CmdJSONMSet CmdJSONMerge CmdJSONDel CmdJSONForget CmdJSONClear CmdJSONType CmdJSONNumIncrBy CmdJSONNumMultBy CmdJSONNumPowBy CmdJSONArrLen CmdJSONArrAppend CmdJSONArrInsert CmdJSONArrPop CmdJSONArrTrim CmdJSONArrIndex CmdJSONStrLen CmdJSONStrAppend CmdJSONObjKeys CmdJSONObjLen CmdJSONToggle CmdJSONResp CmdJSONDebug // CmdMax is a sentinel marking the end of the CommandType enum. // Must remain last. Used to size the registry array. CmdMax )
func GetCommandsInCategory ¶
func GetCommandsInCategory(cat CommandCategory) []CommandType
GetCommandsInCategory returns all commands in a category
func LookupCommandName ¶
func LookupCommandName(name string) (CommandType, bool)
LookupCommandName returns the CommandType for a given uppercase command name. Returns CmdUnknown and false if the name is not recognized.
func ParseCommandType ¶
func ParseCommandType(name []byte) CommandType
ParseCommandType converts a command name byte slice to CommandType
func (CommandType) StringPtr ¶ added in v1.2.0
func (c CommandType) StringPtr() *string
StringPtr returns a stable pointer to the command's display name.
type ConnHandlerFunc ¶
type ConnHandlerFunc func(cmd *Command, w *Writer, db *Database, conn *Connection)
ConnHandlerFunc is for commands that need connection state (blocking, auth, transactions, pubsub, scripting).
type Connection ¶
type Connection struct {
User *ACLUser // nil = unauthenticated
Username string // Cached username for logging
Protocol ProtocolVersion // RESP protocol version (default RESP2)
ClientName string // Client name set via CLIENT SETNAME or HELLO
ClientLibName string // Client library name (from HELLO)
ClientLibVer string // Client library version (from HELLO)
RemoteAddr string // Client remote address for logging
// Transaction state
InTransaction bool // True if inside MULTI block
TxnAborted bool // True if watched key was modified
QueuedCmds []QueuedCommand // Commands queued for EXEC
WatchedKeys []WatchedKey // Keys being watched with their versions
// Script state
InScript bool // True if executing commands from a Lua script (blocking commands become non-blocking)
// SI Transaction state (for CRDT handler with Snapshot Isolation)
SITransaction any // Active SI transaction (nil if not in SI mode)
BufferedResults [][]byte // Results captured during non-SI MULTI for EXEC
// Blocking command support
Ctx context.Context // Context for blocking operations (cancellation on disconnect)
Stats *Stats // Server stats (set at connection creation)
// Pub/Sub state
PubSubClient *PubSubClient // nil if not in pubsub mode
// Effects engine context for migrated modules
EffectsCtx *effects.Context
// ReadOnlyCtx serves read-only, non-transactional commands. It answers
// read-misses from the cluster key filters without subscribing (free
// misses). Lazily created alongside EffectsCtx.
ReadOnlyCtx *effects.Context
// contains filtered or unexported fields
}
Connection represents the state of a client connection
func (*Connection) Block ¶
func (c *Connection) Block(timeout float64) (context.Context, func())
Block sets up a blocking context with an optional timeout. Returns (ctx, cleanup) — caller MUST defer cleanup() immediately.
func (*Connection) ClearWatches ¶
func (c *Connection) ClearWatches()
ClearWatches clears watched keys without affecting transaction state
func (*Connection) InPubSubMode ¶
func (c *Connection) InPubSubMode() bool
InPubSubMode returns true if the connection is in pub/sub mode
func (*Connection) IsBlocked ¶
func (c *Connection) IsBlocked() bool
IsBlocked returns true if the connection is currently blocked.
func (*Connection) IsRESP3 ¶
func (c *Connection) IsRESP3() bool
IsRESP3 returns true if the connection is using RESP3
func (*Connection) ResetTransaction ¶
func (c *Connection) ResetTransaction()
ResetTransaction clears transaction state
func (*Connection) Unblock ¶
func (c *Connection) Unblock(withError bool) bool
Unblock cancels a blocked operation. If withError is true, the client receives an error message instead of nil.
func (*Connection) WasUnblockedWithError ¶
func (c *Connection) WasUnblockedWithError() bool
WasUnblockedWithError returns true if CLIENT UNBLOCK ERROR was used.
type Consumer ¶
type Consumer struct {
Name string
SeenTime int64 // last interaction time (Unix ms)
PendingCount int64 // entries owned by this consumer
ActiveTime int64 // last message fetched time
}
Consumer represents a consumer within a group
type ConsumerGroup ¶
type ConsumerGroup struct {
Name string
LastDeliveredID StreamID // for ">" - next delivery starts after this ID
EntriesRead int64 // for lag calculation (XINFO)
// Pending Entries List (PEL)
// Memory bounded by gap size, not total volume
Pending map[StreamID]*PendingEntry
// Consumers
Consumers map[string]*Consumer
// Per-consumer pending limit (0 = unlimited)
MaxPending int64
CreatedAt int64 // Unix milliseconds
}
ConsumerGroup represents a consumer group with TCP-style ack tracking
func NewConsumerGroup ¶
func NewConsumerGroup(name string, lastDeliveredID StreamID) *ConsumerGroup
NewConsumerGroup creates a new consumer group
func (*ConsumerGroup) GetOrCreateConsumer ¶
func (g *ConsumerGroup) GetOrCreateConsumer(name string) *Consumer
GetOrCreateConsumer gets or creates a consumer in the group
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database is the handle threaded through command handlers. Its only remaining job is reaching the blocking-command subscription registry; actual state lives in the effects engine.
func (*Database) Manager ¶
func (db *Database) Manager() *DatabaseManager
Manager returns the owning DatabaseManager.
type DatabaseManager ¶
type DatabaseManager struct {
// Subscriptions manages blocking command wake signals. Waiters register
// locally; wake signals arrive through the engine's OnKeyDataAdded /
// OnKeyDeleted / OnFlushAll callbacks, which fire for both local flushes
// and remote effect arrivals.
Subscriptions *SubscriptionManager[struct{}]
// contains filtered or unexported fields
}
DatabaseManager owns the Database and the blocking-command wake registry.
func NewDatabaseManager ¶ added in v1.2.0
func NewDatabaseManager() *DatabaseManager
NewDatabaseManager creates a new database manager.
func (*DatabaseManager) DB ¶ added in v1.2.0
func (dm *DatabaseManager) DB() *Database
DB returns the database.
type HLLValue ¶
type HLLValue struct {
Registers [16384]uint8 // Each register stores a 6-bit value (0-63)
}
HLLValue stores HyperLogLog data for probabilistic cardinality estimation Uses 16384 6-bit registers (2^14 registers) for ~0.81% standard error
func (*HLLValue) Add ¶
Add adds an element to the HyperLogLog Returns true if the internal registers were modified (cardinality might have increased)
type HandlerFunc ¶
type HandlerFunc func(cmd *Command, w *Writer, db *Database) (valid bool, keys []string, runner CommandRunner)
HandlerFunc is the standard handler signature: validate a command, return keys and a runner.
func WrapHandler ¶
func WrapHandler(fn func()) HandlerFunc
WrapHandler wraps a direct-execute function as a HandlerFunc (no keys, always valid).
type HashValue ¶
type HashValue struct {
Fields map[string][]byte
FieldsTTL map[string]int64 // field -> Unix millisecond timestamp, 0 = no expiration
}
HashValue stores hash field/value pairs
type KeyExtractFunc ¶
KeyExtractFunc extracts keys from a command for ACL checking. Used by ConnHandler entries that touch data keys but bypass the standard Handler path.
type KeyPattern ¶
type KeyPattern struct {
Pattern string
Type KeyPatternType
}
KeyPattern represents a key access pattern
type KeyPatternType ¶
type KeyPatternType int
KeyPatternType indicates what operations are permitted by a key pattern
const ( KeyPatternReadWrite KeyPatternType = iota // ~pattern (read + write) KeyPatternReadOnly // %R~pattern (read only) KeyPatternWriteOnly // %W~pattern (write only) )
type ListValue ¶
type ListValue struct {
// Sequence tracking for persistent storage (CRDT handler)
// HeadSeq is the sequence number of the first element (decrements on LPUSH)
// TailSeq is the sequence number of the last element (increments on RPUSH)
// For an empty list: HeadSeq=0, TailSeq=-1
HeadSeq int64
TailSeq int64
// contains filtered or unexported fields
}
ListValue stores list data using a doubly-linked list for O(1) push/pop
type ModuleEntry ¶
type ModuleEntry struct {
Cmd CommandType
Entry *CommandEntry
}
ModuleEntry pairs a CommandType with its CommandEntry for module registration.
func GetModuleRegistrations ¶
func GetModuleRegistrations() []ModuleEntry
GetModuleRegistrations returns all module-registered command entries.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser handles RESP2 protocol parsing
func NewParserWithReader ¶
NewParserWithReader creates a parser using an existing buffered reader
func (*Parser) ReadCommand ¶
ReadCommand reads and parses the next Redis command Returns a pooled Command - caller should call putCommand when done
func (*Parser) ReadCommandInto ¶
ReadCommandInto reads a command into the provided Command struct
type PendingEntry ¶
type PendingEntry struct {
ID StreamID
Consumer string // owning consumer name
DeliveryTime int64 // Unix ms of last delivery
DeliveryCount int64 // for retry logic / dead-letter detection
}
PendingEntry tracks delivery information for Redis compatibility
type ProtocolVersion ¶
type ProtocolVersion int
ProtocolVersion represents the RESP protocol version
const ( RESP2 ProtocolVersion = 2 RESP3 ProtocolVersion = 3 )
type PubSubBroker ¶
type PubSubBroker interface {
Subscribe(client *PubSubClient, channels ...string) []int
Unsubscribe(client *PubSubClient, channels ...string) ([]string, []int)
PSubscribe(client *PubSubClient, patterns ...string) []int
PUnsubscribe(client *PubSubClient, patterns ...string) ([]string, []int)
Publish(channel string, message []byte) int
Cleanup(client *PubSubClient)
SubscriptionCount(client *PubSubClient) int
Channels(pattern string) []string
NumSub(channels ...string) map[string]int
NumPat() int
}
PubSubBroker is the interface for the pub/sub subsystem. This allows the pubsub module to register commands via init() without circular imports.
func GetPubSubBroker ¶
func GetPubSubBroker() PubSubBroker
GetPubSubBroker returns the current pub/sub broker instance (may be nil).
type PubSubClient ¶
type PubSubClient struct {
// contains filtered or unexported fields
}
PubSubClient represents a client in pub/sub mode
func NewPubSubClient ¶
func NewPubSubClient(conn *Connection, protocol ProtocolVersion) *PubSubClient
NewPubSubClient creates a new pub/sub client
func (*PubSubClient) Close ¶
func (c *PubSubClient) Close()
Close closes the client's message channel
func (*PubSubClient) Done ¶
func (c *PubSubClient) Done() <-chan struct{}
Done returns a channel that is closed when the client is closed
func (*PubSubClient) IsBusy ¶
func (c *PubSubClient) IsBusy() bool
IsBusy returns true if the client is currently executing a command
func (*PubSubClient) MsgChan ¶
func (c *PubSubClient) MsgChan() <-chan *PubSubMessage
MsgChan returns the message channel for reading
func (*PubSubClient) Send ¶
func (c *PubSubClient) Send(msg *PubSubMessage) bool
Send sends a message to the client's message channel (non-blocking)
func (*PubSubClient) SetBusy ¶
func (c *PubSubClient) SetBusy(busy bool)
SetBusy marks the client as busy (during command execution)
type PubSubClusterRouter ¶ added in v0.3.0
type PubSubClusterRouter interface {
// AnnounceSub broadcasts an ephemeral SubscriptionEffect to every
// peer so they record this node's interest in the channel / pattern.
// Called on the 0→1 transition for a local subscription.
AnnounceSub(channel string, isPattern bool)
// AnnounceUnsub is the unsubscribe counterpart of AnnounceSub.
// Called on the last→0 transition for a local subscription.
AnnounceUnsub(channel string, isPattern bool)
// RouteMessage delivers a PUBLISH to remote peers whose recorded
// subscriptions match the channel (literal channel match or glob
// match against a recorded pattern). Returns the number of peers
// the message was sent to (one count per peer regardless of how
// many of their local clients are subscribed).
RouteMessage(channel string, payload []byte) int
// ClusterChannels returns the union of channels remote peers have
// announced interest in, optionally filtered by pattern.
ClusterChannels(pattern string) []string
// ClusterNumSub returns, per channel, the count of remote peers
// announcing interest in that exact channel name. Patterns are
// not counted (matching Redis NUMSUB semantics).
ClusterNumSub(channels []string) map[string]int
// ClusterPatterns returns every distinct pattern announced by a
// remote peer. Returned to the caller (not as a count) so the
// local broker can union with its own pattern set and dedupe.
ClusterPatterns() []string
}
PubSubClusterRouter is the cluster-side surface the local pub/sub broker uses to fan out subscriptions and messages to peer nodes. A nil router (standalone mode) means every call is a no-op.
func GetPubSubClusterRouter ¶ added in v0.3.0
func GetPubSubClusterRouter() PubSubClusterRouter
GetPubSubClusterRouter returns the installed router, or nil in standalone mode.
type PubSubMessage ¶
type PubSubMessage struct {
Type string // "message", "pmessage", "subscribe", "unsubscribe", "psubscribe", "punsubscribe"
Pattern string // for pmessage only
Channel string
Payload []byte
Count int // subscription count for sub/unsub responses
}
PubSubMessage represents a message to be delivered to subscribers
type QueuedCommand ¶
type QueuedCommand struct {
Type CommandType
Args [][]byte
Keys []string // Keys extracted during validation (for ACL checking at EXEC)
Runner CommandRunner // Pre-validated runner to execute at EXEC time
}
QueuedCommand stores a command queued during a transaction
type RedisValue ¶
type RedisValue struct {
Type ValueType
Data []byte // For strings
List *ListValue // For lists
Hash *HashValue // For hashes
Set *SetValue // For sets
ZSet *ZSetValue // For sorted sets
Stream *StreamValue // For streams
HLL *HLLValue // For HyperLogLog
CounterDeltaInt int64
CounterDeltaFloat float64
Exptime int64 // Unix millisecond timestamp, 0 = no expiration
CreatedAt int64 // Unix nanosecond timestamp when created
}
RedisValue represents a Redis value with expiration support
type RefMode ¶
type RefMode int
RefMode specifies how to handle consumer group references during trimming
type Registration ¶
type Registration[T any] struct { // contains filtered or unexported fields }
Registration represents a pending subscription
func (*Registration[T]) Cancel ¶
func (r *Registration[T]) Cancel()
Cancel marks the waiter as dead and removes it from all topics. Safe to call multiple times. Always call this (use defer).
func (*Registration[T]) CancelAndRenotify ¶
func (r *Registration[T]) CancelAndRenotify()
CancelAndRenotify cancels this registration and wakes the next waiter on each channel. Use this when the waiter could not consume the data (e.g. WRONGTYPE on destination) so the next blocked client gets a chance.
func (*Registration[T]) IsOldestWaiter ¶
func (r *Registration[T]) IsOldestWaiter(channel []byte) bool
IsOldestWaiter checks if this waiter is first in line for the given channel.
func (*Registration[T]) NotifyChan ¶
func (r *Registration[T]) NotifyChan() <-chan struct{}
NotifyChan returns the channel that receives wake signals. Use this when you need to select on multiple channels along with the wake signal.
func (*Registration[T]) Wait ¶
func (r *Registration[T]) Wait() ([]byte, error)
Wait blocks until a wake signal is received or ctx is canceled. Returns the channel that was signaled (nil if canceled) and error. Can be called multiple times - waiter remains subscribed until Cancel().
type Registry ¶
type Registry [CmdMax]*CommandEntry
Registry is the command dispatch table, indexed by CommandType for O(1) lookup. Stored as a field on Handler since entries reference handler methods.
func (*Registry) Lookup ¶
func (r *Registry) Lookup(cmd CommandType) *CommandEntry
Lookup returns the entry for a command type, or nil if unregistered.
func (*Registry) Register ¶
func (r *Registry) Register(cmd CommandType, entry *CommandEntry)
Register adds a command entry to the Registry.
type ScriptingEngine ¶
type ScriptingEngine interface {
HandleEval(cmd *Command, w *Writer, conn *Connection, db *Database, readOnly bool)
HandleScript(cmd *Command, w *Writer)
HandleFunction(cmd *Command, w *Writer)
HandleFcall(cmd *Command, w *Writer, conn *Connection, db *Database, readOnly bool)
IsScriptTimedOut() bool
Close()
}
ScriptingEngine is the interface for the scripting subsystem. This allows the scripting module to register commands via init() without circular imports.
func GetScriptingEngine ¶
func GetScriptingEngine() ScriptingEngine
GetScriptingEngine returns the current scripting engine instance (may be nil).
type Snapshot ¶
type Snapshot struct {
Time time.Time
Uptime time.Duration
CurrConnections int64
TotalConnections uint64
CmdGet uint64
CmdSet uint64
CmdDel uint64
CmdGetHits uint64
CmdGetMisses uint64
HitRate float64
GetLatencyP50 time.Duration
GetLatencyP99 time.Duration
SetLatencyP50 time.Duration
SetLatencyP99 time.Duration
CmdLatencyP50 time.Duration
CmdLatencyP99 time.Duration
BytesRead uint64
BytesWritten uint64
}
Snapshot represents a point-in-time snapshot of statistics
type Stats ¶
type Stats struct {
// Connection stats
CurrConnections atomic.Int64
TotalConnections atomic.Uint64
BlockedClients atomic.Int64
// Command counts
CmdGet atomic.Uint64
CmdSet atomic.Uint64
CmdDel atomic.Uint64
// Hit/miss tracking
CmdGetHits atomic.Uint64
CmdGetMisses atomic.Uint64
// Bytes read/written
BytesRead atomic.Uint64
BytesWritten atomic.Uint64
// Total error replies
TotalErrorReplies atomic.Uint64
// contains filtered or unexported fields
}
Stats tracks Redis server statistics
func GetServerStats ¶
func GetServerStats() *Stats
GetServerStats returns the current server stats instance (may be nil).
func (*Stats) ClientBlocked ¶
func (s *Stats) ClientBlocked()
ClientBlocked records a client entering a blocking state
func (*Stats) ClientUnblocked ¶
func (s *Stats) ClientUnblocked()
ClientUnblocked records a client leaving a blocking state
func (*Stats) CmdLatencyP50 ¶
CmdLatencyP50 returns the 50th percentile command latency (all commands)
func (*Stats) CmdLatencyP99 ¶
CmdLatencyP99 returns the 99th percentile command latency (all commands)
func (*Stats) ConnectionClosed ¶
func (s *Stats) ConnectionClosed()
ConnectionClosed records a closed connection
func (*Stats) ConnectionOpened ¶
func (s *Stats) ConnectionOpened()
ConnectionOpened records a new connection
func (*Stats) GetCommandStats ¶
func (s *Stats) GetCommandStats() map[string]CommandStatsSnapshot
GetCommandStats returns a copy of command statistics, keyed by command name, for commands that have been called at least once.
func (*Stats) GetErrorStats ¶
GetErrorStats returns a copy of error statistics
func (*Stats) GetLatencyP50 ¶
GetLatencyP50 returns the 50th percentile GET latency
func (*Stats) GetLatencyP99 ¶
GetLatencyP99 returns the 99th percentile GET latency
func (*Stats) RecordCommand ¶
func (s *Stats) RecordCommand(cmd CommandType, usec uint64, failed bool)
RecordCommand records a command execution
func (*Stats) RecordError ¶
RecordError records an error by its prefix (e.g., "NOGROUP", "ERR", "WRONGTYPE")
func (*Stats) RecordGetLatency ¶
RecordGetLatency records a GET command latency
func (*Stats) RecordSetLatency ¶
RecordSetLatency records a SET command latency
func (*Stats) SetLatencyP50 ¶
SetLatencyP50 returns the 50th percentile SET latency
func (*Stats) SetLatencyP99 ¶
SetLatencyP99 returns the 99th percentile SET latency
type StreamEntry ¶
type StreamEntry struct {
ID StreamID
Fields [][]byte // alternating [key1, val1, key2, val2, ...]
}
StreamEntry represents a single entry in a stream
type StreamID ¶
type StreamID struct {
Ms uint64 // Unix timestamp in milliseconds
Seq uint64 // Sequence number within the millisecond
}
StreamID represents a Redis stream entry ID (milliseconds-sequence)
func ParseStreamID ¶
ParseStreamID parses a stream ID from a string. Supported formats:
- "*" - auto-generate (only for XADD)
- "$" - last entry ID (for XREAD)
- ">" - only new entries (for XREADGROUP)
- "-" - minimum ID (for XRANGE)
- "+" - maximum ID (for XRANGE)
- "0" or "0-0" - minimum ID
- "1234567890123-0" - full ID
- "1234567890123" - partial ID (seq defaults to 0 for start, max for end)
- "(1234567890123-0" - exclusive (for XRANGE)
func ParseStreamIDForRange ¶
ParseStreamIDForRange parses an ID for XRANGE/XREVRANGE, handling partial IDs appropriately. For start IDs, partial IDs get seq=0. For end IDs, partial IDs get seq=MaxUint64.
func (StreamID) Compare ¶
Compare compares two stream IDs. Returns -1 if id < other, 0 if id == other, 1 if id > other.
type StreamValue ¶
type StreamValue struct {
// Entry storage - trie for ordered iteration, map for O(1) lookup
Index keytrie.KeyIndex // ordered index of ID strings (rebuilt on deserialize)
Entries map[string]*StreamEntry // ID string -> entry data (serialized)
// Stream metadata
LastID StreamID // highest ID ever generated (for auto-ID)
FirstID StreamID // first entry ID (updated on trim)
EntriesAdded int64 // total entries ever added (for XINFO)
MaxDeletedID StreamID // highest deleted ID (for XSETID)
// Consumer groups
Groups map[string]*ConsumerGroup
// contains filtered or unexported fields
}
StreamValue holds all entries and consumer groups for a stream
func (*StreamValue) ForEach ¶
func (s *StreamValue) ForEach(fn func(entry *StreamEntry) bool)
ForEach iterates over all entries in order, calling fn for each. If fn returns false, iteration stops.
func (*StreamValue) Trim ¶
func (s *StreamValue) Trim(opts TrimOptions) int64
Trim trims the stream according to the options and returns the count of trimmed entries
type SubscriptionManager ¶
type SubscriptionManager[T any] struct { // contains filtered or unexported fields }
SubscriptionManager manages subscriptions for blocking commands
func NewSubscriptionManager ¶
func NewSubscriptionManager[T any]() *SubscriptionManager[T]
NewSubscriptionManager creates a new subscription manager
func (*SubscriptionManager[T]) BlockingKeyCount ¶
func (m *SubscriptionManager[T]) BlockingKeyCount() int64
BlockingKeyCount returns the number of keys that have at least one active waiter.
func (*SubscriptionManager[T]) BlockingKeyCounts ¶
func (m *SubscriptionManager[T]) BlockingKeyCounts() (total int64, nokey int64)
BlockingKeyCounts returns the total number of blocking keys and the number of blocking keys where at least one client wants to be unblocked on key deletion (nokey).
func (*SubscriptionManager[T]) Enqueue ¶
func (m *SubscriptionManager[T]) Enqueue(channel []byte, _ T) bool
Enqueue is an alias for Notify (for compatibility)
func (*SubscriptionManager[T]) Notify ¶
func (m *SubscriptionManager[T]) Notify(channel []byte) bool
Notify wakes the oldest waiting subscriber for this channel. Waiters remain in the queue until they call Cancel(). Returns true if a waiter was signaled, false if no waiters.
func (*SubscriptionManager[T]) NotifyAll ¶
func (m *SubscriptionManager[T]) NotifyAll()
NotifyAll wakes ALL waiters across all topics. Used for operations like SWAPDB that may affect any blocked client.
func (*SubscriptionManager[T]) NotifyAllWaiters ¶
func (m *SubscriptionManager[T]) NotifyAllWaiters(channel []byte)
NotifyAllWaiters wakes ALL waiters for a specific channel. Used for operations like DEL, XGROUP DESTROY that invalidate the key/group.
func (*SubscriptionManager[T]) Register ¶
func (m *SubscriptionManager[T]) Register(ctx context.Context, channels ...[]byte) (*Registration[T], error)
Register creates a waiter for the given channels without blocking. Call Cancel() when done, or use defer reg.Cancel().
func (*SubscriptionManager[T]) RegisterWithNoKey ¶
func (m *SubscriptionManager[T]) RegisterWithNoKey(ctx context.Context, channels ...[]byte) (*Registration[T], error)
RegisterWithNoKey creates a waiter that should be unblocked when the key is deleted. This is used for XREADGROUP with ">" where the client wants to know if the stream is deleted.
func (*SubscriptionManager[T]) RegisterWithOptions ¶
func (m *SubscriptionManager[T]) RegisterWithOptions(ctx context.Context, unblockOnNoKey bool, channels ...[]byte) (*Registration[T], error)
RegisterWithOptions creates a waiter with configurable options. unblockOnNoKey: if true, the client wants to be unblocked when the key is deleted.
type Topic ¶
type Topic[T any] struct { // contains filtered or unexported fields }
Topic holds the waiting subscribers for a single key
type TrimOptions ¶
type TrimOptions struct {
MaxLen int64 // Trim to this length (only used if HasMaxLen is true)
MinID *StreamID // Trim entries with ID < MinID (nil = no limit)
Approx bool // Use approximate trimming (~)
Limit int64 // Max entries to trim per operation (0 = unlimited)
NodeSize int64 // Node size for approximate trimming (default 100)
RefMode RefMode // How to handle consumer group references
HasMaxLen bool // Whether MAXLEN was specified (allows MaxLen=0 to mean "trim to 0")
HasExplicitLimit bool // Whether LIMIT was explicitly specified (affects NodeSize rounding)
}
TrimOptions specifies trimming parameters
type TxnPrepareFunc ¶
type TxnPrepareFunc func(cmd *Command, w *Writer, db *Database, conn *Connection) (valid bool, keys []string, runner CommandRunner)
TxnPrepareFunc validates and prepares a command for transaction queueing. It has access to conn for commands that need connection state (scripting, pubsub, etc.).
type Waiter ¶
type Waiter[T any] struct { // contains filtered or unexported fields }
Waiter represents a subscriber waiting for a wake signal
type WatchedKey ¶
type WatchedKey struct {
DB int // Database index
Key string
Version int64 // CreatedAt timestamp when watched (0 if key didn't exist)
}
WatchedKey stores a key being watched with its version
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer handles RESP response formatting (supports RESP2 and RESP3)
func (*Writer) Protocol ¶
func (w *Writer) Protocol() ProtocolVersion
Protocol returns the current protocol version
func (*Writer) ResetErrorFlag ¶
func (w *Writer) ResetErrorFlag()
ResetErrorFlag resets the error tracking flag (call before each command)
func (*Writer) Scratch ¶ added in v1.2.0
Scratch returns the writer's reusable response-staging buffer, reset and ready for use. Retaining the buffer on the writer means the per-command stage-then-commit in ExecuteInto reuses one high-water allocation instead of growing a fresh buffer every command. If the writer is already staging into its scratch (a nested ExecuteInto on the same writer), a fresh buffer is returned so the outer stage's pending bytes aren't clobbered.
func (*Writer) SetProtocol ¶
func (w *Writer) SetProtocol(p ProtocolVersion)
SetProtocol sets the protocol version for subsequent writes
func (*Writer) WriteArray ¶
WriteArray writes a RESP array header (*<count>\r\n)
func (*Writer) WriteAttribute ¶
WriteAttribute writes RESP3 attribute metadata (|<count>\r\n) No RESP2 equivalent - silently ignored for RESP2
func (*Writer) WriteBigNumber ¶
WriteBigNumber writes a RESP3 big number ((<number>\r\n) Falls back to bulk string for RESP2
func (*Writer) WriteBlobError ¶
WriteBlobError writes a RESP3 blob error (!<len>\r\n<data>\r\n) Falls back to simple error for RESP2
func (*Writer) WriteBoolean ¶
WriteBoolean writes a RESP3 boolean (#t\r\n or #f\r\n) Falls back to integer (1 or 0) for RESP2
func (*Writer) WriteBulkString ¶
WriteBulkString writes a RESP bulk string ($5\r\nhello\r\n)
func (*Writer) WriteBulkStringStr ¶
WriteBulkStringStr writes a string as a RESP bulk string
func (*Writer) WriteDouble ¶
WriteDouble writes a RESP3 double (,<value>\r\n) Falls back to bulk string for RESP2
func (*Writer) WriteError ¶
WriteError writes a RESP error (-ERR message\r\n)
func (*Writer) WriteErrorf ¶
WriteErrorf writes a formatted RESP error
func (*Writer) WriteInteger ¶
WriteInteger writes a RESP integer (:1000\r\n)
func (*Writer) WriteMap ¶
WriteMap writes a RESP3 map header (%<count>\r\n) Falls back to array with 2*count elements for RESP2
func (*Writer) WriteNotInteger ¶
func (w *Writer) WriteNotInteger()
WriteNotInteger writes the "not an integer" error
func (*Writer) WriteNull ¶
func (w *Writer) WriteNull()
WriteNull writes RESP3 null (_\r\n) or RESP2 null bulk string ($-1\r\n)
func (*Writer) WriteNullArray ¶
func (w *Writer) WriteNullArray()
WriteNullArray writes a RESP null array (*-1\r\n) for RESP2, or null (_\r\n) for RESP3
func (*Writer) WriteNullBulkString ¶
func (w *Writer) WriteNullBulkString()
WriteNullBulkString writes a RESP null bulk string ($-1\r\n) for RESP2, or null (_\r\n) for RESP3
func (*Writer) WriteOutOfRange ¶
func (w *Writer) WriteOutOfRange()
WriteOutOfRange writes the "out of range" error
func (*Writer) WritePush ¶
WritePush writes a RESP3 push message header (><count>\r\n) Only valid for RESP3 - no RESP2 equivalent (used for pub/sub, invalidation)
func (*Writer) WriteQueued ¶
func (w *Writer) WriteQueued()
WriteQueued writes +QUEUED\r\n (for transactions)
func (*Writer) WriteScore ¶
WriteScore writes a Redis score value In RESP3: uses double type (,<value>\r\n) with proper inf/nan handling In RESP2: uses bulk string with formatted score
func (*Writer) WriteSet ¶
WriteSet writes a RESP3 set header (~<count>\r\n) Falls back to array for RESP2
func (*Writer) WriteSimpleString ¶
WriteSimpleString writes a RESP simple string (+OK\r\n)
func (*Writer) WriteSyntaxError ¶
func (w *Writer) WriteSyntaxError()
WriteSyntaxError writes a syntax error
func (*Writer) WriteUnknownCommand ¶
WriteUnknownCommand writes the unknown command error
func (*Writer) WriteVerbatimString ¶
WriteVerbatimString writes a RESP3 verbatim string (=<len>\r\n<enc>:<data>\r\n) Falls back to bulk string for RESP2
func (*Writer) WriteWrongNumArgs ¶
WriteWrongNumArgs writes the wrong number of arguments error
func (*Writer) WriteWrongNumArguments ¶
WriteWrongNumArguments writes the wrong number of arguments error
func (*Writer) WriteWrongType ¶
func (w *Writer) WriteWrongType()
WriteWrongType writes the WRONGTYPE error
func (*Writer) WroteError ¶
WroteError returns true if WriteError was called since last ResetErrorFlag
type ZSetValue ¶
ZSetValue stores sorted set members with scores
func (*ZSetValue) Sorted ¶
Sorted returns all members sorted by score (ascending), then by member name
func (*ZSetValue) SortedReverse ¶
SortedReverse returns all members sorted by score (descending), then by member name (descending)
func (*ZSetValue) ZAddWithOptions ¶
func (z *ZSetValue) ZAddWithOptions(member string, score float64, nx, xx, gt, lt bool) (added, changed bool)
ZAddWithOptions adds/updates members with ZADD options Returns (added, changed) counts based on options Options: nx (only add new), xx (only update), gt (update if greater), lt (update if less), ch (count changed)
func (*ZSetValue) ZRangeByScore ¶
func (z *ZSetValue) ZRangeByScore(min, max float64, minExclusive, maxExclusive, reverse bool, offset, count int) []ZSetEntry
ZRangeByScore returns members with scores in the given range
func (*ZSetValue) ZRank ¶
ZRank returns the rank (0-indexed) of a member in ascending order Returns -1 if member not found
func (*ZSetValue) ZRem ¶
ZRem removes members from the sorted set Returns the number of members removed