segmentadmin

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: 24 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 segmentadmin is the write side of the dynamic segments: the code that loads members into a Valkey or Redis store, the counterpart of the read side in valkeysegment and redissegment. It holds the Store interface (one implementation for valkey-go, one for go-redis), the streaming import with its atomic swap, the small edits and the statistics of a segment.

A member is stored as resolver.NormalizeID returns it and under the key that redissegment.DefaultKey (or the key of the definition) names, which are the functions the relay uses for a lookup: the two sides cannot drift. No member id is ever put in an error or a report: only counts and line numbers are.

Index

Constants

View Source
const (
	// DefaultBatchSize is the members of one SADD when ImportOptions.BatchSize is zero.
	DefaultBatchSize = 1000
	// MaxBatchSize is the most members of one SADD: a batch is one command that the server runs alone.
	MaxBatchSize = 100_000
	// DefaultTempTTL is the life of the temporary key when ImportOptions.TempTTL is zero.
	DefaultTempTTL = time.Hour

	// DelWarnMembers is the size of a replaced set above which a DEL (the fallback of a server without UNLINK) may
	// block the server for a noticeable time, and the report says so.
	DelWarnMembers = 100_000
)

The bounds of an import.

View Source
const (
	// MinSyncInterval and MaxSyncInterval bound SyncOptions.Interval.
	MinSyncInterval = time.Second
	MaxSyncInterval = 24 * time.Hour
)

The bounds of the interval of a sync, and of the pause after failures.

View Source
const DefaultMaxLineBytes = 64 << 10

DefaultMaxLineBytes is the longest line that is read when ReaderOptions.MaxLineBytes is zero.

View Source
const DefaultMaxObjects = 1000

DefaultMaxObjects is the most objects of a prefix that an import reads when no bound is given.

View Source
const DefaultScanLimit = 100_000

DefaultScanLimit is the most keys that Stat counts of a keys layout segment.

View Source
const DefaultSyncInterval = time.Minute

DefaultSyncInterval is the pause between two checks of a source.

Variables

View Source
var (
	// ErrObjectURL is returned for a source that is not s3://bucket/key or s3://bucket/prefix/.
	ErrObjectURL = errors.New(
		"the source must be s3://<bucket>/<key>, or s3://<bucket>/<prefix>/ for every object under it",
	)
	// ErrObjectMissing is returned when the object of a source does not exist.
	ErrObjectMissing = errors.New("the source object does not exist")
	// ErrObjectChanged is returned by [ObjectAPI.Get] when the ETag no longer matches: the object was replaced.
	ErrObjectChanged = errors.New("the source object changed while it was read")
	// ErrTooManyObjects is returned when a prefix holds more objects than the bound: nothing is read.
	ErrTooManyObjects = errors.New("the prefix holds more objects than --max-objects")
	// ErrNoETag is returned when the store gives an object no ETag: a change cannot be detected without it.
	ErrNoETag = errors.New("the store returned no ETag; change detection needs it")
	// ErrSourceChanged is returned when the objects of a source are not the ones that were listed when the run began:
	// nothing is swapped, and the next run starts again.
	ErrSourceChanged = errors.New("the source changed while it was read: nothing was swapped")
)
View Source
var (
	// ErrEmptyInput is returned by an import that read no valid id, unless AllowEmpty is set: swapping it in would
	// wipe the segment.
	ErrEmptyInput = errors.New(
		"the input holds no valid id: an empty import would wipe the segment (use --allow-empty)",
	)
	// ErrKeysLayout is returned by an import of a segment with the keys layout: there is no single key to swap, and
	// the other protocols leave a half built segment visible to the relay.
	ErrKeysLayout = errors.New("import needs the set layout: the keys layout has no atomic swap (use add and remove)")
	// ErrTempGone is returned when the temporary key is gone before the swap (it expired or was removed): nothing
	// was swapped.
	ErrTempGone = errors.New("the temporary key is gone before the swap: raise --temp-ttl")
	// ErrIncomplete is returned when the temporary key does not hold what the run wrote (it expired and was
	// recreated, or changed): nothing was swapped.
	ErrIncomplete = errors.New("the temporary key does not hold the members that were written: nothing was swapped")
	// ErrLockLost is returned when another run holds the lock when this one writes or swaps (the lock expired):
	// nothing was swapped.
	ErrLockLost = errors.New("the import lock is held by another run: nothing was swapped")
	// ErrImportRunning is returned when another import of the segment holds the lock. A lock that a dead run left
	// expires after its ttl.
	ErrImportRunning = errors.New("another import of this segment is running (a dead run's lock expires by its ttl)")
	// ErrPartial is returned when an add or a remove applied only a part of the ids, or may have applied a batch whose
	// reply was lost. The version key was bumped (or the error says that it could not be).
	ErrPartial = errors.New("partially or possibly applied")
	// ErrSwapUnknown is returned when the swap was sent and no definite answer came back: the live set may or may not
	// be the new one.
	ErrSwapUnknown = errors.New("swap state unknown: run `semaphore-cli segment stat`, then import again")
	// ErrNotBumped is returned when the swap worked and the version key could not be bumped.
	ErrNotBumped = errors.New("set replaced, version not bumped: run `semaphore-cli segment bump` with the same flags")
	// ErrKeyOverlap is returned when a key that an import of the segment derives (its lock, its temporary keys) can be
	// the key of another segment, or when the keys of two segments are the same.
	ErrKeyOverlap = errors.New("the keys of the segments overlap")
	// ErrUnsupportedClient is returned for a go-redis client that is neither a node nor a cluster: it cannot be scanned.
	ErrUnsupportedClient = errors.New("the client cannot be scanned")
	// ErrNoSlotTag is returned for a key that cannot get a temporary key in its cluster slot.
	ErrNoSlotTag = errors.New("the key has a hash tag that cannot be shared by a temporary key")
	// ErrBadOptions is returned for options out of their bounds.
	ErrBadOptions = errors.New("invalid options")
	// ErrSwapped is returned when the swap worked and a later step did not: the segment is the new one.
	ErrSwapped = errors.New("the change is in the store, but a later step failed")
	// ErrStore is the root of the errors of a store command. The command is named, never its arguments.
	ErrStore = errors.New("segment store")
)

