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
- Variables
- func CommandCount() int
- func CommandNames() []string
- func IsQuit(err error) bool
- func OOM(cmd string) error
- func ParseByteSize(s string) (uint64, error)
- func UnknownCommand(name string) error
- func WrongArgs(cmd string) error
- type Ctx
- type EmbedOptions
- type Embedded
- type ExpireOption
- type Options
- type Server
- type ServerOptions
- type SetOption
- type SlowLog
- type Stats
- type Store
- func (s *Store) Append(key string, val []byte) (int64, error)
- func (s *Store) BlockCacheMemory() int64
- func (s *Store) Checkpoint(destDir string) error
- func (s *Store) Close() error
- func (s *Store) Config() *config.Config
- func (s *Store) DBCount() int
- func (s *Store) Del(keys ...string) (int64, error)
- func (s *Store) DelDB(db uint16, keys ...string) (int64, error)
- func (s *Store) DiskUsage() uint64
- func (s *Store) Engine() *storage.Engine
- func (s *Store) Exists(keys ...string) (int64, error)
- func (s *Store) Expire(key string, ttl time.Duration) (bool, error)
- func (s *Store) Flush() error
- func (s *Store) FlushDB() error
- func (s *Store) Get(key string) ([]byte, error)
- func (s *Store) GetDB(db uint16, key string) ([]byte, error)
- func (s *Store) GetSet(key string, val []byte) ([]byte, error)
- func (s *Store) Incr(key string) (int64, error)
- func (s *Store) IncrBy(key string, delta int64) (int64, error)
- func (s *Store) LockKey(db uint16, key string)
- func (s *Store) LockKeys(db uint16, keys []string, write bool) func()
- func (s *Store) MGet(keys ...string) ([][]byte, error)
- func (s *Store) MSet(pairs map[string][]byte) error
- func (s *Store) Persist(key string) (bool, error)
- func (s *Store) RLockKey(db uint16, key string)
- func (s *Store) RUnlockKey(db uint16, key string)
- func (s *Store) Rename(src, dst string) error
- func (s *Store) Set(key string, val []byte) error
- func (s *Store) SetDB(db uint16, key string, val []byte) error
- func (s *Store) SetEx(key string, val []byte, ttl time.Duration) error
- func (s *Store) SetNX(key string, val []byte) (bool, error)
- func (s *Store) Shutdown() <-chan struct{}
- func (s *Store) StrLen(key string) (int64, error)
- func (s *Store) TTL(key string) (ttl time.Duration, ok bool, exists bool, err error)
- func (s *Store) TotalMemory() int64
- func (s *Store) Type(key string) (string, error)
- func (s *Store) UnlockKey(db uint16, key string)
- func (s *Store) Uptime() time.Duration
- func (s *Store) UsedMemory() int64
- type Writer
- type ZAddOption
Constants ¶
const ( SegStreamEntry byte = 0x0B SegStreamGroup byte = 0x0C SegStreamPEL byte = 0x0D )
Segment tags for stream structures.
const Version = "0.1.0"
Version is reported through INFO.
Variables ¶
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.
var ErrClosed = errors.New("Pebbis: store is closed")
ErrClosed is returned once the store has been closed.
Functions ¶
func CommandNames ¶
func CommandNames() []string
CommandNames returns the sorted list of supported command names.
func ParseByteSize ¶
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 ¶
UnknownCommand builds the error for an unrecognised command name.
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.
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 ¶
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 ¶
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.
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 ¶
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) ConnectedClients ¶
ConnectedClients returns the current connection count.
func (*Server) ListenAndServe ¶
ListenAndServe binds opts.Addr and serves. It blocks until Close is called or the listener fails.
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.
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 ¶
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) BlockCacheMemory ¶
BlockCacheMemory returns the current Pebble block cache usage.
func (*Store) Checkpoint ¶
Checkpoint writes a consistent hard-link snapshot to destDir.
func (*Store) Close ¶
Close stops background workers and releases the store. It is safe to call more than once.
func (*Store) LockKey ¶
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 ¶
LockKeys is the multi-key entry point used by command dispatch. See keyLockTable.lockAll for the ordering and deadlock-avoidance contract.
func (*Store) RUnlockKey ¶
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) TTL ¶
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 ¶
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) UsedMemory ¶
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.
Source Files
¶
- admin.go
- aggregate.go
- api.go
- blocking.go
- cmd_bit.go
- cmd_completion.go
- cmd_conn.go
- cmd_generic.go
- cmd_hash.go
- cmd_list.go
- cmd_scripting.go
- cmd_server.go
- cmd_set.go
- cmd_stream.go
- cmd_stream_dispatch.go
- cmd_string.go
- cmd_zset.go
- cmd_zset2.go
- ctx.go
- data.go
- dispatch.go
- embed.go
- errors.go
- keys.go
- option.go
- pubsub.go
- pubsub_hub.go
- server.go
- store.go
- stream.go
- txn.go
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. |