pebbis

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 28 Imported by: ? 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.

README

Pebbis

An embedded, Redis-compatible data store written in Go, with Pebble as its storage engine.

It can be used two ways:

  • As a library — import it, open a Store, and talk RESP semantics without any socket. Persistence, expiration, eviction and transactions all work in-process.
  • As a server — cmd/pebbisd speaks RESP2 over TCP, so any Redis client (redis-cli, go-redis, …) can connect.

Design highlights

  • Pebble-backed durability. Every key lives in an LSM tree; restarts replay nothing but Pebble's own WAL. Checkpoint provides consistent hard-link snapshots.
  • Skiplist-free in-memory index. Aggregates (hash/list/set/zset/stream) are reconstructed lazily from the engine, bounded by cache size — memory stays proportional to the working set, not the dataset.
  • Eviction + TTL. maxmemory with noeviction / allkeys-lru / volatile-lru / allkeys-lfu / volatile-lfu / allkeys-random / volatile-random / volatile-ttl, plus lazy + active key expiration. Above a 16 MiB budget the limit is enforced against the index plus Pebble's block cache and memtables (below it, only the index is counted), so the budget tracks the process footprint instead of just the key index.
  • Atomic transactions. MULTI/EXEC takes the exclusive per-key locks of every key its queue touches and holds them for the whole execution, so another client cannot interleave a command between two queued commands; WATCH versions are verified under the same lock. The queued writes are buffered in one indexed Pebble batch and applied with a single atomic commit, so a crash either applies the whole transaction or none of it, and the queued reads see the buffered writes (counters, sparse aggregates and range scans included). Commands no per-key lock covers (FLUSHALL, SWAPDB, CONFIG SET, …) are still not isolated from concurrent clients, and a writing transaction holds the write gate while it runs, so single writes wait for it — the same visibility a single-threaded Redis gives.
  • Reliable streams. Consumer groups with PEL: deliveries are recorded before they are sent, and acked entries are removed — pending entries survive restarts.
  • Safe defaults. With no requirepass configured, protected mode refuses connections from non-loopback addresses (as Redis does), so starting on :6379 does not expose the store to the network by accident.

Quick start

Embedded (library API):

cfg := pebbis.DefaultOptions()
cfg.Dir = "/path/to/data"
store, err := pebbis.Open(cfg)
if err != nil {
    return err
}
defer store.Close()

Embedded with a RESP endpoint — existing Redis clients switch by changing only the connection string, and the store still lives inside your process:

emb, err := pebbis.OpenEmbedded(pebbis.EmbedOptions{Dir: "/path/to/data"})
if err != nil {
    return err
}
defer emb.Close()
// Clients connect to emb.Addr(), a unix socket with mode 0600.
// Hot paths in this process can also call emb.Store() and skip the protocol.

OpenEmbedded spawns no child process: the listener is a goroutine over the same Store, so a host restart restarts the store (Pebble replays its WAL) and there is no orphan process to reap. The data directory is owned exclusively by one process. Because clients still speak RESP, a command pays for parsing and a socket round trip — embedded mode saves a separate deployment, not the protocol.

Server:

go build -o bin/pebbisd ./cmd/pebbisd
./bin/pebbisd -addr :6379 -dir ./data

Configuration (see config/): maxmemory, maxmemory-policy, slowlog-log-slower-than, slowlog-max-len, lfu-decay-time, protected-mode.

Protected mode is on by default: until -requirepass is set (or -protected-mode=false), connections from anything but loopback are refused.