Functions

func Bump

func Bump(ctx context.Context, store Store, target *Target, rep *Report) error

Bump writes a new version to the version key of the target, when it has one, and records it in rep. The value is the time, a dot and 16 random hex characters, so that two bumps never write the same value (a frozen or coarse clock, two hosts at the same instant): a relay that compares the token always sees a change.

func BumpWithRetry

func BumpWithRetry(
	ctx context.Context, store Store, target *Target, rep *Report, wait func(context.Context, time.Duration) error,
) error

BumpWithRetry is Bump with three tries and a pause between them (wait nil means a timer). When it gives up, the error is ErrNotBumped: the change is in the store and the relays have not been told.

func CheckKeys

func CheckKeys(target, other *Target) error

CheckKeys refuses two segments whose keys can meet: an import of one writes and removes keys under `<key>:import:` (and `{<key>}:import:` for a key without a hash tag), so no key of the other segment (its set, its version key, the prefix of its member keys) may be one of them, and the two segments may not share a set or a prefix. The check is made both ways.

func IsNoSuchKey

func IsNoSuchKey(err error) bool

IsNoSuchKey tells whether a server error is the one of RENAME of a missing key.

func IsUnknownCommand

func IsUnknownCommand(err error) bool

IsUnknownCommand tells whether a server error says that the command does not exist.

func ScanPattern

func ScanPattern(prefix string) string

ScanPattern is the SCAN MATCH pattern of the keys that start with prefix.

func Slot

func Slot(key string) int

Slot is the cluster slot of a key: CRC16 (XMODEM) of its hash tag, or of the key, modulo 16384.

func Sync

func Sync(ctx context.Context, store Store, target *Target, src *ObjectSource, opts *SyncOptions) error

Sync runs rounds until ctx ends. A round that fails keeps the live set, and the next one comes after a longer pause (the interval doubled for each failure in a row, up to sixteen intervals and never above MaxSyncInterval); any other round is followed by the interval. It returns when ctx ends: the round in flight has stopped before its swap, or finished it. The error is a bad option.

func WithContext

func WithContext(ctx context.Context, src io.Reader) io.Reader

WithContext returns a reader of src whose Read returns the error of ctx as soon as ctx ends, even when src blocks (a pipe that no one closes). The read of src that is still in flight ends when src gives a value or is closed.

Types

type Commit

type Commit struct {
	// Lock, Tmp, Live and Old are the keys. Committed holds the token of the run once its swap is applied, so that
	// a second call with the same token (after a lost reply) is answered AlreadyCommitted.
	Lock, Tmp, Live, Old, Committed string
	// Source is the key that holds the fingerprint of the input, in the slot of the live key.
	Source string
	// Token is the token of the run.
	Token string
	// Fingerprint is the fingerprint of the input that the new set was built from. It is stored in the key Source in
	// the step of the swap; empty removes the key (the set no longer comes from a source that was fingerprinted).
	Fingerprint string
	// Want is the least cardinality that the temporary key must have: the members that the run saw added (a batch
	// that was sent twice counts once, so the key may hold more).
	Want int64
	// OldTTL is the expiry of the replaced set.
	OldTTL time.Duration
	// Empty is the explicit empty import: the live key is removed, if the lock still holds the token.
	Empty bool
}

