redis

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: AGPL-3.0 Imports: 52 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUserNotFound     = errors.New("ERR User not found")
	ErrUserDisabled     = errors.New("WRONGPASS invalid username-password pair or user is disabled")
	ErrWrongPassword    = errors.New("WRONGPASS invalid username-password pair or user is disabled")
	ErrNoPermission     = errors.New("NOPERM this user has no permissions to run the command")
	ErrNoKeyPermission  = errors.New("NOPERM this user has no permissions to access one of the keys")
	ErrNoChanPermission = errors.New("NOPERM this user has no permissions to access one of the channels")
)

ACL errors

View Source
var Version = "dev"

Version is set at build time

Functions

func EffectsUsage

func EffectsUsage() string

EffectsUsage returns the usage string for effects flags.

func GeneratePassword

func GeneratePassword(bits int) (string, error)

GeneratePassword generates a random password of the specified bit length

func GetActiveEngine

func GetActiveEngine() *effects.Engine

GetActiveEngine returns the running effects engine (nil before InitializeEffects).

func HashPassword

func HashPassword(password string) ([]byte, error)

HashPassword hashes a password using bcrypt

func InitializeCluster

func InitializeCluster(cfg *EffectsConfig, handler shared.CommandHandler) error

InitializeCluster wires redis-specific hooks onto the cluster runtime: subscription notifications (engine key events → pg wire clients) and command forwarding (PeerManager → Handler). Must be called after InitializeEffects and NewServer.

func InitializeEffects

func InitializeEffects(cfg *EffectsConfig) error

InitializeEffects stands up the effects engine (always) plus the cluster runtime (when a passphrase is set). Keeps a package-level handle so StopCluster can tear it down. The cluster port defaults to --port + 1000 so a stock redis launch gets 7379, matching the previous implicit convention.

func Main

func Main(args []string)

Main is the entry point for the Redis server CLI

func PrintEffectsConfig

func PrintEffectsConfig(cfg *EffectsConfig)

PrintEffectsConfig prints effects configuration to stdout.

func Run

func Run(args []string) error

Run starts the Redis server with the given arguments

func StopCluster

func StopCluster()

StopCluster gracefully shuts down the cluster runtime (beacon, peer manager, engine). Safe to call multiple times.

Types

type ACLLogEntry

type ACLLogEntry struct {
	Count         int     // Number of times this event occurred
	Reason        string  // "command", "key", "channel", "auth"
	Context       string  // "toplevel", "multi", "lua"
	Object        string  // The command or key that was denied
	Username      string  // The user that was denied
	AgeSeconds    float64 // Seconds since this entry was created
	ClientInfo    string  // Client connection info
	EntryID       int64   // Unique ID for deduplication
	TimestampUsec int64   // Microseconds since epoch
}

ACLLogEntry represents an entry in the ACL security log

type ACLManager

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

ACLManager manages Redis ACL users and permissions

func NewACLManager

func NewACLManager() *ACLManager

NewACLManager creates a new ACL manager

func (*ACLManager) Authenticate

func (m *ACLManager) Authenticate(username, password string) (*shared.ACLUser, error)

Authenticate validates username and password, returns the user if successful

func (*ACLManager) AuthenticateDefault

func (m *ACLManager) AuthenticateDefault() (*shared.ACLUser, bool)

AuthenticateDefault returns the default user if it has nopass, otherwise requires auth

func (*ACLManager) CheckChannel

func (m *ACLManager) CheckChannel(user *shared.ACLUser, channel string) error

CheckChannel checks if a user has permission to access a pub/sub channel

func (*ACLManager) CheckCommand

func (m *ACLManager) CheckCommand(user *shared.ACLUser, cmd shared.CommandType) error

CheckCommand checks if a user has permission to execute a command

func (*ACLManager) CheckKey

func (m *ACLManager) CheckKey(user *shared.ACLUser, key string, isWrite bool) error

CheckKey checks if a user has permission to access a key

