redissegment

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 18 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.

Documentation

Overview

Package redissegment is a segment.Provider that answers segment membership lookups from a Redis or Valkey store with go-redis (segment type segment.TypeRedis; the valkey-go provider, type segment.TypeValkey, is a separate package).

All the lookups of one call go out in one pipeline (one more after a NOSCRIPT answer), so one call is one round trip on a single node (one per node on a cluster). A segment is either a set of members read with SMISMEMBER (layout "set") or one key per member read with EXISTS (layout "keys"). The provider only reads: it never writes, so a read-only ACL user is enough.

The provider reports what it could not answer as segment.Unknown and never applies a failure policy: the engine does (segment.Definition.OnError and the onError of the rule). A call that fails, in whole or in part, returns a *LookupError that names the class of the failure and the counts only, never an id or a key. A panic of the client is recovered and counts as an unavailable store: no answer of that call is kept.

A go-redis client passed to New must have ContextTimeoutEnabled set, or the socket ignores the deadline of a call: New refuses one that exposes its options and has it off. Dial sets it on a copy of the options. Init probes the commands that the configured layouts and mode will use, on keys of the configured namespace.

Shutdown stops new calls (Contains, Init and Exists return ErrClosed), waits for the calls in flight until its own context ends, and then ends them: no command is sent after it returns.

Index

Constants

View Source
const (
	// DefaultTimeout is the per-call timeout when Options.Timeout is zero.
	DefaultTimeout = 100 * time.Millisecond
	// DefaultKeyPrefix is the prefix of the keys of the segments when Options.KeyPrefix is empty.
	DefaultKeyPrefix = "semaphore:segment:"
	// DefaultMaxIDBytes is the longest id that is looked up when Options.MaxIDBytes is zero.
	DefaultMaxIDBytes = 512
	// MaxIDsPerCommand is the most ids that one SMISMEMBER (or script) carries: a segment with more ids in a call is
	// several commands in the same pipeline.
	MaxIDsPerCommand = 1000
	// MinSocketTimeout is the least positive read, write or dial timeout of a go-redis client that is accepted.
	// go-redis runs the handshake that opens a connection (HELLO and the init pipeline) under the read and write
	// timeouts, and the dial, TLS handshake included, under the dial timeout, and has no separate handshake
	// timeout: the bound is one second so that a value that is accepted does not fail the connection on a link with
	// ordinary latency (TLS, another region, a loaded host).
	MinSocketTimeout = time.Second
)
View Source
const MaxInitProbes = 16

MaxInitProbes is the most namespaces that Init probes, the set and the keys layouts together: a provider with segments in more namespaces checks the first MaxInitProbes of them by name, so startup stays one small pipeline.

View Source
const MaxScanPages = 1 << 20

MaxScanPages is the most pages that one scan may take: a store that keeps answering pages (a cursor loop) fails the scan instead of running for ever. At a COUNT of 1000 it is a set of more than a billion members.

View Source
const ScanCount = 1000

ScanCount is the COUNT hint of each SSCAN page of Provider.Members.

View Source
const Script = `` /* 133-byte string literal not displayed */

Script is the Lua script of an atomic call (see Options.Atomic) for one set: it answers the existence of the key, then 1 or 0 for each id, in one atomic step on the node that holds the key. It reads one key, so it runs on a cluster, and it has no limit on the number of ids as SMISMEMBER through unpack would.

View Source
const ScriptSHA = "4dc3e21a3a7ca911ad25145699dd3279464e74cf"

ScriptSHA is the SHA1 of Script, which EVALSHA names. A test pins it to the script.

Variables