Commit is the conditional swap of an import. Every key must be in one cluster slot.

type CommitResult

type CommitResult int

CommitResult is what the conditional swap did.

const (
	// Committed means that the new set is live.
	Committed CommitResult = iota
	// LockLost means that the lock did not hold the token of the run: nothing changed.
	LockLost
	// TempGone means that the temporary key does not exist: nothing changed.
	TempGone
	// CountMismatch means that the temporary key holds fewer members than were written: nothing changed.
	CountMismatch
	// AlreadyCommitted means that this run's swap was applied before (the reply of the first call was lost): the new
	// set is live.
	AlreadyCommitted
)

type EditOptions

type EditOptions struct {
	// Wait pauses between the tries of the version bump. Nil means a timer.
	Wait func(ctx context.Context, delay time.Duration) error
	// BatchSize is the ids of one command. Zero means [DefaultBatchSize].
	BatchSize int
}

EditOptions set how an add or a remove runs.

type Format

type Format string

Format is how the input of an import is laid out.

const (
	// FormatLines is one id for each line.
	FormatLines Format = "lines"
	// FormatCSV is one record for each line: the id is a column of it.
	FormatCSV Format = "csv"
)

type ImportOptions

type ImportOptions struct {
	// Wait pauses between the tries of a step that may have lost its reply. Nil means a timer. A test injects one that
	// returns at once.
	Wait func(ctx context.Context, delay time.Duration) error
	// Token identifies the run in the lock and in the name of its temporary key. Empty means a random token.
	Token string
	// Fingerprint identifies the input (see [ObjectSource.Fingerprint]). The swap records it in the key
	// [RunKeys.Source] in the same step, so the record is there exactly when the set is live. Empty means an input
	// without one (a file, standard input): the swap removes the record of an older input.
	Fingerprint string
	// BatchSize is the members of one batch. Zero means [DefaultBatchSize].
	BatchSize int
	// TempTTL is the life of the temporary key and of the lock, refreshed by every batch. Zero means [DefaultTempTTL];
	// the least is one second.
	TempTTL time.Duration
	// AllowEmpty lets an input without a valid id empty the segment.
	AllowEmpty bool
	// DryRun reads and validates the input and writes nothing.
	DryRun bool
}

ImportOptions set how an import runs.

type Inspector

type Inspector interface {
	// Value reads a string key; ok is false when it does not exist.
	Value(ctx context.Context, key string) (value string, ok bool, err error)
	// SCard is the cardinality of a set, zero for a missing key.
	SCard(ctx context.Context, key string) (int64, error)
	// KeyTTL tells whether the key exists and, when it expires, in how long (zero: never).
	KeyTTL(ctx context.Context, key string) (exists bool, ttl time.Duration, err error)
	// CountKeys counts the keys that start with prefix, with SCAN, and stops at limit: more is true when it did.
	CountKeys(ctx context.Context, prefix string, limit int) (count int, more bool, err error)
}

Inspector is the commands that read a segment.

type KeyCounter

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

KeyCounter counts distinct keys, which a SCAN may return more than once, in memory bounded by its limit.

func NewKeyCounter

func NewKeyCounter(limit int) *KeyCounter

NewKeyCounter returns a counter that keeps at most limit keys.

func (*KeyCounter) Add

func (c *KeyCounter) Add(keys []string) bool

Add counts the keys and tells whether the counter is full: a key beyond the limit is not kept, and More is true.

func (*KeyCounter) Count

func (c *KeyCounter) Count() int

Count is the distinct keys that were kept.

func (*KeyCounter) More

func (c *KeyCounter) More() bool

More tells that a key beyond the limit was seen.

type Locker