func (*ACLManager) DeleteUser

func (m *ACLManager) DeleteUser(name string) bool

DeleteUser removes a user (thread-safe)

func (*ACLManager) GetLog

func (m *ACLManager) GetLog(count int) []ACLLogEntry

GetLog returns the ACL security log entries

func (*ACLManager) GetUser

func (m *ACLManager) GetUser(name string) *shared.ACLUser

GetUser returns a user by name (thread-safe)

func (*ACLManager) GetUsers

func (m *ACLManager) GetUsers() []string

GetUsers returns a copy of all user names (thread-safe)

func (*ACLManager) LoadFromFile

func (m *ACLManager) LoadFromFile(path string) error

LoadFromFile loads ACL rules from a file

func (*ACLManager) LogDenied

func (m *ACLManager) LogDenied(reason, context, object, username, clientInfo string)

LogDenied logs a permission denial

func (*ACLManager) RequiresAuth

func (m *ACLManager) RequiresAuth() bool

RequiresAuth returns true if authentication is required

func (*ACLManager) ResetLog

func (m *ACLManager) ResetLog()

ResetLog clears the ACL security log

func (*ACLManager) SaveToFile

func (m *ACLManager) SaveToFile(path string) error

SaveToFile saves ACL rules to a file

func (*ACLManager) SetUser

func (m *ACLManager) SetUser(user *shared.ACLUser)

SetUser creates or updates a user (thread-safe)

type ClientInfo

type ClientInfo struct {
	ID         int64
	Addr       string
	Name       string
	CreatedAt  time.Time
	LastActive time.Time
	DB         int
	Flags      string
	LastCmd    atomic.Pointer[string]
	Conn       *shared.Connection
}

ClientInfo holds per-client state for CLIENT LIST reporting

type ClientRegistry

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

ClientRegistry tracks all active client connections

func NewClientRegistry

func NewClientRegistry() *ClientRegistry

NewClientRegistry creates a new client registry

func (*ClientRegistry) Count

func (r *ClientRegistry) Count() int

Count returns the number of registered clients

func (*ClientRegistry) CountBlocked

func (r *ClientRegistry) CountBlocked() int

CountBlocked returns the number of blocked clients

func (*ClientRegistry) FormatClientList

func (r *ClientRegistry) FormatClientList() string

FormatClientList returns the CLIENT LIST output string

func (*ClientRegistry) GetByConn

func (r *ClientRegistry) GetByConn(conn *shared.Connection) *ClientInfo

GetByConn returns the ClientInfo for a connection

func (*ClientRegistry) GetByID

func (r *ClientRegistry) GetByID(id int64) *ClientInfo

GetByID returns the ClientInfo for a client ID

func (*ClientRegistry) Register

func (r *ClientRegistry) Register(conn *shared.Connection) *ClientInfo

Register adds a new client connection and returns its ClientInfo

func (*ClientRegistry) SetLastCmd

func (r *ClientRegistry) SetLastCmd(conn *shared.Connection, cmd string)

SetLastCmd updates the last command for a client

func (*ClientRegistry) Unblock

func (r *ClientRegistry) Unblock(clientID int64, withError bool) bool

Unblock unblocks a blocked client by ID. Returns true if the client was unblocked. If withError is true, the client receives an error message instead of nil.

func (*ClientRegistry) Unregister

func (r *ClientRegistry) Unregister(conn *shared.Connection)

Unregister removes a client connection

func (*ClientRegistry) UpdateDB

func (r *ClientRegistry) UpdateDB(conn *shared.Connection, db int)

UpdateDB updates the database for a client

type EffectsConfig

type EffectsConfig struct {
	Enabled            bool
	ClusterPassphrase  string
	JoinAddr           string
	ClusterPort        int
	AdvertiseAddr      string
	MemoryLimit        int64
	MemoryLimitPercent float64
	Port               int // main Redis port, used to compute default ClusterPort
}