View Source
var (
	// ErrCanceled is wrapped by a LookupError of ClassCanceled.
	ErrCanceled = errors.New("redis segment: context ended")
	// ErrTimeout is wrapped by a LookupError of ClassTimeout.
	ErrTimeout = errors.New("redis segment: timeout")
	// ErrUnavailable is wrapped by a LookupError of ClassUnavailable.
	ErrUnavailable = errors.New("redis segment: store unavailable")
	// ErrServer is wrapped by a LookupError of ClassServer.
	ErrServer = answeredError("redis segment: store returned an error")
	// ErrProtocol is wrapped by a LookupError of ClassProtocol.
	ErrProtocol = answeredError("redis segment: unexpected reply")

	// ErrInvalidOptions is wrapped by the errors of options that are not valid.
	ErrInvalidOptions = errors.New("redis segment: invalid options")
	// ErrClosed is returned by a call after Shutdown.
	ErrClosed = errors.New("redis segment: closed")
	// ErrContextTimeoutDisabled is wrapped by the error of New for a go-redis client without ContextTimeoutEnabled.
	ErrContextTimeoutDisabled = errors.New("redis segment: the client must set ContextTimeoutEnabled")
	// ErrSocketDeadlineDisabled is wrapped by the error of New and Dial for a go-redis client whose read or write
	// timeout is disabled: the socket then has no deadline, whatever the context says.
	ErrSocketDeadlineDisabled = errors.New("redis segment: the client must not disable its read and write timeouts")
	// ErrSocketTimeoutTooShort is wrapped by the error of New and Dial for a go-redis client whose read, write or dial
	// timeout is positive and below MinSocketTimeout: go-redis bounds its connection handshake by them.
	ErrSocketTimeoutTooShort = errors.New(
		"redis segment: the client's read, write and dial timeouts must be at least 1s")
	// ErrNoVersionKey is returned by Version for a segment that has no SegmentOptions.VersionKey.
	ErrNoVersionKey = fmt.Errorf("%w: %s segment: no version key is configured", segment.ErrNoVersion, "redis")
	// ErrSnapshotLayout is yielded by Members for a segment of LayoutKeys: a snapshot of the keys layout would need
	// SCAN over the whole keyspace of the node (and of every node of a cluster), see Members.
	ErrSnapshotLayout = errors.New("redis segment: the snapshot mode needs the set layout")
	// ErrNilClient is returned when the client is nil.
	ErrNilClient = errors.New("redis segment: nil client")
)
View Source
var ErrInit = errors.New("redis segment: init failed")

ErrInit is wrapped, with the sentinel of the class, by the error of Init.

Functions

func DefaultKey

func DefaultKey(prefix, name string, layout Layout) string

DefaultKey is the key of a segment whose definition names none: <prefix>{<name>} for a set (the name is a hash tag, so a temporary key with the same tag lands in the same cluster slot and RENAME works) and <prefix><name>: for the keys layout. An empty prefix means DefaultKeyPrefix. The providers and the tools that write members use it.

Types

type Class

type Class uint8

Class is the kind of failure of a call.

const (
	// ClassNone means no failure.
	ClassNone Class = iota
	// ClassCanceled means the context of the caller ended (cancelled or its own deadline passed).
	ClassCanceled
	// ClassTimeout means the per-call timeout of the provider (or a network timeout) passed.
	ClassTimeout
	// ClassUnavailable means the store could not be reached or the connection broke.
	ClassUnavailable
	// ClassServer means the store answered with an error (no permission, wrong key type, loading, cluster down).
	ClassServer
	// ClassProtocol means the store answered with a reply that is not the one the command returns.
	ClassProtocol
)

func Classes

func Classes() []Class

Classes lists the failure classes, ClassNone excluded.

func (Class) String

func (c Class) String() string

String implements fmt.Stringer.

type Client

type Client interface {
	Pipeline() redis.Pipeliner
}

Client is the part of a go-redis client that the provider uses. A redis.UniversalClient (a single node, a failover set or a cluster) satisfies it.

type Counters

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

Counters is an Observer that counts with atomics. The zero value is ready to use.

func (*Counters) Observe

func (c *Counters) Observe(obs Observation)

Observe implements Observer.

func (*Counters) Snapshot

func (c *Counters) Snapshot() Stats

Snapshot returns the current counts.

type Layout

type Layout string

Layout is how the members of a segment are stored.

const (
	// LayoutSet stores the members in one set. A lookup is SMISMEMBER (Redis 6.2, Valkey 7.2 and later). The
	// lookups of a segment in a call are one SMISMEMBER.
	LayoutSet Layout = "set"
	// LayoutKeys stores one key per member, named <prefix><id>. A lookup is EXISTS.
	LayoutKeys Layout = "keys"
)

type LookupError

type LookupError struct {
	// Class is the most severe class among the failures of the call.
	Class Class
	// Failed is the number of lookups left Unknown by a failure.
	Failed int
	// Total is the number of lookups of the call.
	Total int
}

LookupError is returned by Contains when at least one lookup could not be answered. It holds the class of the failure and counts only: never an id, a key or an address.

func (*LookupError) Error

func (e *LookupError) Error() string

Error implements error.

func (*LookupError) Unwrap

func (e *LookupError) Unwrap() error

Unwrap returns the sentinel of the class, so errors.Is with ErrTimeout works.

type MissingKey

type MissingKey string

MissingKey is what a lookup of a set segment becomes when the key of the set does not exist.

const (
	// MissingUnknown answers Unknown: the segment is not loaded, and the engine applies the failure policy to it. It
	// is an opt-in, fail-closed. An empty set does not exist in Valkey, so an emptied segment is also Unknown.
	MissingUnknown MissingKey = "unknown"
	// MissingNotMember answers NotMember: a missing key is an empty segment. It is the default and saves the EXISTS
	// command.
	MissingNotMember MissingKey = "notMember"
)