type Locker interface {
	// Lock takes the lock key with the token for ttl and tells whether it is the run's: it is idempotent by the token,
	// so a call whose reply was lost can be sent again (a lock that holds this token is answered true).
	Lock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
	// Claim, if, and only if, the lock holds the token, removes the temporary key of a dead run (stale, may be empty)
	// and records the name of the temporary key of this run in the last key. It tells whether the lock held.
	Claim(ctx context.Context, lock, last, stale, tmp, token string) (bool, error)
	// Unlock removes the lock and the last key if, and only if, the lock still holds the token, and the committed key
	// if it holds the token.
	Unlock(ctx context.Context, lock, last, committed, token string) error
	// StageAdd adds members to the temporary key, and refreshes its expiry and the one of the lock, if, and only if,
	// the lock holds the token. Only the first batch (first is true) may create the temporary key; a later batch that
	// finds it missing writes nothing. A batch can be sent again: the members are a set.
	StageAdd(ctx context.Context, lock, tmp, token string, members []string, ttl time.Duration, first bool) (
		added int64, result StageResult, err error)
	// EditSet adds members to (or removes them from) the live set, if, and only if, no import holds the lock; locked
	// is true when one does, and nothing was written. It is one step on the server.
	EditSet(
		ctx context.Context,
		lock, key string,
		members []string,
		remove bool,
	) (changed int64, locked bool, err error)
	// Commit swaps in one step on the server: if the lock holds the token, the temporary key exists and has Want
	// members, the live key moves to Old (with its expiry), the temporary key becomes the live key and loses its
	// expiry. Otherwise nothing changes. The fingerprint is recorded in the same step. fellBack is true when the
	// empty path had to use DEL.
	Commit(ctx context.Context, commit *Commit) (result CommitResult, fellBack bool, err error)
}

Locker is the commands of the lock and of the conditional swap of an import.

type Mutator

type Mutator interface {
	// SAdd adds members to a set and returns how many were new. With ttl > 0 it sets the expiry of the key in the same
	// pipeline, so that every batch refreshes it.
	SAdd(ctx context.Context, key string, members []string, ttl time.Duration) (int64, error)
	// SRem removes members from a set and returns how many were there.
	SRem(ctx context.Context, key string, members []string) (int64, error)
	// SetKeys creates the keys (one key for each member of the keys layout) and returns how many were new.
	SetKeys(ctx context.Context, keys []string) (int64, error)
	// Unlink removes keys without blocking the server (UNLINK) and returns how many existed. A server that has no
	// UNLINK is sent DEL, and fellBack says so.
	Unlink(ctx context.Context, keys ...string) (removed int64, fellBack bool, err error)
	// SetValue sets a string key.
	SetValue(ctx context.Context, key, value string) error
}

Mutator is the commands that change a segment. Every method takes the keys it touches as they are; a method that takes several keys of a cluster sends one command for each.

type Object

type Object struct {
	// Body is the content; the caller closes it.
	Body io.ReadCloser
	// Size is the length that the server announced, zero or less when it did not.
	Size int64
	// Gzip tells that Content-Encoding is gzip.
	Gzip bool
}

Object is the answer of a GET.

type ObjectAPI

type ObjectAPI interface {
	// Head returns the object, or [ErrObjectMissing].
	Head(ctx context.Context, key string) (ObjectInfo, error)
	// List returns a page of the objects under prefix, in key order. An empty token starts the listing.
	List(ctx context.Context, prefix, token string) (ObjectPage, error)
	// Get streams an object of one ETag (If-Match): when the object has another one, the answer is
	// [ErrObjectChanged]. The body is read as it arrives, never held whole.
	Get(ctx context.Context, key, etag string) (Object, error)
}

ObjectAPI is the bucket that holds the objects of a source, as the code needs it. The adapter of a client library implements it; a test injects a fake. The bucket is part of the implementation.

type ObjectInfo

type ObjectInfo struct {
	// Key is the key of the object.
	Key string
	// ETag is the validator of the content.
	ETag string
	// Size is the size of the stored bytes.
	Size int64
}

ObjectInfo is what a listing or a HEAD says about an object.

type ObjectPage

type ObjectPage struct {
	// Next is the token of the next page, empty on the last.
	Next string
	// Objects are the objects of the page, in key order.
	Objects []ObjectInfo
}

ObjectPage is one page of a listing.

type ObjectRef

type ObjectRef struct {
	// Bucket is the bucket of the URL.
	Bucket string
	// Key is the key of the object, or the prefix of the objects.
	Key string
	// Prefix tells that Key is a prefix (the URL ends with a slash): every object under it is read.
	Prefix bool
}

ObjectRef names the object, or the prefix of the objects, of a source.

func ParseObjectURL

func ParseObjectURL(raw string) (ObjectRef, error)

ParseObjectURL reads s3://bucket/key and s3://bucket/prefix/.

type ObjectSource

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

ObjectSource is the objects of one source URL.

func NewObjectSource

func NewObjectSource(api ObjectAPI, ref ObjectRef, maxObjects int) *ObjectSource

NewObjectSource returns the source of ref in the bucket of api. A prefix may hold maxObjects objects at most (zero means DefaultMaxObjects).