EffectsConfig holds effects-specific configuration for the redis CLI. The cluster-shaped fields (passphrase, join, port, advertise) are forwarded to beacon.RuntimeConfig; anything redis-specific stays here.

func RegisterEffectsFlags

func RegisterEffectsFlags(fs *flag.FlagSet) *EffectsConfig

RegisterEffectsFlags adds effects-specific flags to the flag set.

type Handler

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

Handler processes Redis commands using CloxCache as the backend

func NewHandler

func NewHandler(cfg HandlerConfig) *Handler

NewHandler creates a new Redis command handler

func (*Handler) Close

func (h *Handler) Close()

NewHandlerWithDefaults creates a handler with default configuration Close releases resources used by the handler

func (*Handler) DebugEnabled

func (h *Handler) DebugEnabled() bool

DebugEnabled returns true if debug logging is enabled

func (*Handler) ExecuteInto

func (h *Handler) ExecuteInto(cmd *shared.Command, w *shared.Writer, conn *shared.Connection)

ExecuteInto processes a command and writes the response to the writer

func (*Handler) GetAdaptiveStats

func (h *Handler) GetAdaptiveStats() []cache.AdaptiveStats

GetAdaptiveStats returns per-shard adaptive cache statistics

func (*Handler) GetCacheBytes

func (h *Handler) GetCacheBytes() int64

GetCacheBytes returns current bytes used by cached items

func (*Handler) GetCacheEvictions

func (h *Handler) GetCacheEvictions() uint64

GetCacheEvictions returns total evictions from the cache

func (*Handler) GetDatabaseManager

func (h *Handler) GetDatabaseManager() *shared.DatabaseManager

GetDatabaseManager returns the database manager for cluster handler setup.

func (*Handler) GetItemCount

func (h *Handler) GetItemCount() int

GetItemCount returns current number of items in cache

func (*Handler) HandleForwardedTransaction

func (h *Handler) HandleForwardedTransaction(tx *pb.ForwardedTransaction) *pb.ForwardedResponse

HandleForwardedTransaction implements cluster.ForwardHandler. Executes forwarded commands locally and returns raw RESP bytes.

func (*Handler) NumDatabases

func (h *Handler) NumDatabases() int

NumDatabases returns the number of databases available

func (*Handler) RequiresAuth

func (h *Handler) RequiresAuth() bool

RequiresAuth returns true if authentication is required

func (*Handler) SetClientRegistry

func (h *Handler) SetClientRegistry(registry *ClientRegistry)

SetClientRegistry sets the client registry for CLIENT LIST support

func (*Handler) SetStats

func (h *Handler) SetStats(stats *shared.Stats)

SetStats sets the shared stats tracker

type HandlerConfig

type HandlerConfig struct {
	NumDatabases  int
	CapacityPerDB int
	MemoryLimit   int64
	Password      string // Deprecated: use ACLFile instead
	RequireAuth   bool   // Deprecated: use ACLFile instead
	ACLFile       string // Path to ACL file for user authentication
	DebugLogging  bool
	// Engine, if set, enables effects-based data access for migrated modules
	Engine *effects.Engine
}

HandlerConfig contains configuration for the handler

func DefaultHandlerConfig

func DefaultHandlerConfig() HandlerConfig

DefaultHandlerConfig returns a default configuration

type Logger

type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

Logger wraps slog.Logger and provides debug mode control

func NewLogger

func NewLogger(debug bool) *Logger

NewLogger creates a new logger with the specified debug mode

func (*Logger) IsDebug

func (l *Logger) IsDebug() bool

IsDebug returns true if debug mode is enabled

func (*Logger) LogCommand

func (l *Logger) LogCommand(cmd *shared.Command, db int, clientAddr string)

LogCommand logs a command execution at debug level

func (*Logger) LogResponse

func (l *Logger) LogResponse(clientAddr string, buf *bytes.Buffer)

LogResponse logs response data at debug level

func (*Logger) LogUnknownCommand