type Observation

type Observation struct {
	// Lookups is the number of lookups of the call.
	Lookups int
	// Answered is the number of lookups set to Member or NotMember.
	Answered int
	// Oversized is the number of lookups left Unknown because the id is longer than MaxIDBytes.
	Oversized int
	// Unknown is the number of lookups left Unknown (a failure, an unconfigured segment, a missing key).
	Unknown int
	// RoundTrips is the number of pipelines the call sent: 0 when nothing was sent, 1 usually, 2 when the store
	// answered NOSCRIPT and the script was sent again with its text.
	RoundTrips int
	// Duration is the time of the call, read from the clock package.
	Duration time.Duration
	// Failure is the class of the failure, ClassNone when the call returned no error.
	Failure Class
}

Observation describes one call of Contains. It holds counts only, never an id or a key.

type Observer

type Observer interface {
	Observe(Observation)
}

Observer receives one Observation per call of Contains that reached the provider: a call with no lookup and a call after Shutdown return before it and are not observed. It is called on the goroutine of the caller, so it must be fast and safe for concurrent use. The relay proxy wires its metrics through it.

type Options

type Options struct {
	// Segments maps a segment name to where its members are. A lookup of a segment that is not here stays Unknown:
	// a flag can never choose a key.
	Segments map[string]SegmentOptions
	// Observer (optional) receives one Observation per call, except for a call with no lookup and a call after
	// Shutdown.
	Observer Observer
	// Atomic sets the atomic existence check: the EXISTS of the key of a set and its SMISMEMBER run in one
	// MULTI/EXEC, so a set that is created or deleted while the call runs is seen whole or not at all. Nil means on.
	// False sends the two commands in one pipeline without a transaction: a set that is created between them is
	// answered as a non-member, which matches no state of the set, and the resolver may cache the answer. The check
	// applies only to MissingUnknown (MissingNotMember has no key check) and to the set layout. It needs the
	// MULTI and EXEC commands (an ACL user needs +multi +exec); on a cluster each set is a transaction of its
	// own, so a call with several sets is one round trip for each set, at most eight at the same time. A client
	// without a TxPipelined method gets no check: [Provider.AtomicExistence] says so.
	Atomic *bool
	// KeyPrefix is the default prefix of the keys. Empty means DefaultKeyPrefix.
	KeyPrefix string
	// MissingKey is what a missing set key means. Empty means MissingNotMember.
	MissingKey MissingKey
	// MaxIDBytes is the longest id, in bytes, that the provider looks up. A longer id stays Unknown, is not sent to
	// the store and is counted in Observation.Oversized. Zero means DefaultMaxIDBytes.
	MaxIDBytes int
	// Timeout bounds one call, under the deadline of the caller. Zero means DefaultTimeout.
	Timeout time.Duration
	// Script makes the atomic check one Lua script (EVALSHA, with EVAL as the fallback) instead of MULTI/EXEC: all
	// the ids of a set go in one script, whatever their number (the limit of MaxIDsPerCommand does not apply), and
	// a cluster call is still one pipeline. It needs the permission to run the script commands. It has no effect
	// when Atomic is false or MissingKey is not MissingUnknown (no existence check is sent then).
	Script bool
}

Options configures a Provider.

type Provider

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

Provider is a segment.Provider over Redis or Valkey through go-redis. It is safe for concurrent use.

func Dial

func Dial(redisOpts *redis.UniversalOptions, opts *Options) (*Provider, error)

Dial creates a go-redis client from the options and returns a Provider that owns it: Close closes the client.

func New

func New(client Client, opts *Options) (*Provider, error)

New returns a Provider that reads through client. The caller owns the client and closes it. A go-redis client must have ContextTimeoutEnabled set (Dial does it): New fails with ErrContextTimeoutDisabled when the client exposes its options and it is not.

func (*Provider) AtomicExistence

func (p *Provider) AtomicExistence() bool

AtomicExistence implements segment.AtomicExistencer: true when the set lookups of a missingKey unknown provider answer the existence of the key and the membership of the ids from one read, in MULTI/EXEC or in one script. It is false when the check is turned off (Options.Atomic false), when missingKey is notMember (no existence check is sent), and when the client has no transactions and Options.Script is not set.

func (*Provider) Close

func (p *Provider) Close() error

Close closes the client when the provider owns it (see Dial) and does nothing otherwise. It is safe to call more than once: the first call returns the error of the client, the next ones return nil.

func (*Provider) Contains

func (p *Provider) Contains(ctx context.Context, lookups []segment.Lookup) error