func (*ObjectSource) Fingerprint

func (s *ObjectSource) Fingerprint(ctx context.Context) (string, error)

Fingerprint is the identity of the content of the source: one object (HEAD), or the keys and ETags of the listing of a prefix, hashed into one value. It reads no content.

func (*ObjectSource) Open

func (s *ObjectSource) Open(ctx context.Context, want string, opts ReaderOptions) (*ObjectStream, error)

Open lists the source and starts a stream of its objects, one after the other, with a line break between two of them. With a non-empty want, a listing that has another fingerprint is ErrSourceChanged. The stream is a Source; it checks at its end that the listing still has the fingerprint, and it fails when it does not.

type ObjectStream

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

ObjectStream is the ids of the objects of a source.

func (*ObjectStream) Close

func (s *ObjectStream) Close() error

Close closes the object that is open.

func (*ObjectStream) Fingerprint

func (s *ObjectStream) Fingerprint() string

Fingerprint is the fingerprint of the listing that the stream reads.

func (*ObjectStream) Next

func (s *ObjectStream) Next() (Record, error)

Next implements Source. At the end it checks that no object was added, replaced or removed meanwhile.

func (*ObjectStream) Objects

func (s *ObjectStream) Objects() int

Objects is how many objects the stream reads.

type Outcome

type Outcome string

Outcome is how a round of a sync ended.

const (
	// OutcomeUnchanged means that the source has the fingerprint of the live set: nothing was written.
	OutcomeUnchanged Outcome = "unchanged"
	// OutcomeChanged means that the source was imported.
	OutcomeChanged Outcome = "changed"
	// OutcomeSkipped means that another import holds the lock: this round did nothing.
	OutcomeSkipped Outcome = "skipped"
	// OutcomeFailed means that the check or the import failed: the live set is what it was.
	OutcomeFailed Outcome = "failed"
	// OutcomeStopped means that the context ended during the round: the live set is what it was, or the new one.
	OutcomeStopped Outcome = "stopped"
)

type Reader

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

Reader streams the ids of an input. It holds one line at a time. A source of an import (a file, standard input, later an object of a bucket) is anything that gives an io.Reader.

func NewReader

func NewReader(src io.Reader, opts ReaderOptions) (*Reader, error)

NewReader returns a Reader of src.

func (*Reader) Next

func (r *Reader) Next() (Record, error)

Next returns the next line of the input. A line is read whole or rejected: a long line is skipped to its end without being held. It returns io.EOF at the end of the input.

type ReaderOptions

type ReaderOptions struct {
	// Format is FormatLines (default) or FormatCSV.
	Format Format
	// Column is the 1-based column of the id of a CSV record. Zero means the first.
	Column int
	// MaxLineBytes bounds a line; a longer one is rejected, not buffered. Zero means [DefaultMaxLineBytes].
	MaxLineBytes int
}

ReaderOptions set how an input is read.

type Reason

type Reason string

Reason is why a line was not taken as an id. The counts of the reasons are reported, never the lines.

const (
	// ReasonEmpty is a line (or column) with no id, or an id that is empty once normalised.
	ReasonEmpty Reason = "empty"
	// ReasonTooLong is a line longer than the limit, or an id longer than the longest id that the relay looks up.
	ReasonTooLong Reason = "tooLong"
	// ReasonInvalid is an id that is not valid UTF-8 under a normalising segment.
	ReasonInvalid Reason = "invalid"
	// ReasonColumn is a CSV record with no such column, or that is not valid CSV.
	ReasonColumn Reason = "column"
)

type Record

type Record struct {
	// ID is the id as written, not yet normalised. Empty when Reason is set.
	ID string
	// Reason is why the line holds no id, empty for an id.
	Reason Reason
	// Line is the 1-based number of the line.
	Line int
}

Record is one line of an input.

type RedisStore

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

RedisStore is a Store over go-redis: a single node or a cluster.

func NewRedis

func NewRedis(client redis.UniversalClient) *RedisStore

NewRedis returns a Store over a go-redis client. Close closes the client.

func (*RedisStore) Claim

func (s *RedisStore) Claim(ctx context.Context, lock, last, stale, tmp, token string) (bool, error)

Claim implements Store.

func (*RedisStore) Close

func (s *RedisStore) Close()

Close implements Store.

func (*RedisStore) Commit

func (s *RedisStore) Commit(ctx context.Context, commit *Commit) (CommitResult, bool, error)

Commit implements Store.

func (*RedisStore) CountKeys

