relaycore

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 42 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 relaycore assembles the config v2 relay core from a loaded bootstrap file: the connections, the object store of the control plane, the cache directory, the polling flag source, the source that feeds the reconcile engine, the engine with its holder and evaluator, and the exporters and notifiers of the events package.

A Core is a service object: New builds everything and starts nothing, Core.Run runs the loops until its context ends or Core.Shutdown is called, and Core.Shutdown stops them in order and drains the events within the deadline of its context. The package has no global state, imports no HTTP code and registers no route: the handlers of the relay take the flagruntime.Holder and the flagruntime.Evaluator from the core.

Index

Constants

View Source
const (
	RejectedKept    = reloadstats.RejectedKept
	RejectedDropped = reloadstats.RejectedDropped
)

The reasons of semaphore_flag_rejected_total: a flag that failed validation either keeps the definition it had (last known good) or, with none to fall back on, is dropped. They are the whole set; the flag set is no label.

Variables

View Source
var (
	// ErrNoFlagSets is returned by [New] and [Core.Reload] for a bootstrap file without a flagSets section.
	ErrNoFlagSets = bootstrap.ErrNoFlagSets
	// ErrUnknownConnection is returned when a section names a connection that the file does not define.
	ErrUnknownConnection = errors.New("unknown connection")
	// ErrAcceleratorNeedsS3 is returned when the event accelerator is set and the control plane is not an S3 bucket.
	ErrAcceleratorNeedsS3 = errors.New("the event accelerator needs an s3 source")
	// ErrNilConfig is returned when no bootstrap configuration is given.
	ErrNilConfig = errors.New("no bootstrap configuration")
	// ErrClosed is returned by [Core.Run] and [Core.Reload] after [Core.Shutdown].
	ErrClosed = errors.New("the relay core is shut down")
	// ErrAlreadyRunning is returned by a second [Core.Run].
	ErrAlreadyRunning = errors.New("the relay core runs already")
	// ErrNotDrained is returned by [Core.Shutdown] when the deadline passed before everything stopped.
	ErrNotDrained = errors.New("the relay core did not stop in time")
)

Sentinel errors of the package.

Functions

func SerializeJitter

func SerializeJitter(source func() float64) func() float64

SerializeJitter makes a source of jitter (a value in [0, 1)) safe to call from several goroutines: the polling flag source and the poll of the dynamic segments both draw from Deps.Jitter. Nil stays nil.

Types

type BuildError

type BuildError struct {
	Err  error
	Path string
}

BuildError says which setting of the bootstrap file made a build step fail. Path is the dotted path of the setting (connections.control.path); Err never holds a secret, only names.

func (*BuildError) Error

func (e *BuildError) Error() string

Error implements error.

func (*BuildError) Unwrap

func (e *BuildError) Unwrap() error

Unwrap returns the cause.

type Core

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

Core is the assembled relay core.

func New

func New(ctx context.Context, cfg *bootstrap.Config, deps *Deps) (*Core, error)

New builds the core of a validated bootstrap file. The context bounds the build (the exporters and notifiers); it does not outlive New. It starts no goroutine of the loops (see Core.Run), but it opens the cache directory and starts the exporters and notifiers, so a core that was built must be stopped with Core.Shutdown. An error names the setting at fault (see BuildError) and never holds a secret. The core keeps cfg: the caller must not change it afterwards.

func (*Core) Collect

func (c *Core) Collect(event events.Event) bool

Collect hands an event to the exporters, the way the evaluator does for the events of the flags that track them. It reports whether the event was accepted. The event belongs to the exporters from the call: the caller must not change it afterwards.

func (*Core) DropNotPublic

func (c *Core) DropNotPublic(count int)

DropNotPublic counts the events of a caller without a key that were refused: their flag is not a public one.

func (*Core) Evaluator

func (c *Core) Evaluator() *flagruntime.Evaluator

Evaluator returns the evaluator of the flag sets. The events of the flags that track them reach the exporters.

func (*Core) Holder

func (c *Core) Holder() *flagruntime.Holder

Holder returns the holder of the current runtime: handlers load the runtime from it for every request.

func (*Core) Refresh

func (c *Core) Refresh(ctx context.Context) (RefreshResult, error)

Refresh looks at the sources now, through the loop that looks on schedule, then waits until the engine has decided the generation the pass left: what the relay serves is known when it returns. Calls that arrive together share one pass, and ctx bounds both waits.

func (*Core) Reload

func (c *Core) Reload(cfg *bootstrap.Config) error

Reload applies a new bootstrap file in place. Only the admin keys apply live; every other change is kept out and named in the PendingRestart of the status (the connections, the control plane, the exporters, the notifiers, the listeners). The reload is asynchronous and latest-wins: the engine takes the file in its next round, and the outcome is in the status. cfg must be a loaded and validated file, and belongs to the core afterwards.

func (*Core) Run

func (c *Core) Run(ctx context.Context) error