func (l *Logger) LogUnknownCommand(cmd *shared.Command, clientAddr string)

LogUnknownCommand logs an unknown command at info level (always visible)

type MetricsAdapter

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

MetricsAdapter adapts Redis Stats and Handler to the metrics.StatsProvider interface.

func NewMetricsAdapter

func NewMetricsAdapter(stats *shared.Stats, handler shared.CommandHandler, memoryLimit int64) *MetricsAdapter

NewMetricsAdapter creates a new metrics adapter for the Redis server.

func (*MetricsAdapter) AdaptiveKThresholds

func (a *MetricsAdapter) AdaptiveKThresholds() map[int]int32

AdaptiveKThresholds returns the adaptive K threshold for each shard.

func (*MetricsAdapter) BlockedClients

func (a *MetricsAdapter) BlockedClients() int64

BlockedClients returns the number of clients blocked on blocking commands.

func (*MetricsAdapter) BytesRead

func (a *MetricsAdapter) BytesRead() uint64

BytesRead returns the total bytes read from network.

func (*MetricsAdapter) BytesWritten

func (a *MetricsAdapter) BytesWritten() uint64

BytesWritten returns the total bytes written to network.

func (*MetricsAdapter) CacheHits

func (a *MetricsAdapter) CacheHits() uint64

CacheHits returns the total number of cache hits.

func (*MetricsAdapter) CacheMisses

func (a *MetricsAdapter) CacheMisses() uint64

CacheMisses returns the total number of cache misses.

func (*MetricsAdapter) CasHits

func (a *MetricsAdapter) CasHits() uint64

CasHits returns 0 (not applicable for Redis).

func (*MetricsAdapter) CasMisses

func (a *MetricsAdapter) CasMisses() uint64

CasMisses returns 0 (not applicable for Redis).

func (*MetricsAdapter) CmdLatencyP50

func (a *MetricsAdapter) CmdLatencyP50() float64

CmdLatencyP50 returns the 50th percentile command latency in seconds (all commands).

func (*MetricsAdapter) CmdLatencyP99

func (a *MetricsAdapter) CmdLatencyP99() float64

CmdLatencyP99 returns the 99th percentile command latency in seconds (all commands).

func (*MetricsAdapter) CommandCounts

func (a *MetricsAdapter) CommandCounts() map[string]uint64

CommandCounts returns command execution counts by command name.

func (*MetricsAdapter) CommandErrors

func (a *MetricsAdapter) CommandErrors() map[string]uint64

CommandErrors returns command error counts by command name.

func (*MetricsAdapter) CurrentConnections

func (a *MetricsAdapter) CurrentConnections() int64

CurrentConnections returns the current number of client connections.

func (*MetricsAdapter) DeleteHits

func (a *MetricsAdapter) DeleteHits() uint64

DeleteHits returns 0 (not applicable for Redis).

func (*MetricsAdapter) DeleteMisses

func (a *MetricsAdapter) DeleteMisses() uint64

DeleteMisses returns 0 (not applicable for Redis).

func (*MetricsAdapter) Evictions

func (a *MetricsAdapter) Evictions() uint64

Evictions returns the total number of cache evictions.

func (*MetricsAdapter) GetLatencyP50

func (a *MetricsAdapter) GetLatencyP50() float64

GetLatencyP50 returns the 50th percentile GET latency in seconds.

func (*MetricsAdapter) GetLatencyP99

func (a *MetricsAdapter) GetLatencyP99() float64

GetLatencyP99 returns the 99th percentile GET latency in seconds.

func (*MetricsAdapter) HitRate

func (a *MetricsAdapter) HitRate() float64

HitRate returns the cache hit rate (0-1).

func (*MetricsAdapter) ItemCount

func (a *MetricsAdapter) ItemCount() int

ItemCount returns the current number of items in the cache.

func (*MetricsAdapter) MaxMemoryBytes

func (a *MetricsAdapter) MaxMemoryBytes() int64

MaxMemoryBytes returns the maximum configured memory limit.