func (s *RedisStore) CountKeys(ctx context.Context, prefix string, limit int) (int, bool, error)

CountKeys implements Store.

func (*RedisStore) EditSet

func (s *RedisStore) EditSet(
	ctx context.Context, lock, key string, members []string, remove bool,
) (int64, bool, error)

EditSet implements Store.

func (*RedisStore) KeyTTL

func (s *RedisStore) KeyTTL(ctx context.Context, key string) (bool, time.Duration, error)

KeyTTL implements Store.

func (*RedisStore) Lock

func (s *RedisStore) Lock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)

Lock implements Store.

func (*RedisStore) Ping

func (s *RedisStore) Ping(ctx context.Context) error

Ping implements Store.

func (*RedisStore) SAdd

func (s *RedisStore) SAdd(ctx context.Context, key string, members []string, ttl time.Duration) (int64, error)

SAdd implements Store.

func (*RedisStore) SCard

func (s *RedisStore) SCard(ctx context.Context, key string) (int64, error)

SCard implements Store.

func (*RedisStore) SRem

func (s *RedisStore) SRem(ctx context.Context, key string, members []string) (int64, error)

SRem implements Store.

func (*RedisStore) SetKeys

func (s *RedisStore) SetKeys(ctx context.Context, keys []string) (int64, error)

SetKeys implements Store.

func (*RedisStore) SetValue

func (s *RedisStore) SetValue(ctx context.Context, key, value string) error

SetValue implements Store.

func (*RedisStore) StageAdd

func (s *RedisStore) StageAdd(
	ctx context.Context, lock, tmp, token string, members []string, ttl time.Duration, first bool,
) (int64, StageResult, error)

StageAdd implements Store.

func (s *RedisStore) Unlink(ctx context.Context, keys ...string) (int64, bool, error)

Unlink implements Store.

func (*RedisStore) Unlock

func (s *RedisStore) Unlock(ctx context.Context, lock, last, committed, token string) error

Unlock implements Store.

func (*RedisStore) Value

func (s *RedisStore) Value(ctx context.Context, key string) (string, bool, error)

Value implements Store.

type Rejections

type Rejections struct {
	// Empty counts the lines with no id.
	Empty int64
	// TooLong counts the lines or ids over the limit.
	TooLong int64
	// Invalid counts the ids that are not valid UTF-8 under a normalising segment.
	Invalid int64
	// Column counts the CSV records with no such column.
	Column int64
}

Rejections counts the lines that were not an id, by reason.

func (*Rejections) Add

func (r *Rejections) Add(reason Reason)

Add counts one rejected line.

type Report

type Report struct {
	// Version is the value written to the version key, empty when none was.
	Version string
	// Rejected counts the lines that are not an id, by reason.
	Rejected Rejections
	// Read is the lines read.
	Read int64
	// Applied is the ids that an add or a remove sent to the store, whatever they changed.
	Applied int64
	// Accepted is the lines that are an id.
	Accepted int64
	// Added is the distinct ids written (zero for a dry run).
	Added int64
	// Removed is the ids that a remove took out of the segment.
	Removed int64
	// Duplicates is the accepted ids that were already in the input (zero for a dry run, and not exact when
	// DuplicatesUnknown).
	Duplicates int64
	// Swapped tells that the new set is live.
	Swapped bool
	// DuplicatesUnknown tells that a batch was sent again after a lost reply, so that the count of new members, and
	// the duplicates that follow from it, are not exact.
	DuplicatesUnknown bool
	// FallbackLarge tells that DEL (no UNLINK on the server) removed a set above [DelWarnMembers]: it may have blocked.
	FallbackLarge bool
	// CleanupFailed tells that the temporary key could not be removed after a failure: it expires.
	CleanupFailed bool
	// FellBackToDel tells that the server has no UNLINK and DEL removed the old set.
	FellBackToDel bool
	// DryRun tells that nothing was written.
	DryRun bool
}

Report is what an import did. It holds counts only, never an id.

func Edit

func Edit(
	ctx context.Context,
	store Store,
	target *Target,
	src Source,
	remove bool,
	opts EditOptions,
) (*Report, error)

Edit adds the ids of src to the segment (or removes them), in batches, then bumps the version key. Add and remove are for small edits of the live key: there is no temporary key and no swap. An edit of a set is refused while an import holds the lock (the check and the write are one step on the server), because the swap would lose it.

When a failure or the end of the context stops the edit after a batch was sent (a lost reply may hide that it was applied), the version key is still bumped, on a context of its own, so that the relays see what may have been applied, and the error says how much was confirmed: ErrPartial.

func Import