Run starts the loops (the reader, the source, the engine, the notification worker and the cache directory writer) and blocks until ctx is done or Core.Shutdown is called. It returns nil after the loops ended and the cache directory wrote what it held. It does not stop the exporters and notifiers: Core.Shutdown drains them, and must always be called. Run can be called once, and not after Shutdown.

func (*Core) Shutdown

func (c *Core) Shutdown(ctx context.Context) error

Shutdown stops the core in order: it stops the reader, the source and the engine (nothing new enters the runtime), waits for the cache directory to write what it holds, drains the exporters and notifiers until the deadline of ctx, and releases the connections. It is safe to call without Run, and more than once: a later call waits for the first and returns its result. When ctx ends first, Shutdown returns an error that wraps ErrNotDrained and the context error, and what did not stop keeps stopping in the background: a goroutine of the core then releases the cache directory and the collector once the loops ended. A later call waits for that cleanup within its own context.

func (*Core) Status

func (c *Core) Status() Status

Status returns a snapshot of the status. It reads atomics and immutable values and never blocks.

func (*Core) WorkStats added in v1.0.0

func (c *Core) WorkStats() WorkStats

WorkStats reads the work the relay does besides serving, see WorkStats. Call it once for a scrape, not for a probe.

type Deps

type Deps struct {
	// Logger receives the logs of every part; nil discards them.
	Logger *slog.Logger
	// Registerer receives the collector of the events; nil registers nothing.
	Registerer prometheus.Registerer
	// Scheduler replaces the timer of the polling loop of the change source (tests drive the passes with it).
	Scheduler polling.Scheduler
	// SegmentWait replaces the timer of the watcher of the version keys of the dynamic segments; nil is a timer.
	SegmentWait flagruntime.Wait
	// Jitter replaces the random source of the change source: it returns a value in [0, 1).
	Jitter func() float64
	// TunePolling changes the configuration of the change source after it was made from the bootstrap file.
	TunePolling func(*polling.Config)
	// StateFS is the file system of the cache directory; nil is the real one.
	StateFS statedir.FS
	// NewManager builds the exporter managers, see [events.RuntimeConfig.NewManager]; nil takes the default.
	NewManager events.NewManagerFunc
	// Now is the clock of the request limits of the connections; nil is [clock.Now].
	Now func() time.Time
	// Broadcast is called with every change of a flag set, see [events.RuntimeConfig.Broadcast].
	Broadcast func(flagruntime.Change)
	// Hooks are the hooks of the reconcile engine.
	Hooks flagruntime.Hooks
	// Secrets reads the secrets of the file (environment and files).
	Secrets bootstrap.LoadOptions
	// TuneAccelerator changes the configuration of the event accelerator after it was made from the bootstrap file (a
	// test replaces its timer and its jitter source).
	TuneAccelerator func(*eventaccel.Config)
	// Tracing are the OpenTelemetry providers that the clients of the core are built with (the AWS clients, the
	// segment stores, the poll passes and the event accelerator). The zero value is tracing off: nothing is
	// instrumented.
	Tracing tracing.Providers
	// Connection options for the factory (an HTTP client or round tripper, an observer).
	Connection []connection.Option
}

Deps are the injected dependencies of a Core. Every field is optional.

type FlagSourcesStatus added in v1.3.0

type FlagSourcesStatus struct {
	// Source is the work of the change source.
	Source flagsource.Stats `json:"source"`
	// Data is the state of the flag data.
	Data flagdata.Status `json:"data"`
}

FlagSourcesStatus is the status of the change source (what it did against the stores) and of the flag data (what the events became).

type PollResult added in v1.3.0

type PollResult struct {
	// Result is one of the Poll results of package service.
	Result string
	// Reason is the closed code of a failed pass, else empty.
	Reason string
	// Generation is the generation of the flag data after the pass.
	Generation uint64
	// Changed says that the pass left another generation than the one the call found.
	Changed bool
}

PollResult is what the pass of a refresh found.

type RefreshResult

type RefreshResult struct {
	Engine flagruntime.Reload
	Poll   PollResult
	// Running is the generation the relay serves when the call returns: the one of the decision when it was applied,
	// the last known good when it was rejected.
	Running uint64
}

RefreshResult is what a refresh found: the pass of the change source, and what the engine decided of the generation the pass left the flag data with.

type ReloadStats

type ReloadStats = reloadstats.Stats

ReloadStats counts the rounds of the engine (the bootstrap round, every generation and every reload of the file) by outcome, and keeps the last ones.

type RequestLimitStatus added in v1.3.0

type RequestLimitStatus struct {
	// Connection is the name of the connection.
	Connection string `json:"connection"`
	// MaxPerSecond is the limit of maxRequestsPerSecond.
	MaxPerSecond int `json:"maxPerSecond"`
	// Refused counts the requests that were not made because the limit was reached.
	Refused uint64 `json:"refused"`
}