Supported commands (188)

  • Connection / server: PING, ECHO, SELECT, QUIT, HELLO, AUTH, COMMAND, CLIENT (GET/GETNAME/ID/INFO/LIST/RESET/SETNAME), CONFIG (subset), INFO, DEBUG, TIME, SORT, SORT_RO, DBSIZE, FLUSHDB, FLUSHALL, SAVE, BGSAVE, LASTSAVE, SHUTDOWN, SLOWLOG, MEMORY, OBJECT (subset)
  • Strings: GET, SET, SETNX, SETXX, SETEX, PSETEX, GETSET, GETDEL, GETEX, DELEX, MSET, MSETNX, MGET, APPEND, STRLEN, INCR, DECR, INCRBY, DECRBY, INCRBYFLOAT, GETRANGE, SETRANGE, SUBSTR, LCS, SETBIT, GETBIT, BITCOUNT, BITPOS, BITOP
  • Keys (generic): DEL, UNLINK, EXISTS, TYPE, TTL, PTTL, EXPIRE, PEXPIRE, EXPIREAT, PEXPIREAT, PERSIST, EXPIRETIME, PEXPIRETIME, KEYS, SCAN, RANDOMKEY, RENAME, RENAMENX, COPY, MOVE, SWAPDB, TOUCH
  • Hashes: HSET, HMSET, HSETNX, HGET, HMGET, HGETALL, HDEL, HEXISTS, HKEYS, HVALS, HLEN, HSTRLEN, HINCRBY, HINCRBYFLOAT, HSCAN, HRANDFIELD
  • Lists: LPUSH, LPUSHX, RPUSH, RPUSHX, LPOP, RPOP, LRANGE, LINDEX, LLEN, LREM, LSET, LTRIM, LINSERT, LMOVE, LPOS, LMPOP, RPOPLPUSH, BLPOP, BRPOP, BRPOPLPUSH, BLMOVE, BLMPOP
  • Sets: SADD, SREM, SMEMBERS, SISMEMBER, SMISMEMBER, SCARD, SMOVE, SPOP, SRANDMEMBER, SINTER, SINTERSTORE, SINTERCARD, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SSCAN
  • Sorted sets: ZADD, ZCARD, ZCOUNT, ZINCRBY, ZSCORE, ZMSCORE, ZRANK, ZREVRANK, ZREVRANGE, ZRANGE (incl. REV/BYSCORE/BYLEX), ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZRANGEBYLEX, ZREVRANGEBYLEX, ZRANGESTORE, ZLEXCOUNT, ZREM, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREMRANGEBYLEX, ZPOPMIN, ZPOPMAX, ZMPOP, BZPOPMIN, BZPOPMAX, BZMPOP, ZRANDMEMBER, ZUNION, ZUNIONSTORE, ZINTER, ZINTERSTORE, ZDIFF, ZDIFFSTORE
  • Streams: XADD, XLEN, XRANGE, XREVRANGE, XREAD, XDEL, XTRIM, XGROUP (CREATE/DESTROY/CREATECONSUMER/DELCONSUMER), XREADGROUP, XACK, XPENDING, XCLAIM, XINFO (GROUPS/CONSUMERS/STREAM)
  • Pub/Sub: SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBLISH, PUBSUB
  • Transactions: MULTI, EXEC, DISCARD, WATCH, UNWATCH

Unsupported commands

This is a cache/store, not a full Redis clone. Compared with Redis 7.x, the following are not implemented:

  • Clustering & replication: CLUSTER *, REPLICAOF, SLAVEOF, SYNC, PSYNC, WAIT, WAITAOF, FAILOVER, READONLY, READWRITE
  • ACL: the entire ACL * family (authentication via AUTH <password> works with a configured default password)
  • Bitmaps: BITFIELD, BITFIELD_RO (the SETBIT / GETBIT / BITCOUNT / BITPOS / BITOP primitives are supported)
  • HyperLogLog: PFADD, PFCOUNT, PFMERGE
  • Geospatial: GEOADD and the whole GEO* family
  • Scripting / functions: EVAL, EVALSHA, EVAL_RO, EVALSHA_RO, FCALL, FCALL_RO, SCRIPT *, FUNCTION *
  • Server internals: MONITOR, LATENCY *, LOLWUT, COMMAND DOCS/INFO (only the full COMMAND dump is served)
  • Data-command gaps: DUMP, RESTORE, MIGRATE
  • Hash field TTL (Redis 7.4): HGETEX, HGETDEL, HEXPIRE, HPEXPIRE, HEXPIREAT, HPEXPIREAT, HTTL, HPTTL, HPERSIST, HFIELDS
  • Streams: XAUTOCLAIM, XSETID
  • Keyspace notifications: expired-key / keyevent channels are not published

Anything not listed here will return an ERR unknown command error, same as Redis.