func Import(ctx context.Context, store Store, target *Target, src Source, opts ImportOptions) (*Report, error)

Import loads the ids of src into the set of the segment and swaps it in. It is safe by construction:

  • One import of a segment runs at a time: a lock key takes the token of the run (SET NX PX). A second run fails at once with ErrImportRunning. The lock and the temporary key are refreshed by every batch, in a script that checks the token, and removed at the end only if the token is still the run's.
  • The temporary key has the token in its name, so nothing else can share or recreate it. The key records its name in a last key, so that the next run removes exactly the key of a dead run, without a scan.
  • The swap is one script on the server: it moves the live key only if the lock holds the token, the temporary key exists and holds exactly the number of members that the run wrote. Otherwise nothing changes.

The order is: fill, swap, bump the version key, remove the old set without blocking.

type Round

type Round struct {
	// Err is why the round failed or was stopped, nil for the other outcomes.
	Err error
	// Report is the import of a changed or failed round, nil when none ran.
	Report *Report
	// Outcome is how the round ended.
	Outcome Outcome
}

Round is the result of one round.

func SyncRound

func SyncRound(
	ctx context.Context, store Store, target *Target, src *ObjectSource, opts *SyncOptions,
) Round

SyncRound checks the source once and imports it when it changed. The fingerprint of the source that is recorded next to the live set is compared first, with one read and no write; an import writes the new fingerprint in the step of its swap, so a crash can neither skip a change nor leave a fingerprint that does not describe the live set.

type RunKeys

type RunKeys struct {
	// Lock holds the token of the run that may import the segment.
	Lock string
	// Last holds the name of the temporary key of the run that holds the lock, so that the next run removes exactly
	// that key when the run died (no SCAN, no KEYS).
	Last string
	// Committed holds the token of the run whose swap was applied.
	Committed string
	// Source holds the fingerprint of the input that the live set was last imported from.
	Source string
	// Tmp is filled by the run; its name holds the token of the run, so nothing else can recreate or share it.
	Tmp string
	// Old holds the replaced set until it is removed.
	Old string
	// contains filtered or unexported fields
}

RunKeys are the keys of one import. All are in the cluster slot of the live key, which the script of the swap needs.

func ImportKeys

func ImportKeys(live, token string) (RunKeys, error)

ImportKeys returns the keys of the run of an import with a token. They keep the hash tag of the live key, or, when the live key has none, wrap the live key in one (which hashes like the key). A key whose tag cannot be shared is refused.

func (*RunKeys) Owns

func (k *RunKeys) Owns(key string) bool

Owns tells whether a key is one that an import of the segment names (a leftover of a dead run).

type SliceSource

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

SliceSource is the ids of the command line: each one is a record, never joined with the others.

func NewSliceSource

func NewSliceSource(ids []string) *SliceSource

NewSliceSource returns a Source of ids that are already separated.

func (*SliceSource) Next

func (s *SliceSource) Next() (Record, error)

Next implements Source.

type Source

type Source interface {
	// Next returns the next record.
	Next() (Record, error)
}

Source gives the lines of an input one at a time, and io.EOF at the end. A file, standard input and the ids of the command line (and later an object of a bucket) are sources.

type StageResult

type StageResult int

StageResult is what a batch of the temporary key did.

const (
	// Staged means that the batch was written.
	Staged StageResult = iota
	// StageLockLost means that the lock did not hold the token: nothing was written.
	StageLockLost
	// StageTempGone means that a batch after the first found no temporary key (it expired or was removed): nothing
	// was written, because recreating it would hide the members that are lost.
	StageTempGone
)

type Stats

type Stats struct {
	Version    string
	Count      int64
	TTL        time.Duration
	LockTTL    time.Duration
	Exists     bool
	AtLeast    bool
	HasVersion bool
	LockHeld   bool
}

Stats is what Stat tells of a segment.

func Stat

func Stat(ctx context.Context, store Store, target *Target, scanLimit int) (*Stats, error)

Stat reads the existence, the cardinality, the version and the ttl of a segment. A keys layout segment is counted by SCAN, up to scanLimit keys (zero means DefaultScanLimit).

type Store

type Store interface {
	Mutator
	Inspector
	Locker
	// Ping checks the connection.
	Ping(ctx context.Context) error
	// Close releases the client.
	Close()
}

Store is the write side of a segment store. An implementation exists for each client library.

type SyncOptions