func (*MetricsAdapter) MemoryBytes

func (a *MetricsAdapter) MemoryBytes() int64

MemoryBytes returns the current memory used by cached items.

func (*MetricsAdapter) SetLatencyP50

func (a *MetricsAdapter) SetLatencyP50() float64

SetLatencyP50 returns the 50th percentile SET latency in seconds.

func (*MetricsAdapter) SetLatencyP99

func (a *MetricsAdapter) SetLatencyP99() float64

SetLatencyP99 returns the 99th percentile SET latency in seconds.

func (*MetricsAdapter) Subsystem

func (a *MetricsAdapter) Subsystem() string

Subsystem returns "redis" for the Redis adapter.

func (*MetricsAdapter) TotalConnections

func (a *MetricsAdapter) TotalConnections() uint64

TotalConnections returns the total number of connections since start.

func (*MetricsAdapter) UptimeSeconds

func (a *MetricsAdapter) UptimeSeconds() float64

UptimeSeconds returns the server uptime in seconds.

type Server

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

Server is a Redis-compatible TCP server

func NewServer

func NewServer(config ServerConfig) (*Server, error)

NewServer creates a new Redis server Returns an error if persistent storage is configured but fails to initialize.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr returns the server's listening address

func (*Server) Handler

func (s *Server) Handler() shared.CommandHandler

Handler returns the command handler

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the server and blocks until it's stopped

func (*Server) Start

func (s *Server) Start() error

Start begins listening for connections

func (*Server) Stats

func (s *Server) Stats() *shared.Stats

Stats returns the server statistics

func (*Server) Stop

func (s *Server) Stop() error

Stop gracefully stops the server

type ServerConfig

type ServerConfig struct {
	// Address to listen on (e.g., ":6379")
	Address string

	// UnixSocket is the path to a Unix domain socket
	UnixSocket string

	// UnixSocketMode is the file mode for the Unix socket
	UnixSocketMode os.FileMode

	// NumDatabases is the number of databases (default 16)
	NumDatabases int

	// CapacityPerDB is the cache capacity per database
	CapacityPerDB int

	// MemoryLimit is the maximum memory in bytes (0 = unlimited)
	MemoryLimit int64

	// Password for AUTH command (empty = no auth required)
	// Deprecated: use ACLFile instead
	Password string

	// ACLFile is the path to the ACL file for user authentication
	ACLFile string

	// ReadTimeout is the timeout for reading commands
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for writing responses
	WriteTimeout time.Duration

	// MaxConnections limits concurrent connections (0 = unlimited)
	MaxConnections int

	// DebugLogging enables debug-level command logging
	DebugLogging bool

	// TCPKeepAlive enables TCP keepalive
	TCPKeepAlive time.Duration

	// ReadBufferSize is the size of the read buffer per connection
	ReadBufferSize int

	// WriteBufferSize is the size of the write buffer per connection
	WriteBufferSize int

	// NumAcceptors is the number of parallel accept loops (0 = auto, uses NumCPU on supported platforms)
	// On Linux/macOS/BSD, uses SO_REUSEPORT to allow multiple listeners on the same port.
	// On Windows, this is ignored (single acceptor only).
	NumAcceptors int

	// TLSCertFile is the path to the TLS certificate file (PEM format)
	TLSCertFile string

	// TLSKeyFile is the path to the TLS private key file (PEM format)
	TLSKeyFile string

	// TLSCAFile is the path to the CA certificate for client verification (mTLS)
	TLSCAFile string

	// TLSMinVersion is the minimum TLS version (e.g., "1.2", "1.3")
	TLSMinVersion string
}

ServerConfig holds configuration for the Redis server

func DefaultServerConfig

func DefaultServerConfig() ServerConfig

DefaultServerConfig returns a default server configuration

func (*ServerConfig) TLSEnabled

func (c *ServerConfig) TLSEnabled() bool

TLSEnabled returns true if TLS is configured

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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