valkeysegment

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: 20 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 valkeysegment is the segment.Provider of segment type segment.TypeValkey. It answers segment membership lookups from a Valkey (or Redis 6.2 and later) store with valkey-go.

All the lookups of one call go out in one DoMulti: the client writes the commands of the call to the connection together and reads their replies in order, so one call is one round trip on a single node (one per node on a cluster). Concurrent calls share a connection and the client batches their writes (automatic pipelining). 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, so a read-only ACL user is enough. Client-side caching of the client is off: the answers are not cached here, the resolver does that.

The layouts, the options of a segment, the failure classes and the observer are the ones of package redissegment (the go-redis provider), so the two providers can be swapped. The provider reports what it could not answer as segment.Unknown and never applies a failure policy. A call that fails, in whole or in part, returns a *LookupError that names the class and the counts only, never an id, a key or an address. A reply that is not the one the command returns, or a stream that cannot be parsed, means no answer of the call is kept.

The client that Dial creates is configured by the Options Pipelining, BlockingPipeline and Retry, with safe defaults (always, never, false). Client-side caching is not used: lookups go through DoMulti, which valkey-go never caches, and the resolver is the cache. Under PipeliningAlways the client reads in the background even for a call that is alone on its connection: a connection that fails inside a batch keeps the replies already read, and a cancel ends the call at once. valkey-go's own default (PipeliningAuto) writes and reads a lone call synchronously, which loses the whole batch on a failure and sees only the deadline: a reply that arrives after the cancel and before the deadline is returned as the answer (a correct one). A client passed to New should be created like the default, see Client. valkey-go moves a call of BlockingPipeline commands or more to a dedicated connection, where a cancel waits for the connection to close; the default threshold of the provider is never.

Limits: a server or proxy that sends a reply nobody asked for makes valkey-go panic in its reader goroutine, which ends the process. The reader runs on every connection that pipelines in the background: all of them under PipeliningAlways, and under PipeliningAuto the connections that concurrent calls share. The go-redis provider (type redis) drops such a connection, closes it and the next call works: use it when the store sits behind a proxy that you do not trust. Also, when a slow peer stops reading until the ring of commands of a connection is full (1024 calls waiting), valkey-go's DoMulti waits for a slot without looking at the context: the call timeout does not end that wait. It ends when the connection is closed because of ClientOption.ConnWriteTimeout (about 10 seconds by default): set a lower value if you need a tighter bound.

The decoded replies are checked before any answer is kept: a reply of the wrong shape anywhere in a call (not an integer 0 or 1, a list of the wrong length or with a null) means no answer of the call is kept. A set segment asks EXISTS of its key before SMISMEMBER, so a set that is created while the call runs is Unknown or answered by SMISMEMBER, never a NotMember that matches no state of the set.

Shutdown stops new calls (they return ErrClosed, also after a Shutdown whose context ended), waits for the calls in flight until its own context ends, and then ends them: the call in flight returns the canceled class. It closes the client when the provider owns it (Dial); when its context ended first, the close runs in the background so that Shutdown does not wait behind the deadline of the caller.

Index

Constants

View Source
const (
	ClassNone        = redissegment.ClassNone
	ClassCanceled    = redissegment.ClassCanceled
	ClassTimeout     = redissegment.ClassTimeout
	ClassUnavailable = redissegment.ClassUnavailable
	ClassServer      = redissegment.ClassServer
	ClassProtocol    = redissegment.ClassProtocol

	LayoutSet  = redissegment.LayoutSet
	LayoutKeys = redissegment.LayoutKeys

	MissingUnknown   = redissegment.MissingUnknown
	MissingNotMember = redissegment.MissingNotMember
)

The classes, the layouts and the missing key modes, as in package redissegment.

View Source
const (
	// DefaultTimeout is the per-call timeout when Options.Timeout is zero.
	DefaultTimeout = redissegment.DefaultTimeout
	// DefaultKeyPrefix is the prefix of the keys of the segments when Options.KeyPrefix is empty.
	DefaultKeyPrefix = redissegment.DefaultKeyPrefix
	// DefaultMaxIDBytes is the longest id that is looked up when Options.MaxIDBytes is zero.
	DefaultMaxIDBytes = redissegment.DefaultMaxIDBytes
	// MaxIDsPerCommand is the most ids that one SMISMEMBER carries: a segment with more ids in a call is several
	// commands in the same DoMulti.
	MaxIDsPerCommand = redissegment.MaxIDsPerCommand
	// MaxInitProbes is the most namespaces that Init probes.
	MaxInitProbes = redissegment.MaxInitProbes
)

The defaults and limits are the ones of package redissegment.