type SyncOptions struct {
	// Log gets one line for each round (counts only, never an id). Nil logs nothing.
	Log *slog.Logger
	// Wait pauses between rounds. Nil means a timer; a test injects one that returns at once.
	Wait func(ctx context.Context, delay time.Duration) error
	// Reader sets how the objects are read.
	Reader ReaderOptions
	// Import sets how the import of a changed source runs. Its Fingerprint is set by the round.
	Import ImportOptions
	// Interval is the pause between two rounds, from [MinSyncInterval] to [MaxSyncInterval]. Zero means
	// [DefaultSyncInterval].
	Interval time.Duration
}

SyncOptions set how a sync runs.

func (*SyncOptions) Validate

func (o *SyncOptions) Validate() error

Validate checks the interval.

type Target

type Target struct {
	// Name is the name of the segment (for messages).
	Name string
	// Key is the key of the set, or the prefix of the member keys.
	Key string
	// Layout is redissegment.LayoutSet (or empty) or redissegment.LayoutKeys.
	Layout redissegment.Layout
	// VersionKey is the key that the relay polls for a change, empty for none.
	VersionKey string
	// Normalize is the normalization of the ids that the relay applies before a lookup.
	Normalize resolver.Normalization
	// MaxIDBytes is the longest id that the relay looks up; a longer one is rejected. Zero means no bound.
	MaxIDBytes int
}

Target is a segment as its definition and the bootstrap file say it: the operator does not retype any of it.

type ValkeyStore

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

ValkeyStore is a Store over valkey-go: a single node, a sentinel set or a cluster.

func NewValkey

func NewValkey(client valkey.Client) *ValkeyStore

NewValkey returns a Store over a valkey-go client. Close closes the client.

func (*ValkeyStore) Claim

func (s *ValkeyStore) Claim(ctx context.Context, lock, last, stale, tmp, token string) (bool, error)

Claim implements Store.

func (*ValkeyStore) Close

func (s *ValkeyStore) Close()

Close implements Store.

func (*ValkeyStore) Commit

func (s *ValkeyStore) Commit(ctx context.Context, commit *Commit) (CommitResult, bool, error)

Commit implements Store.

func (*ValkeyStore) CountKeys

func (s *ValkeyStore) CountKeys(ctx context.Context, prefix string, limit int) (int, bool, error)

CountKeys implements Store.

func (*ValkeyStore) EditSet

func (s *ValkeyStore) EditSet(
	ctx context.Context, lock, key string, members []string, remove bool,
) (int64, bool, error)

EditSet implements Store.

func (*ValkeyStore) KeyTTL

func (s *ValkeyStore) KeyTTL(ctx context.Context, key string) (bool, time.Duration, error)

KeyTTL implements Store.

func (*ValkeyStore) Lock

func (s *ValkeyStore) Lock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)

Lock implements Store.

func (*ValkeyStore) Ping

func (s *ValkeyStore) Ping(ctx context.Context) error

Ping implements Store.

func (*ValkeyStore) SAdd

func (s *ValkeyStore) SAdd(ctx context.Context, key string, members []string, ttl time.Duration) (int64, error)

SAdd implements Store.

func (*ValkeyStore) SCard

func (s *ValkeyStore) SCard(ctx context.Context, key string) (int64, error)

SCard implements Store.

func (*ValkeyStore) SRem

func (s *ValkeyStore) SRem(ctx context.Context, key string, members []string) (int64, error)

SRem implements Store.

func (*ValkeyStore) SetKeys

func (s *ValkeyStore) SetKeys(ctx context.Context, keys []string) (int64, error)

SetKeys implements Store.

func (*ValkeyStore) SetValue

func (s *ValkeyStore) SetValue(ctx context.Context, key, value string) error

SetValue implements Store.

func (*ValkeyStore) StageAdd

func (s *ValkeyStore) StageAdd(
	ctx context.Context, lock, tmp, token string, members []string, ttl time.Duration, first bool,
) (int64, StageResult, error)

StageAdd implements Store.

func (s *ValkeyStore) Unlink(ctx context.Context, keys ...string) (int64, bool, error)

Unlink implements Store.

func (*ValkeyStore) Unlock

func (s *ValkeyStore) Unlock(ctx context.Context, lock, last, committed, token string) error

Unlock implements Store.

func (*ValkeyStore) Value

func (s *ValkeyStore) Value(ctx context.Context, key string) (string, bool, error)

Value implements Store.

Directories

Path Synopsis
Package admintest holds an in-memory segmentadmin.Store with failure injection, for tests of the code that writes segments (the import and the commands of the CLI) that must not need a server.
Package admintest holds an in-memory segmentadmin.Store with failure injection, for tests of the code that writes segments (the import and the commands of the CLI) that must not need a server.

Jump to

Keyboard shortcuts

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