Contains implements segment.Provider. It sends all the lookups in one pipeline and sets the state of each lookup that the store answered. See the package documentation for the failure behaviour.

func (*Provider) Exists

func (p *Provider) Exists(ctx context.Context, names []string) ([]segment.State, error)

Exists tells whether the segments are loaded: Member when the key of a set exists, NotMember when it does not, Unknown for a segment of the keys layout (it has no single key) or one that is not configured, or when the store could not answer. A failure returns a *LookupError and leaves the states of the answered names.

func (*Provider) Health

func (p *Provider) Health() segment.Health

Health implements segment.HealthReporter.

func (*Provider) Init

func (p *Provider) Init(ctx context.Context) (err error)

Init checks that the store answers (a PING under the timeout of the provider) and that it has the commands that the layouts need: SMISMEMBER for a set segment, EXISTS for a keys segment, EVAL for Atomic. It also learns whether the read-only script commands exist, and uses them from then on. It fails with ErrInit, naming the command that is missing, so an old or restricted server is found at the start and not at the first request. A provider needs no Init to work.

func (*Provider) Members

func (p *Provider) Members(ctx context.Context, name string) iter.Seq2[string, error]

Members implements segment.SnapshotSource for the set layout: SSCAN pages of ScanCount members, all of them read from the primary of the slot of the set (a cursor belongs to one node), streamed as they arrive. SSCAN may repeat a member, which the consumer's set absorbs. An empty set does not exist in the store, so a segment with no member is reported as segment.ErrSegmentMissing, whatever the MissingKey of the provider: what a missing segment means for the snapshot is the policy of the holder, not of the store. A reply that is not a well formed page (a cursor that is not a number, members that are not strings, a cursor that comes back, too many pages) is an error that wraps ErrProtocol, never the end of the scan.

The keys layout is refused with ErrSnapshotLayout: its members are separate keys, so the only way to list them is SCAN with a MATCH over the whole keyspace of every node, which reads every key of the database, not only the segment, and on a cluster reaches only one node. That is too slow and not safe for a periodic pull.

func (*Provider) Shutdown

func (p *Provider) Shutdown(ctx context.Context) error

Shutdown marks the provider closed, so no new call starts, waits for the calls in flight until ctx ends, and then closes the client when the provider owns it (see Dial). When ctx ends first it ends the calls in flight and returns the error of ctx: no call sends a command after Shutdown returns. A second call waits for the same calls and closes nothing again.

func (*Provider) Status

func (p *Provider) Status() Status

Status returns a snapshot of the health of the provider.

func (*Provider) Version

func (p *Provider) Version(ctx context.Context, name string) (string, error)

Version implements segment.Versioner: the value of the version key of the segment (GET), read from the primary of its slot and prefixed with "v:". A version key that does not exist is segment.AbsentVersion, which no stored value can be equal to. A segment with no version key has no version: the error wraps segment.ErrNoVersion.

type SegmentOptions

type SegmentOptions struct {
	// Layout is LayoutSet (default) or LayoutKeys.
	Layout Layout
	// Key is the key of the set (LayoutSet) or the prefix of the member keys (LayoutKeys). Empty means
	// <KeyPrefix>{<name>} for a set (the name is a hash tag, so a temporary key named with the same tag lands in
	// the same cluster slot and RENAME works) and <KeyPrefix><name>: for keys.
	Key string
	// VersionKey (optional) is the key that holds the version of the segment: a string that the writer of the members
	// changes whenever it changes them. [Provider.Version] reads it with GET; a missing key is the fixed version
	// [segment.AbsentVersion], not an error. Without it Version fails with [ErrNoVersionKey].
	VersionKey string
	// Snapshot makes Init probe the commands of the snapshot mode on this segment: SSCAN of the set, and GET of the
	// version key when there is one. A user that may only run the lookup commands then fails at the start, with an
	// error that names the command, not at the first pull.
	Snapshot bool
}

SegmentOptions says where the members of one segment are.

type Stats

type Stats struct {
	Failures map[string]uint64
	Calls    uint64
	Lookups  uint64
	Answered uint64
	Unknown  uint64
	// Oversized is the number of lookups left Unknown because the id was too long.
	Oversized  uint64
	RoundTrips uint64
	Duration   time.Duration
}

Stats is a snapshot of the counters of Counters.

type Status

type Status struct {
	// LastFailure is the class of the failure of the last call, ClassNone when it succeeded.
	LastFailure Class
	// Ready is true once Init or a call succeeded.
	Ready bool
	// Closed is true after Shutdown.
	Closed bool
}

Status is a snapshot of the health of the provider.

Jump to

Keyboard shortcuts

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