View Source
const (
	// MinConnWriteTimeout is the least ConnWriteTimeout that is accepted. valkey-go applies the timeout to every
	// command of a connection, the commands of its handshake (HELLO, CLIENT SETINFO) included, and has no separate
	// handshake timeout: the bound is one second so that a value that is accepted does not fail the handshake on a
	// link with ordinary latency (TLS, another region, a loaded host).
	MinConnWriteTimeout = time.Second
	// MaxConnWriteTimeout is the most ConnWriteTimeout that is accepted.
	MaxConnWriteTimeout = time.Minute
)

The bounds of Options.ConnWriteTimeout.

View Source
const MaxClusterConcurrency = 16

MaxClusterConcurrency is the most DoMulti calls that one lookup call has in flight on a cluster client with the atomic check: each set is a transaction in a DoMulti of its own.

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.

Variables

View Source
var (
	// ErrCanceled is wrapped by a LookupError of ClassCanceled.
	ErrCanceled = errors.New("valkey segment: context ended")
	// ErrTimeout is wrapped by a LookupError of ClassTimeout.
	ErrTimeout = errors.New("valkey segment: timeout")
	// ErrUnavailable is wrapped by a LookupError of ClassUnavailable.
	ErrUnavailable = errors.New("valkey segment: store unavailable")
	// ErrServer is wrapped by a LookupError of ClassServer.
	ErrServer = answeredError("valkey segment: store returned an error")
	// ErrProtocol is wrapped by a LookupError of ClassProtocol.
	ErrProtocol = answeredError("valkey segment: unexpected reply")
	// ErrInvalidOptions is wrapped by the error of New and Dial for options that cannot work.
	ErrInvalidOptions = errors.New("valkey segment: invalid options")
	// ErrClosed is returned by a call after Shutdown.
	ErrClosed = errors.New("valkey segment: closed")
	// 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, "valkey")
	// 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("valkey segment: the snapshot mode needs the set layout")
	// ErrNilClient is returned by New and Dial for a nil client or nil options.
	ErrNilClient = errors.New("valkey segment: nil client")
	// ErrInit is wrapped, with the sentinel of the class, by the error of Init.
	ErrInit = errors.New("valkey segment: init failed")
)

Functions

func DefaultConnWriteTimeout

func DefaultConnWriteTimeout(callTimeout time.Duration) time.Duration

DefaultConnWriteTimeout is the ConnWriteTimeout that Dial sets when the option is zero: ten call timeouts (zero call timeout means DefaultTimeout), at least one second and at most MaxConnWriteTimeout.

Types

type Class

type Class = redissegment.Class

Class is the kind of failure of a call.

type Client

type Client interface {
	B() valkey.Builder
	DoMulti(ctx context.Context, multi ...valkey.Completed) []valkey.ValkeyResult
}

Client is the part of a valkey-go client that the provider uses. A valkey.Client (a single node, a sentinel set or a cluster) satisfies it. The contract for a client that you pass to New: DoMulti returns one result for each command, in order, and when the connection fails inside a batch it keeps the results that were read and gives the error to the others. valkey-go does that only when it pipelines in the background, so create the client with ClientOption.AlwaysPipelining (and not DisableAutoPipelining): on its synchronous path, which it takes for a call that is alone on a connection, a failure replaces every result of the batch with the error, and the provider then answers the whole batch Unknown (the safe direction, but the answered lookups are lost). Dial sets both.

type Counters

type Counters = redissegment.Counters

Counters is an Observer that counts with atomics.

type Layout

type Layout = redissegment.Layout

Layout is how the members of a segment are stored.

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 the error of a call that could not answer all its lookups. It holds the class and the counts only.

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, for errors.Is.

type MissingKey

type MissingKey = redissegment.MissingKey

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

type Observation

type Observation = redissegment.Observation

Observation describes one call of Contains.

type Observer

type Observer = redissegment.Observer