Production caveats

  • Single node. No replication, cluster mode, failover, or DUMP/RESTORE/MIGRATE. The backup story is Checkpoint (hard-link snapshot) plus whatever copies it off the machine.
  • Durability is the configured one. -appendfsync group (default) batches WAL fsyncs over WALMinSyncInterval (200 µs), so a power failure can lose the last acknowledged writes; use -appendfsync always when that matters.
  • No ACL, no scripting, no keyspace notifications (see the unsupported list above). Authentication is a single requirepass password compared in plaintext — use TLS (ServerOptions.TLSConfig) when the network is not trusted.
  • Treat it as an embedded store or a single-node cache backed by Pebble, not as the only copy of data you cannot rebuild.

Requirements

Go 1.26 or newer. go.mod declares the language version only — no toolchain is pinned, so any newer Go release works without editing the module (the go 1.26.0 line is Go's canonical form, not a pinned patch release). Tests that drive the server through go-redis pull github.com/redis/go-redis/v9 from the module proxy. make race needs a working C toolchain (CC), since the race detector uses cgo.

Development

make build   # build cmd/pebbisd into bin/
make test    # go test across all packages
make race    # go test -race across all packages (the standard gate)
make drill   # SIGKILL + restart drill: every acknowledged write must survive
make bench   # run benchmarks (XADD, sparse aggregates, ...)
make cover   # coverage profile + HTML report

CI (.github/workflows/ci.yml) runs build, vet, test, the race detector and the restart drill on every push and pull request.

make drill starts a real pebbisd with -appendfsync always, writes a mixed workload (strings including a value too large to be inline, a sparse hash, a list, a sorted set, a stream with un-acked consumer-group entries, counters, TTLs and a transaction), SIGKILLs the process without any graceful shutdown, restarts it on the same directory and verifies everything came back.

Layout: storage/ (Pebble engine wrapper), memory/ (aggregate encodings), stream.go (streams + consumer groups), cmd_*.go (one file per data type), tests/compat/ (black-box RESP compatibility tests).

Documentation

Overview

Package Pebbis is an embeddable, Redis-protocol-compatible store with Pebble-backed persistence and bounded memory.

It can be used as a Go library with zero network overhead:

s, err := pebbis.Open(pebbis.DefaultOptions())
defer s.Close()
_ = s.Set(ctx, 0, "k", []byte("v"))

or as a standalone RESP server:

srv := pebbis.NewServer(s, pebbis.ServerOptions{Addr: ":6379"})
log.Fatal(srv.ListenAndServe())

Index

Constants

View Source
const (
	SegStreamEntry byte = 0x0B
	SegStreamGroup byte = 0x0C
	SegStreamPEL   byte = 0x0D
)

Segment tags for stream structures.

View Source
const Version = "0.1.0"

Version is reported through INFO.

Variables

View Source
var (
	// ErrWrongType is returned when a command meets a key of another type.
	ErrWrongType = errors.New("WRONGTYPE Operation against a key holding the wrong kind of value")
	// ErrSyntax is returned for malformed commands.
	ErrSyntax = errors.New("ERR syntax error")
	// ErrNotInteger is returned when a numeric argument does not parse.
	ErrNotInteger = errors.New("ERR value is not an integer or out of range")
	// ErrNotFloat is the float counterpart of ErrNotInteger.
	ErrNotFloat = errors.New("ERR value is not a valid float")
	// ErrOverflow is returned when INCR/DECR would leave the 64-bit range.
	ErrOverflow = errors.New("ERR increment or decrement would overflow")
	// ErrNoSuchKey is returned by commands that require an existing key.
	ErrNoSuchKey = errors.New("ERR no such key")
	// ErrDBIndex is returned when SELECT targets a database out of range.
	ErrDBIndex = errors.New("ERR DB index is out of range")
	// ErrInvalidExpire is returned for out-of-range TTLs.
	ErrInvalidExpire = errors.New("ERR invalid expire time in 'set' command")
	// ErrUnknownCmd is returned for unrecognised commands.
	ErrUnknownCmd = errors.New("ERR unknown command")
	// ErrQuit is a sentinel that ends the connection.
	ErrQuit = errors.New("quit")
	// ErrBusyKey is returned when a write is rejected by NX/XX semantics.
	ErrBusyKey = errors.New("BUSYKEY Target key name already exists")
)

Protocol-level errors. The wording matches Redis so that existing clients and their error handlers behave identically.

View Source
var ErrClosed = errors.New("Pebbis: store is closed")

ErrClosed is returned once the store has been closed.

Functions

func CommandCount

func CommandCount() int

CommandCount returns the number of supported commands.

func CommandNames

func CommandNames() []string

CommandNames returns the sorted list of supported command names.

func IsQuit

func IsQuit(err error) bool

IsQuit reports whether err asks for the connection to be closed.

func OOM

func OOM(cmd string) error

OOM is returned when no eviction can free memory.

func ParseByteSize

func ParseByteSize(s string) (uint64, error)

ParseByteSize accepts a plain byte count or a 1k/1mb/1gb suffix. Exported so the command-line entry point can accept the same syntax as CONFIG SET maxmemory.

func UnknownCommand

func UnknownCommand(name string) error

UnknownCommand builds the error for an unrecognised command name.

func WrongArgs

func WrongArgs(cmd string) error

WrongArgs builds the standard arity error for a command.

Types

type Ctx

type Ctx struct {
	// Store is the instance being served.
	Store *Store
	// DB is the logical database selected by this connection.
	DB uint16
	// Name is the upper-cased command name, used in error messages.
	Name string
	// MaxBulkLen caps a single argument, guarding against a huge SET
	// exhausting memory before anything is written.
	MaxBulkLen int
	// Args is the full command line, kept for the slow log.
	Args []string
	// contains filtered or unexported fields
}

Ctx is the per-command execution context.

func (*Ctx) Client

func (c *Ctx) Client() *connState

Client returns the per-connection state, or nil when the command did not come from a network connection.

func (*Ctx) Server

func (c *Ctx) Server() *Server

Server returns the serving Server, or nil when not served over the network.

type EmbedOptions

type EmbedOptions struct {
	// Dir is the data directory. Required: it is what makes the embedded store
	// durable across restarts. It must be owned by this process alone; Pebble
	// takes an exclusive lock on it.
	Dir string
	// Socket overrides the unix socket path. Default: <temp>/pebbis-<hash>.sock,
	// where the hash is derived from the data directory, so the path is stable
	// per directory and stays well under the platform's sockaddr_un limit. An
	// explicit path must fit that limit too (~100 bytes).
	Socket string
	// Network selects the listener kind: "" or "unix" (the default) serves a
	// unix socket, "tcp" serves a loopback TCP address. TCP exists for hosts
	// where a unix socket is awkward: Windows cannot chmod a socket file and
	// has a much shorter sockaddr_un budget, so an embedded store there has to
	// listen on TCP. Socket is ignored when Network is "tcp".
	Network string
	// Addr overrides the listen address for Network "tcp". Default
	// "127.0.0.1:0", i.e. an ephemeral loopback port; read the assigned
	// address back from Embedded.Addr.
	Addr string
	// Config overrides the store configuration. Default: DefaultOptions() with
	// Dir set. It is copied, so the caller's value is not mutated.
	Config *config.Config
	// MaxClients caps concurrent client connections. Zero means unlimited.
	MaxClients int
}

EmbedOptions configures OpenEmbedded.

type Embedded

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

Embedded is an in-process RESP endpoint: a Store plus a listener goroutine in the calling process. Nothing is forked, so the storage lifecycle is exactly the process lifecycle — when the host process restarts, the store restarts with it and Pebble replays its WAL.

The endpoint speaks RESP over a unix socket, which is what lets existing Redis clients switch over by changing only the connection string. That also means a command still pays for RESP parsing and a socket round trip: it saves the separate process, not the protocol. Code that can call Store methods directly is faster and needs no listener at all — the two can be used side by side on the same Store.

func OpenEmbedded

func OpenEmbedded(opts EmbedOptions) (*Embedded, error)

OpenEmbedded opens a data directory and serves it on a unix socket inside the current process. The returned Embedded must be closed; closing it stops the listener, closes Pebble (so the WAL is complete) and removes the socket.

func (*Embedded) Addr

func (e *Embedded) Addr() string

Addr is what clients connect to: the unix socket path for a "unix" listener, or the resolved "host:port" (with the ephemeral port filled in) for a "tcp" one.

func (*Embedded) Close

func (e *Embedded) Close() error

Close stops the listener, then closes the store so the WAL is complete, then removes the socket file. Connections that are mid-command when this runs will see an error rather than a reply: stop the listener first is deliberate, but there is no drain of in-flight requests.

func (*Embedded) Network

func (e *Embedded) Network() string

Network is the listener kind, "unix" or "tcp". Clients need it to pick the right dial network.

func (*Embedded) Store

func (e *Embedded) Store() *Store

Store exposes the underlying store, so hot paths can call it directly and skip the protocol entirely.

type ExpireOption

type ExpireOption struct {
	// Time is the absolute deadline.
	Time time.Time
	// NX only sets the TTL when the key has none; XX only when it has one.
	NX bool
	XX bool
	// GT only extends an existing TTL; LT only shortens it.
	GT bool
	LT bool
}

ExpireOption carries the parsed flags of EXPIRE / PEXPIRE / EXPIREAT / ...

type Options

type Options = config.Config

Options configures a Store. It aliases config.Config so callers can use DefaultOptions() and then tweak fields.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns a configuration suitable for a single-node cache.

type Server

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

Server serves the RESP protocol over a Store.

The protocol and connection handling come from redcon: it parses an entire pipeline in one read and flushes the batch of replies in one write, which is the main reason it was picked over rolling our own loop.

func NewServer

func NewServer(s *Store, opts ServerOptions) *Server

NewServer wraps a Store with a RESP listener.

func (*Server) Addr

func (srv *Server) Addr() string

Addr returns the listener address, once ListenAndServe has bound it.

func (*Server) Close

func (srv *Server) Close() error

Close stops the listener.

func (*Server) ConnectedClients

func (srv *Server) ConnectedClients() int64

ConnectedClients returns the current connection count.

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe binds opts.Addr and serves. It blocks until Close is called or the listener fails.

func (*Server) Serve

func (srv *Server) Serve(ln net.Listener) error

Serve accepts connections on an existing listener. Useful when the address must be known before the server starts, as in tests that bind port 0.

type ServerOptions

type ServerOptions struct {
	// Addr is the listen address, e.g. ":6379".
	Addr string
	// Network defaults to "tcp"; "unix" is also supported.
	Network string
	// TLSConfig enables TLS when set (and mTLS when ClientAuth is set).
	TLSConfig *tls.Config
	// MaxClients caps concurrent connections. Zero means unlimited.
	MaxClients int
	// IdleTimeout closes connections with no traffic for this long.
	IdleTimeout time.Duration
	// MaxBulkLen caps a single command argument, guarding against a huge SET
	// exhausting memory before anything is written.
	MaxBulkLen int
	// MaxClients 之外的背压:单条命令响应的写缓冲上限。
	MaxWriteBuffer int
}

ServerOptions configures the RESP listener.

type SetOption

type SetOption struct {
	// EX / PX are relative durations.
	EX time.Duration
	PX time.Duration
	// EXAT / PXAT are absolute deadlines.
	EXAT time.Time
	PXAT time.Time
	// NX / XX are the conditional-write flags.
	NX bool
	XX bool
	// KEEPTTL preserves any existing TTL on overwrite.
	KEEPTTL bool
	// GET returns the previous value.
	GET bool
}

SetOption carries the parsed flags of SET and friends.

The shape mirrors cybergarage/go-redis's redis.SetOption, which got the Redis option grammar right; re-deriving it from the spec is a reliable way to end up subtly incompatible with real clients.

func (SetOption) ExpireAt

func (o SetOption) ExpireAt(now time.Time) time.Time

ExpireAt resolves the effective expiry of the option set, or the zero time when no expiry was requested.

type SlowLog

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

SlowLog keeps a bounded ring of the slowest commands.

maxLen and slowerThan are atomic: record() runs on the hot path for every command and must not contend with CONFIG SET, which mutates them from a client goroutine. The entries ring itself is guarded by mu.

type Stats

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

Stats holds the counters surfaced by INFO.

type Store

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

Store is a single logical instance: one Pebble store plus its in-memory index.

Nothing here depends on the network layer, which is what makes the embedded use case cheap - see api.go for the direct-call surface.

func Open

func Open(cfg *config.Config) (*Store, error)

Open creates or reopens a store. An empty cfg.Dir yields a memory-backed store, which is handy for tests and for pure-cache deployments.

func (*Store) Append

func (s *Store) Append(key string, val []byte) (int64, error)

Append appends to a string value and returns the new length.

func (*Store) BlockCacheMemory

func (s *Store) BlockCacheMemory() int64

BlockCacheMemory returns the current Pebble block cache usage.

func (*Store) Checkpoint

func (s *Store) Checkpoint(destDir string) error

Checkpoint writes a consistent hard-link snapshot to destDir.

func (*Store) Close

func (s *Store) Close() error

Close stops background workers and releases the store. It is safe to call more than once.

func (*Store) Config

func (s *Store) Config() *config.Config

Config returns the live configuration.

func (*Store) DBCount

func (s *Store) DBCount() int

DBCount returns the number of addressable logical databases.

func (*Store) Del

func (s *Store) Del(keys ...string) (int64, error)

Del removes keys and returns how many existed.

func (*Store) DelDB

func (s *Store) DelDB(db uint16, keys ...string) (int64, error)

DelDB is Del on an explicit database.

func (*Store) DiskUsage

func (s *Store) DiskUsage() uint64

DiskUsage returns an estimate of the on-disk footprint.

func (*Store) Engine

func (s *Store) Engine() *storage.Engine

Engine exposes the Pebble wrapper, for backup and metrics.

func (*Store) Exists

func (s *Store) Exists(keys ...string) (int64, error)

Exists counts how many of keys are present.

func (*Store) Expire

func (s *Store) Expire(key string, ttl time.Duration) (bool, error)

Expire sets a TTL on a key, reporting whether it was applied.

func (*Store) Flush

func (s *Store) Flush() error

Flush forces memtables to stable storage.

func (*Store) FlushDB

func (s *Store) FlushDB() error

FlushDB removes every key in database 0.

func (*Store) Get

func (s *Store) Get(key string) ([]byte, error)

Get returns the value at key in database 0, or nil when it is absent.

func (*Store) GetDB

func (s *Store) GetDB(db uint16, key string) ([]byte, error)

GetDB is Get on an explicit database.

func (*Store) GetSet

func (s *Store) GetSet(key string, val []byte) ([]byte, error)

GetSet writes a value and returns the previous one.

func (*Store) Incr

func (s *Store) Incr(key string) (int64, error)

Incr increments the integer at key and returns the new value.

func (*Store) IncrBy

func (s *Store) IncrBy(key string, delta int64) (int64, error)

IncrBy adds delta to the integer at key and returns the new value.

func (*Store) LockKey

func (s *Store) LockKey(db uint16, key string)

LockKey/UnlockKey/RLockKey/RUnlockKey are the single-key entry points used by callers that already know the (db, key) they touch for the whole operation (the embedded API, blocking commands that re-lock inside their handler).

func (*Store) LockKeys

func (s *Store) LockKeys(db uint16, keys []string, write bool) func()

LockKeys is the multi-key entry point used by command dispatch. See keyLockTable.lockAll for the ordering and deadlock-avoidance contract.

func (*Store) MGet

func (s *Store) MGet(keys ...string) ([][]byte, error)

MGet returns the values of keys, using nil for absent ones.

func (*Store) MSet

func (s *Store) MSet(pairs map[string][]byte) error

MSet writes several key/value pairs atomically on the durable side.

func (*Store) Persist

func (s *Store) Persist(key string) (bool, error)

Persist removes a key's TTL.

func (*Store) RLockKey

func (s *Store) RLockKey(db uint16, key string)

func (*Store) RUnlockKey

func (s *Store) RUnlockKey(db uint16, key string)

func (*Store) Rename

func (s *Store) Rename(src, dst string) error

Rename moves a key.

func (*Store) Set

func (s *Store) Set(key string, val []byte) error

Set writes a value in database 0 with no expiry.

func (*Store) SetDB

func (s *Store) SetDB(db uint16, key string, val []byte) error

SetDB is Set on an explicit database.

func (*Store) SetEx

func (s *Store) SetEx(key string, val []byte, ttl time.Duration) error

SetEx writes a value with a TTL.

func (*Store) SetNX

func (s *Store) SetNX(key string, val []byte) (bool, error)

SetNX writes only when the key is absent, reporting whether it was written.

func (*Store) Shutdown

func (s *Store) Shutdown() <-chan struct{}

Shutdown returns a channel that is closed when a client issues SHUTDOWN. A standalone server uses it to exit; an embedded caller may ignore it.

func (*Store) StrLen

func (s *Store) StrLen(key string) (int64, error)

StrLen returns the length of a string value.

func (*Store) TTL

func (s *Store) TTL(key string) (ttl time.Duration, ok bool, exists bool, err error)

TTL returns the remaining time to live. It returns ok=false when the key has no TTL, and exists=false when the key is absent.

func (*Store) TotalMemory

func (s *Store) TotalMemory() int64

TotalMemory returns everything charged against MaxMemory: the index plus, when the budget is large enough to include them, the block cache and memtables.

func (*Store) Type

func (s *Store) Type(key string) (string, error)

Type returns the Redis type name of a key, or "none".

func (*Store) UnlockKey

func (s *Store) UnlockKey(db uint16, key string)

func (*Store) Uptime

func (s *Store) Uptime() time.Duration

Uptime returns how long the store has been running.

func (*Store) UsedMemory

func (s *Store) UsedMemory() int64

UsedMemory returns the estimated bytes held by the in-memory index.

type Writer

type Writer interface {
	WriteString(str string)
	WriteBulk(bulk []byte)
	WriteBulkString(bulk string)
	WriteInt(num int)
	WriteInt64(num int64)
	WriteArray(count int)
	WriteNull()
	WriteError(msg string)
}

Writer is the RESP response surface a command handler may use.

redcon.Conn satisfies it directly, so the RESP path allocates nothing extra, while tests can substitute a recorder.

type ZAddOption

type ZAddOption struct {
	XX, NX, LT, GT, CH, INCR bool
}

ZAddOption carries the flags of ZADD, mirroring cybergarage/go-redis.

Directories

Path Synopsis
cmd
pebbisd command
Command pebbisd runs a Pebbis instance as a standalone RESP server.
Command pebbisd runs a Pebbis instance as a standalone RESP server.
Package config holds the tunable knobs of a Pebbis instance.
Package config holds the tunable knobs of a Pebbis instance.
Package glob implements Redis-compatible key-pattern matching for KEYS, SCAN MATCH, and pub/sub channel patterns.
Package glob implements Redis-compatible key-pattern matching for KEYS, SCAN MATCH, and pub/sub channel patterns.
Package memory implements the in-memory index, LRU/LFU metadata, expiry and eviction.
Package memory implements the in-memory index, LRU/LFU metadata, expiry and eviction.
Package storage implements the Pebble-backed persistence layer.
Package storage implements the Pebble-backed persistence layer.
tests
bench command
Command bench is a standalone performance/load harness for a running pebbisd instance.
Command bench is a standalone performance/load harness for a running pebbisd instance.
drill command
Command drill is a restart drill: it starts a real pebbisd, writes a mixed workload, SIGKILLs it (no graceful shutdown, no Pebble close), restarts it on the same directory and checks that every acknowledged write came back — including large values that live in Pebble rather than the in-memory index, counters kept through the merge operator, transactions, TTLs and the stream pending-entries list.
Command drill is a restart drill: it starts a real pebbisd, writes a mixed workload, SIGKILLs it (no graceful shutdown, no Pebble close), restarts it on the same directory and checks that every acknowledged write came back — including large values that live in Pebble rather than the in-memory index, counters kept through the merge operator, transactions, TTLs and the stream pending-entries list.
miniredis
Package miniredis is a pure Go Redis test server, for use in Go unittests.
Package miniredis is a pure Go Redis test server, for use in Go unittests.
miniredis/geohash
Package geohash provides encoding and decoding of string and integer geohashes.
Package geohash provides encoding and decoding of string and integer geohashes.

Jump to

Keyboard shortcuts

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