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
- Variables
- func DefaultKey(prefix, name string, layout Layout) string
- type Class
- type Client
- type Counters
- type Layout
- type LookupError
- type MissingKey
- type Observation
- type Observer
- type Options
- type Provider
- func (p *Provider) AtomicExistence() bool
- func (p *Provider) Capabilities() segment.Capabilities
- func (p *Provider) Close() error
- func (p *Provider) Contains(ctx context.Context, lookups []segment.Lookup) error
- func (p *Provider) Exists(ctx context.Context, names []string) ([]segment.State, error)
- func (p *Provider) Health() segment.Health
- func (p *Provider) Init(ctx context.Context) (err error)
- func (p *Provider) Members(ctx context.Context, name string) iter.Seq2[string, error]
- func (p *Provider) Shutdown(ctx context.Context) error
- func (p *Provider) Status() Status
- func (p *Provider) Version(ctx context.Context, name string) (string, error)
- type SegmentOptions
- type Stats
- type Status
Constants ¶
const ( ClassNone = redisproto.ClassNone ClassCanceled = redisproto.ClassCanceled ClassTimeout = redisproto.ClassTimeout ClassServer = redisproto.ClassServer ClassProtocol = redisproto.ClassProtocol )
The failure classes.
const ( // LayoutSet stores the members in one set (SMISMEMBER). LayoutSet = redisproto.LayoutSet // LayoutKeys stores one key per member (EXISTS). LayoutKeys = redisproto.LayoutKeys // MissingUnknown answers Unknown for a missing set key. MissingUnknown = redisproto.MissingUnknown // MissingNotMember answers NotMember for a missing set key. It is the default. MissingNotMember = redisproto.MissingNotMember // DefaultTimeout is the per-call timeout when Options.Timeout is zero. DefaultTimeout = redisproto.DefaultTimeout // DefaultKeyPrefix is the prefix of the keys of the segments when Options.KeyPrefix is empty. DefaultKeyPrefix = redisproto.DefaultKeyPrefix // DefaultMaxIDBytes is the longest id that is looked up when Options.MaxIDBytes is zero. DefaultMaxIDBytes = redisproto.DefaultMaxIDBytes // MaxIDsPerCommand is the most ids that one SMISMEMBER (or script) carries. MaxIDsPerCommand = redisproto.MaxIDsPerCommand // MaxInitProbes is the most namespaces that Init probes. MaxInitProbes = redisproto.MaxInitProbes // ScanCount is the COUNT hint of each SSCAN page of [Provider.Members]. ScanCount = redisproto.ScanCount // MaxScanPages is the most pages that one scan may take. MaxScanPages = redisproto.MaxScanPages )
const MinSocketTimeout = redisproto.MinSocketTimeout
MinSocketTimeout is the least positive read, write or dial timeout of a go-redis client that is accepted (see redisproto.MinSocketTimeout).
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.
const ScriptSHA = "4dc3e21a3a7ca911ad25145699dd3279464e74cf"
ScriptSHA is the SHA1 of Script, which EVALSHA names. A test pins it to the script.
Variables ¶
var ( // ErrCanceled is wrapped by a LookupError of ClassCanceled: the caller left. It matches [context.Canceled]. ErrCanceled = newContextError("redis segment: context ended", context.Canceled) // ErrTimeout is wrapped by a LookupError of ClassTimeout: the timeout of the provider passed. It matches // [context.DeadlineExceeded]. ErrTimeout = newContextError("redis segment: timeout", context.DeadlineExceeded) // ErrCallerDeadline is wrapped by a LookupError of ClassCanceled when the deadline of the caller passed: the // caller's affair, not a failure of the store. It matches [context.DeadlineExceeded], not ErrTimeout. ErrCallerDeadline = newContextError("redis segment: the deadline of the caller passed", context.DeadlineExceeded) 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") )
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 ¶
DefaultKey is the key of a segment whose definition names none, see redisproto.DefaultKey.
Types ¶
type Client ¶
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 = redisproto.Counters
Counters is an Observer that counts with atomics.
type LookupError ¶
type LookupError struct {
// Class is the most severe class among the failures of the call.
Class Class
// CallerDeadline tells that a ClassCanceled call ended because the deadline of the caller passed (not a cancel).
CallerDeadline bool
// 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) Unwrap ¶
func (e *LookupError) Unwrap() error
Unwrap returns the sentinel of the class, so errors.Is with ErrTimeout works.
type MissingKey ¶
type MissingKey = redisproto.MissingKey
MissingKey is what a lookup of a set segment becomes when the key of the set does not exist.
type Observation ¶
type Observation = redisproto.Observation
Observation describes one call of Contains.
type Observer ¶
type Observer = redisproto.Observer
Observer receives one Observation per call of Contains.
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 ¶
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 ¶
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) Capabilities ¶ added in v1.3.0
func (p *Provider) Capabilities() segment.Capabilities
Capabilities implements segment.Provider: the provider starts, stops and reports on its store, and answers the existence check of its segments.
func (*Provider) Close ¶
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 ¶
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 ¶
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 ¶
Health implements segment.HealthReporter.
func (*Provider) Init ¶
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 ¶
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 ¶
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) Version ¶
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 = redisproto.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.