Observer receives one Observation per call of Contains that reached the provider.

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. Unset (nil) means on, except for a client that [Dial] creates with
	// replica reads (ClientOption.SendToReplicas or ReplicaOnly): then off, with one INFO line to Logger. On, with
	// MissingUnknown, a set segment sends MULTI, EXISTS, SMISMEMBER and EXEC in one batch, so a set that is removed
	// or expires during the call is missing for both commands. Off, it sends EXISTS and SMISMEMBER outside a
	// transaction: fewer commands, and a set that disappears between them can answer not-a-member for a former
	// member. It has no effect with MissingNotMember (no existence check is sent). A transaction goes to the primary,
	// never to a replica: an explicit true with replica reads moves the set lookups there. [New] cannot see the
	// replica reads of its client: it defaults to on.
	Atomic *bool
	// Logger (optional) receives the INFO line of the replica default of Atomic. Nil discards.
	Logger *slog.Logger
	// 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
	// Pipelining is PipeliningAlways (default) or PipeliningAuto: see their documentation.
	Pipelining Pipelining
	// MaxIDBytes is the longest id, in bytes, that the provider looks up. A longer id stays Unknown and is not sent.
	// Zero means DefaultMaxIDBytes.
	MaxIDBytes int
	// Timeout bounds one call, under the deadline of the caller. Zero means DefaultTimeout.
	Timeout time.Duration
	// BlockingPipeline is the number of commands of one call from which valkey-go moves the call to a dedicated
	// connection, where a cancel waits for the connection to close. Zero (default) means never: a call of any size
	// stays on the shared connection. A positive value is valkey-go's own threshold.
	BlockingPipeline int
	// ConnWriteTimeout is the read and write timeout of each connection of the client (valkey-go
	// ClientOption.ConnWriteTimeout). It bounds each command of the connection and the handshake that opens it
	// (valkey-go has no separate handshake timeout; the dial timeout can end the handshake sooner). It also ends the
	// wait of a call behind a peer that stopped reading until the ring of the connection is full, which the call
	// timeout does not. Zero keeps the ConnWriteTimeout of the client option, and when that is zero too uses
	// DefaultConnWriteTimeout(Timeout). Otherwise it is from MinConnWriteTimeout to MaxConnWriteTimeout.
	ConnWriteTimeout time.Duration
	// Retry lets valkey-go send a read again after a network error. Default false: a retry runs behind the call
	// timeout of the provider and sends the lookups twice.
	Retry bool
}

Options configures a Provider. Pipelining, BlockingPipeline, Retry and ConnWriteTimeout configure the client that Dial creates; New ignores them and does not check them.

type OwnedClient

type OwnedClient interface {
	Client
	Close()
}

OwnedClient is a Client that the provider closes: see NewOwning.

type Pipelining

type Pipelining string

Pipelining is how the valkey-go client sends the commands of a call. It only applies to a client that Dial creates. The names are the ones of the relay proxy configuration.

const (
	// PipeliningAlways (default) pipelines in the background even for a call that is alone on a connection. A
	// connection that fails inside a batch keeps the replies already read (the others are Unknown), and a cancel of
	// the caller ends the call at once. Exposed to the unsolicited-reply panic of valkey-go (see the package doc).
	PipeliningAlways Pipelining = "always"
	// PipeliningAuto is the default of valkey-go: a call that is alone on a connection is written and read
	// synchronously, and the background reader starts under concurrent load. A transport failure inside a batch
	// loses the whole batch (all Unknown), and a cancel is seen only when the deadline of the call passes: a reply
	// that arrives after the cancel and before the deadline is returned as the answer (a correct one). Alone on a
	// connection it is not exposed to the unsolicited-reply panic; under concurrent load it is.
	PipeliningAuto Pipelining = "auto"
)

type Provider

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

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

func Dial

func Dial(clientOpt *valkey.ClientOption, opts *Options) (*Provider, error)

Dial creates a valkey-go client from clientOpt and the client settings of opts (Pipelining, Retry and BlockingPipeline; their defaults are the safe ones) and returns a Provider that owns it: Close closes the client. The settings override the same fields of clientOpt: see Options for what each one trades.

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.

func NewOwning

func NewOwning(client OwnedClient, opts *Options) (*Provider, error)

NewOwning is New for a client that the provider owns: Close and Shutdown close it, in the background, so that a close that hangs never holds the caller past its deadline. Dial uses it.

func (*Provider) AtomicExistence

func (p *Provider) AtomicExistence() bool

AtomicExistence implements segment.AtomicExistencer: true when missingKey is unknown and the check is on (Options.Atomic), so the EXISTS and the SMISMEMBER of a set are one MULTI/EXEC. With missingKey notMember no existence check is sent and it is false.

func (*Provider) Close

func (p *Provider) Close()

Close closes the client when the provider owns it (see Dial) and does nothing otherwise. It waits for the close. It is safe to call more than once. Use Shutdown for a close that is bound by a deadline.

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 DoMulti 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 the others, on the keys of the configured namespaces (at most MaxInitProbes of them). 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, streamed as they arrive. The client never sends SSCAN to a replica (see Dial). 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). The close runs in the background: Shutdown returns the error of ctx when ctx ends first, in the wait for the calls or in the close, and the late close ends by itself. When ctx ends first it ends the calls in flight: 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), 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 = redissegment.SegmentOptions

SegmentOptions says where the members of one segment are.

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