RequestLimitStatus is the request limit of one connection and what it refused.

type RoundSummary

type RoundSummary = reloadstats.RoundSummary

RoundSummary is one round of the engine, without its free text: the outcome and the stable code, the generation the round was about, and when it ended.

type SegmentSetHealth

type SegmentSetHealth struct {
	Healthy    int `json:"healthy"`
	StoreError int `json:"storeError"`
}

SegmentSetHealth is the number of served dynamic segments of a flag set that are healthy and that have a store error.

type SegmentsStatus

type SegmentsStatus struct {
	// Sets is the live health of the served dynamic segments of each flag set that has some.
	Sets map[string]SegmentSetHealth `json:"sets,omitempty"`
	// Stores is the state of each connection that can serve segments.
	Stores []segmentstore.ConnectionState `json:"stores,omitempty"`
	// Bindings is the number of shared bindings that the served runtime uses (one for each segments object, connection
	// and reading of a missing key), and the state of the held sets of each connection.
	Bindings flagruntime.SegmentBindingsStatus `json:"bindings"`
	// Resolver sums what the resolvers of every generation did since the start.
	Resolver resolver.Stats `json:"resolver"`
}

SegmentsStatus is the state of the dynamic segments of the process.

type SourceStatus added in v1.3.0

type SourceStatus struct {
	// Round is the result of the last round of the engine, applied, ignored or rejected.
	Round flagruntime.RoundResult `json:"round"`
	// Runtime is the status tree of the runtime that serves now.
	Runtime *flagruntime.Status `json:"runtime"`
	// State is the state of the cache directory.
	State cachestate.StateStatus `json:"state"`
	// LastGeneration is the generation of the last content that was handed to the engine.
	LastGeneration uint64 `json:"lastGeneration"`
}

SourceStatus is the status of the engine and of the runtime that serves now.

type StateWriterStats added in v1.0.0

type StateWriterStats = statewriter.Stats

StateWriterStats is the work of the writer of the cache directory: the snapshots that wait for the engine and the objects visited to find the content the runtime holds.

type Status

type Status struct {
	// Accelerator is the status of the event accelerator; nil when it is not configured.
	Accelerator *eventaccel.Status `json:"eventAccelerator,omitempty"`
	// CacheDirDisabled is the reason there is no cache directory although one was asked for; empty otherwise.
	CacheDirDisabled string `json:"cacheDirDisabled,omitempty"`
	// RequestLimits are the connections that have maxRequestsPerSecond, by name, with the requests each refused.
	RequestLimits []RequestLimitStatus `json:"requestLimits,omitempty"`
	// Reloads counts the rounds of the engine by outcome since the core was built.
	Reloads ReloadStats `json:"reloads"`
	// Source is the status of the engine and the running runtime.
	Source SourceStatus `json:"source"`
	// FlagSources is the status of the change source and of the flag data it feeds.
	FlagSources FlagSourcesStatus `json:"flagSources"`
	// Events is the status of the exporters and notifiers.
	Events events.Status `json:"events"`
	// Segments is the state of the dynamic segments: the stores, the served segments of each flag set, the counters.
	Segments SegmentsStatus `json:"segments"`
	// ShuttingDown is true from the first call of [Core.Shutdown].
	ShuttingDown bool `json:"shuttingDown"`
	// Bootstrapped is true once the first round that carried the bootstrap file ended, whatever its outcome. It is a
	// fact of the engine, not inferred from the snapshot: a file equal to the empty runtime swaps nothing.
	Bootstrapped bool `json:"bootstrapped"`
}

Status is the status of a core: the joined status of the change source, the flag data and the engine, the one of the exporters and notifiers, and the cache directory. It holds no API key and no secret.

type WorkStats added in v1.0.0

type WorkStats struct {
	// StateWriter is the work of the writer of the cache directory; zero when there is no cache directory.
	StateWriter StateWriterStats `json:"stateWriter"`
	// Evaluation is the view of the caches of the evaluation service that every flag set shares: the queries it
	// compiled and parsed, and what it keeps. Reading it takes no part in an evaluation.
	Evaluation flagdef.Stats `json:"evaluation"`
	// RefreshWaiting is the number of refresh calls that wait for the pass of the change source.
	RefreshWaiting int `json:"refreshWaiting"`
}

WorkStats is the work the relay does besides serving, read at scrape time by the metrics and by nothing on the path of a probe: it takes locks and walks caches that Core.Status does not.

Directories

Path Synopsis
internal
reloadstats
Package reloadstats counts the rounds of the reconcile engine of a relay core by outcome and keeps the last ones.
Package reloadstats counts the rounds of the reconcile engine of a relay core by outcome and keeps the last ones.
statewriter
Package statewriter makes the cache directory of a relay core hold what its runtime serves.
Package statewriter makes the cache directory of a relay core hold what its runtime serves.

Jump to

Keyboard shortcuts

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