Documentation
¶
Overview ¶
Package flagruntime holds the immutable runtime of the relay proxy and the reconcile engine that replaces it.
A Runtime is built once from one verified snapshot of the published content (Content) and is never changed afterwards: nothing may mutate a Runtime, a FlagSet, a Status or the flags they hold. A reader calls Holder.Load once and uses the result for the whole request; it never sees a mix of two generations.
The Builder turns a Content into a Runtime with structural sharing: a flags object is parsed once per checksum, a flag set whose definition and sources did not change is carried over by pointer, and the flags of a source object are shared by every flag set that lists it. The Engine owns one goroutine, the only writer of the Holder. Work reaches it through channels (a latest-wins channel of Content, a latest-wins channel of bootstrap configurations), and every round ends with one atomic pointer store.
The relay runs on it: [relaycore.Core] owns the engine and the HTTP layer reads its holder.
The values of variations are shared between flag sets (and between generations). A caller that gets a value out of a flag must treat it as read-only; the evaluator clones what it hands out.
Index ¶
- Constants
- Variables
- func RandomSpread(limit time.Duration) time.Duration
- func ResolveAdminKeys(cfg *bootstrap.Config, opts bootstrap.LoadOptions) (map[string]struct{}, error)
- func RunSegmentVersions(ctx context.Context, holder *Holder, poll *SegmentPoll)
- type Binding
- type BoundDefinition
- type Builder
- type BuilderOptions
- type Built
- type Change
- type ConfigIdentity
- type ConnectionBreakers
- type ConnectionSnapshots
- type Content
- type Decision
- type Engine
- func (e *Engine) Await(ctx context.Context, revision uint64) (Reload, error)
- func (e *Engine) AwaitDecision(ctx context.Context, revision uint64) (Decision, error)
- func (e *Engine) Bootstrapped() bool
- func (e *Engine) Changes() <-chan Change
- func (e *Engine) Reload(cfg *bootstrap.Config)
- func (e *Engine) Result() RoundResult
- func (e *Engine) Run(ctx context.Context)
- func (e *Engine) Submit(content *Content)
- func (e *Engine) Taken() uint64
- type EntryProblem
- type Evaluator
- func (e *Evaluator) AllFlagsState(ctx context.Context, set *FlagSet, evalCtx ffcontext.Context) flagstate.AllFlags
- func (e *Evaluator) BoolVariationDetails(ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, ...) (model.VariationResult[bool], error)
- func (e *Evaluator) ConfigTag(set *FlagSet, keys []string) (uint64, bool)
- func (e *Evaluator) EachFlagState(ctx context.Context, set *FlagSet, evalCtx ffcontext.Context, keys []string, ...)
- func (e *Evaluator) EvaluationContextEnrichment(set *FlagSet) map[string]any
- func (e *Evaluator) Float64VariationDetails(ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, ...) (model.VariationResult[float64], error)
- func (e *Evaluator) GetFlagStates(ctx context.Context, set *FlagSet, evalCtx ffcontext.Context, ...) flagstate.AllFlags
- func (e *Evaluator) IntVariationDetails(ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, ...) (model.VariationResult[int], error)
- func (e *Evaluator) JSONArrayVariationDetails(ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, ...) (model.VariationResult[[]any], error)
- func (e *Evaluator) JSONVariationDetails(ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, ...) (model.VariationResult[map[string]any], error)
- func (e *Evaluator) PreTag(set *FlagSet, keys []string) (PreTag, bool)
- func (e *Evaluator) RawVariation(ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, ...) (model.RawVarResult, error)
- func (e *Evaluator) ResponseMetadata(res *model.RawVarResult) map[string]any
- func (e *Evaluator) StringVariationDetails(ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, ...) (model.VariationResult[string], error)
- type EvaluatorConfig
- type FlagChange
- type FlagRejection
- type FlagSet
- func (f *FlagSet) Change() (FlagChange, error)
- func (f *FlagSet) ChangeTag(tagOf func(body []byte) string) (string, error)
- func (f *FlagSet) ConfigETag() string
- func (f *FlagSet) Configuration(keys []string) map[string]flagdef.Flag
- func (f *FlagSet) EncodedBytes() int
- func (f *FlagSet) EncodedValue(flagKey, variation string) flagstate.EncodedValue
- func (f *FlagSet) Flag(name string) (*flagdef.InternalFlag, bool)
- func (f *FlagSet) PreTaggable(keys []string) bool
- func (f *FlagSet) SegmentCatalog() *segment.Catalog
- func (f *FlagSet) SegmentCatalogFor(flagKey string) *segment.Catalog
- func (f *FlagSet) SegmentUse(flagKey string) ([]string, bool)
- type FlagSetStatus
- type Holder
- type Hooks
- type Object
- type ObjectState
- type ObjectStatus
- type Option
- func WithChangeBuffer(size int) Option
- func WithHooks(hooks Hooks) Option
- func WithInitialBootstrap(cfg *bootstrap.Config) Option
- func WithSecretOptions(opts bootstrap.LoadOptions) Option
- func WithSegmentStores(stores SegmentStores) Option
- func WithSegments(env *SegmentEnv) Option
- func WithWithdrawnCap(size int) Option
- type Outcome
- type ParseEvent
- type PreTag
- type Problem
- type PublicStatus
- type Rebuilt
- type Reload
- type Reloadability
- type RoundResult
- type Route
- type Runtime
- type SegmentBinder
- type SegmentBindingsStatus
- type SegmentCounts
- type SegmentEnv
- type SegmentPoll
- type SegmentRejection
- type SegmentStore
- type SegmentStores
- type SegmentView
- type SetSegments
- type SetState
- type StateVisitor
- type Stats
- type Status
- type StoreTable
- type Wait
- type WithdrawnSet
Constants ¶
const ( SettingVersion = "version" SettingServerListeners = "server.listeners" SettingServerUnixSocket = "server.unixSocketPath" SettingServerUnixMode = "server.unixSocketMode" SettingServerShutdown = "server.shutdown" SettingConnections = "connections" SettingControlPlane = "controlPlane" SettingControlPlaneConn = "controlPlane.connection" SettingControlPlaneState = "controlPlane.stateDir" SettingControlPlaneMan = "controlPlane.manifest" SettingExporters = "exporters" SettingNotifiers = "notifiers" SettingObservability = "observability" SettingEvaluation = "evaluation" SettingSegments = "segments" SettingServerOps = "server.ops" SettingServerEventStream = "server.ofrepEventStream" SettingServerValidate = "server.validateFlags" SettingServerHideBanner = "server.hideBanner" )
The settings that need a restart, as they appear in Status.PendingRestart.
const ( // KindFlags is an object of flags, parsed with the engine parser. KindFlags = controlplane.KindFlags // KindFlagSets is an object of flag-set documents. KindFlagSets = controlplane.KindFlagSets // KindSegments is an object of segments documents: accepted, validated and used for evaluation (the relay // builds the segment catalog of each flag set from it, see segcatalog.go). KindSegments = controlplane.KindSegments )
Kinds and formats of the objects that the runtime reads.
const ( // MetadataCacheable is the Semaphore key. MetadataCacheable = "semaphore_cacheable" // MetadataSegmentStatus is the Semaphore key of the health of the segment lookups of an evaluation: STALE, // NOT_CONFIGURED or STORE_ERROR, the worst of the segments of the evaluation (the names of LaunchDarkly's // bigSegmentsStatus). A healthy evaluation, and one that looked at no segment, do not carry it. MetadataSegmentStatus = "semaphore_segmentStatus" // LegacyMetadataCacheable is the legacy key, always sent. LegacyMetadataCacheable = "gofeatureflag_cacheable" )
The metadata keys that tell a provider that a value can be cached: the Semaphore name and the legacy one, which the upstream providers read.
const ( CodeApplied = "applied" CodeInvalidContent = "invalid-content" CodeGenerationConflict = "generation-conflict" CodeStaleGeneration = "stale-generation" CodeDuplicate = "duplicate-generation" CodeInvalidBootstrap = "invalid-bootstrap" CodeBuildFailed = "build-failed" CodeVetoed = "vetoed" )
The codes of a Reload.
const CodeAdminKeyCollision controlplane.Code = "admin-key-collision"
CodeAdminKeyCollision is the code of a Problem that says an API key of the flag set is also an admin key. The key grants nothing while the collision exists: it is not routed to the flag set and it is not an admin key (it is answered as an unknown key). The other keys of the flag set and the other admin keys work, and the generation is applied. It is reported per key owner like controlplane.CodeDuplicateKey, never as a rejected generation, so a published key can never keep the relay from serving.
const CodeDefinitionKept controlplane.Code = "definition-kept"
CodeDefinitionKept is the code of a Problem that says the flag set keeps its last valid definition because its entry in the new document is invalid.
const CodeSourceDegraded controlplane.Code = "source-degraded"
CodeSourceDegraded is the code of a Problem about a source object that is not ok. The codes of the other problems are the controlplane codes (controlplane.CodeUnresolvedSource, controlplane.CodeDuplicateKey, controlplane.CodeDuplicateName) and the entry codes of its validation.
const DefaultChangeBuffer = 64
DefaultChangeBuffer is the default size of the change channel.
const DefaultJoinTimeout = 5 * time.Second
DefaultJoinTimeout bounds the wait of RunSegmentVersions for the passes at its end: a store call that ignores its context must not keep the relay from stopping.
const DefaultPullTimeout = time.Minute
DefaultPullTimeout is the deadline of the refresh of one snapshot segment, much longer than the poll interval: a big set may take longer than the interval to pull, and a slow set never takes the time of another.
const DefaultVersionInterval = 5 * time.Second
DefaultVersionInterval is how often the version key of a segment is polled when its definition gives no interval.
const DefaultWithdrawnCap = 256
DefaultWithdrawnCap is the default size of the list of withdrawn flag sets in the status.
const MaxUnresolvedNames = 5
MaxUnresolvedNames bounds the unresolved names that /info and the log list.
const PublicName = "@public"
PublicName is the name of the public flag set: the merged view of the flag sets that are published without an API key. A real flag set can not have it (the name rule forbids the character), so it never meets a published name.
Variables ¶
var ( // ErrInvalidContent is matched by a rejection of a Content that is malformed (generation 0, an unknown // object state or kind of state, an unsupported format). ErrInvalidContent = errors.New("runtime: invalid content") // ErrGenerationConflict is matched by the rejection of a Content with the generation that is running // but another content. ErrGenerationConflict = errors.New("runtime: generation conflict") // ErrStaleGeneration is matched when a Content has a lower generation than the running one, or the same // content again; it is ignored. ErrStaleGeneration = errors.New("runtime: stale generation") // ErrInvalidBootstrap is matched by the rejection of a bootstrap configuration that cannot be applied // (an admin key that does not resolve). ErrInvalidBootstrap = errors.New("runtime: invalid bootstrap") // ErrVetoed is matched when the BeforeSwap hook refused the candidate. ErrVetoed = errors.New("runtime: candidate vetoed") // ErrDecode is matched by the reason of an object that cannot be decoded. ErrDecode = errors.New("runtime: decode") )
var ( // ErrUnknownKey is the error of [RouteUnknown]. ErrUnknownKey = errors.New("runtime: unknown API key") // set uses it to say "flag set is not available" in the error details of a single evaluation. ErrFlagSetUnavailable = errors.New("runtime: flag set is not available") )
Sentinel errors of the routes that are not served.
var ErrDuplicatePublicFlag = errors.New("runtime: a flag key is defined in two public flag sets")
ErrDuplicatePublicFlag is matched by the rejection of a generation in which two public flag sets define the same flag key: they form one namespace.
var ErrFlagNotPresent = errors.New("is not present or disabled")
ErrFlagNotPresent is wrapped by the error of an evaluation of a flag that the flag set does not hold. Its text is the one of the version 1 client ("flag <key> is not present or disabled").
var ErrNoSnapshotSource = errors.New("the connection cannot read the members of a segment: use mode: lookup")
ErrNoSnapshotSource is the reason of a snapshot definition on a connection that cannot read the members of a set.
Functions ¶
func RandomSpread ¶
RandomSpread returns a random duration in [0, limit), zero for a limit that is not positive: the production source of SegmentPoll.Jitter.
func ResolveAdminKeys ¶
func ResolveAdminKeys(cfg *bootstrap.Config, opts bootstrap.LoadOptions) (map[string]struct{}, error)
ResolveAdminKeys reads the admin keys of a bootstrap configuration. The error names an index, never a value.
func RunSegmentVersions ¶
func RunSegmentVersions(ctx context.Context, holder *Holder, poll *SegmentPoll)
RunSegmentVersions refreshes the dynamic segments of the current runtime every tick, off the request path, until ctx ends (or Wait fails): it reads the version keys of the lookup segments and refreshes the holders of the snapshot segments. Each distinct binding is polled once when its interval is due, however many flag sets use it. The bindings of one connection are polled in order in a pass of their own; the loop never waits for a pass, and a connection whose pass still runs is skipped, so a store that hangs delays no other connection and there is at most one pass for each connection. Each holder refresh has its own deadline (DefaultPullTimeout). A pass that runs for more than twice that deadline is hung (a store call that ignores its context): it is logged once, the connection counts as down, and the sets that nothing refreshes answer STALE after three intervals. The time of the loop is the sum of the ticks it waited, so it needs no wall clock and a test that drives Wait drives the polls. The loop is owned by the run context of the relay; the passes end with it, and it returns after them, or after SegmentPoll.JoinTimeout for a pass that does not end.
Types ¶
type Binding ¶
type Binding struct {
// Provider answers the lookups of the definitions. It must honour the context.
Provider segment.Provider
// Versioner reads the version keys of the definitions, nil when the store cannot.
Versioner segment.Versioner
// Source reads the version and the members of a set, for the definitions in the snapshot mode; nil when the store
// cannot, and then a snapshot definition is not served.
Source segment.SnapshotSource
}
Binding is what a connection serves for a set of definitions.
type BoundDefinition ¶
type BoundDefinition struct {
// Name is the name of the segment.
Name string
// Key is the key of the set, or the prefix of the member keys; empty means the default of the store.
Key string
// VersionKey is the key that holds the version of the segment, empty for none.
VersionKey string
// Layout is how the members are stored.
Layout segment.Layout
}
BoundDefinition is what a store needs to serve one dynamic segment.
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder turns a Content into the candidate of a Runtime, with structural sharing against the last committed build. It is not safe for concurrent use: the engine goroutine owns it.
func NewBuilder ¶
func NewBuilder(svc *flagdef.Service, opts BuilderOptions) *Builder
NewBuilder returns a Builder that validates flags with svc, which the caller owns.
func (*Builder) Build ¶
Build computes the candidate for a content.
Cost: the content is scanned once, O(objects), comparing checksums. Parsing is proportional to the objects whose checksum changed. A generation that changed only flags objects rebuilds only the flag sets that list them and copies the flag-set, status and key tables once (O(total flag sets) + O(total keys) map copies, no per-flag work). A generation that changed a flag-set document, or added or removed any object, also walks every entry of the documents (O(entries + keys)), reusing the flag sets that did not change by pointer. A no-op generation allocates a few small values only.
func (*Builder) CachedParses ¶
CachedParses returns the number of parse results held (flags objects plus documents).
type BuilderOptions ¶
type BuilderOptions struct {
// SegmentStores tells what the connections of the bootstrap file can serve: a dynamic segment is checked against
// it when its segments object is read. Nil means the connections are not known and are not checked.
SegmentStores SegmentStores
// Segments binds the served dynamic segments to the providers of the process. The zero value serves none: they
// answer not a member, NOT_CONFIGURED.
Segments *SegmentEnv
// OnParse is called once for every object that is parsed (not for an object served from the cache).
OnParse func(ParseEvent)
// Now returns the time stamped on the flag sets that a build creates ([FlagSet.ModifiedAt]). Nil means
// [clock.Now], read once per build.
Now func() time.Time
// WithdrawnCap is the number of withdrawn flag-set names that the status keeps; the oldest are dropped.
// Zero means [DefaultWithdrawnCap].
WithdrawnCap int
}
BuilderOptions configure a Builder.
type Built ¶
type Built struct {
// Runtime holds the maps, the generation and the status tree of the candidate. Snapshot, AdminKeys and
// the reload fields of the status are the business of the caller.
Runtime *Runtime
// Rebuilt lists the flag sets with a new pointer, by name.
Rebuilt []Rebuilt
// SegmentRejections lists the segments objects whose content this build met and rejected, once each: a build that
// finds the content it already rejected lists nothing.
SegmentRejections []SegmentRejection
// Stats counts the work of the build.
Stats Stats
// contains filtered or unexported fields
}
Built is the candidate of one Builder.Build. Nothing of the builder changes until Builder.Commit.
type Change ¶
type Change struct {
// Diff lists the flags added, deleted and updated. A flag whose pointer is the same in both flag sets is not
// listed, so an unchanged flag costs nothing.
Diff notifier.DiffCache
// Config names the configuration the change leads to; nil when it is not known.
Config *ConfigIdentity
// FlagSet is the name of the flag set.
FlagSet string
// Generation is the generation of the swap that produced the last of the coalesced changes.
Generation uint64
// Snapshot is the snapshot number of that swap.
Snapshot uint64
// Removed says that the flag set was withdrawn: every flag of the diff is deleted.
Removed bool
}
Change tells what changed in one flag set. It is emitted once per rebuilt flag set after a swap.
type ConfigIdentity ¶
type ConfigIdentity struct {
// ModifiedAt is the date of the configuration ([Runtime.ConfigDate]), zero when the manifest has none.
ModifiedAt time.Time
// ETag is the identity of the content of the flag set ([FlagSet.ConfigETag]).
ETag string
}
ConfigIdentity names the configuration of a flag set: what a change notification tells a client, so that a replica can tell whether it serves that configuration.
type ConnectionBreakers ¶
type ConnectionBreakers struct {
// Connection is the name in the bootstrap file.
Connection string `json:"connection"`
// Open and HalfOpen count the segments in that state; the others are closed.
Open int `json:"open"`
HalfOpen int `json:"halfOpen"`
}
ConnectionBreakers counts the segments of a connection by the state of their breaker.
type ConnectionSnapshots ¶
type ConnectionSnapshots struct {
// Connection is the name in the bootstrap file.
Connection string `json:"connection"`
// Loaded is the number of sets held and current.
Loaded int `json:"loaded"`
// Stale is the number of sets held after a refresh failed (or a set over the limit).
Stale int `json:"stale"`
// Missing is the number of segments that the store does not have.
Missing int `json:"missing"`
// NeverLoaded is the number of segments with no set yet.
NeverLoaded int `json:"neverLoaded"`
// Members is the number of members held, all the sets of the connection together.
Members int `json:"members"`
}
ConnectionSnapshots counts the held sets (snapshot mode) of one connection by state, and their members.
type Content ¶
type Content struct {
// Objects are the objects by manifest object name.
Objects map[string]Object
// CreatedAt is the createdAt of the manifest: the date of the configuration, the same on every replica. Zero when
// the manifest has none.
CreatedAt time.Time
// Generation is the manifest generation of the content, at least 1.
Generation uint64
// Revision is the sequence number of the snapshot the content comes from, zero when it has none. A caller that
// must know when its snapshot was decided waits for it with [Engine.Await].
Revision uint64
}
Content is one verified snapshot of published content. The manifest reader builds it; this package never reads a manifest. Objects of another kind than KindFlags, KindFlagSets and KindSegments are ignored.
type Decision ¶
type Decision struct {
Reload Reload
// Running is the generation of the runtime that was stored when the decision was made: the generation of the
// decision when it was applied, the last known good one when it was rejected or ignored.
Running uint64
}
Decision is what the engine decided of a revision, and the generation it served when it decided: the two are one fact, so a swap that comes after the decision never changes the answer.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the reconcile engine. One goroutine (Engine.Run) is the only writer of the Holder; the other methods only hand it work through channels.
Ownership: a *Content or a *bootstrap.Config passed to Submit or Reload belongs to the engine from that moment. The engine does not copy it, and the caller must not change it afterwards (nor the maps and byte slices it reaches). The same holds for everything a Runtime reaches.
Withdrawn flag sets: a flag set that the publisher removes leaves FlagSets and ByKey in that generation. Its keys are unknown from then on (the relay answers as for any unknown key) and are free for another flag set at once. The Status lists the most recently withdrawn names with the generation, up to a cap (default DefaultWithdrawnCap); the engine keeps no other state for a withdrawn flag set.
Events: the events of one flag set reach the consumer in order; events of different flag sets are not ordered by generation (a pending event keeps the place of the first change it merged).
A round: take the latest content and the latest bootstrap configuration (a burst is coalesced); validate the content (generation, shape); build the candidate off to the side (parse what changed, rebuild the flag sets that use it); compose the candidate Runtime with the admin keys and the status; store it with one atomic pointer store; then commit the builder (the old parse results are released), compute one change per rebuilt flag set and queue it for the consumer. A rejected candidate stores nothing.
Change events: the consumer reads Engine.Changes, a channel of bounded size. The engine never blocks on it: an event that does not fit in the channel is kept per flag set in a pending table and merged with later changes of the same flag set (the diff goes from the state the consumer last saw to the newest one), and it is handed to the channel when there is room. An event can be merged or cancelled only while it is in the pending table, before it was handed to the channel; with free room in the channel it is handed over at once, so a creation and a withdrawal can arrive as two events. The table holds at most one entry per flag set name, so it is bounded by the number of flag sets, and no name is lost. Events still in the pending table when Run returns are dropped, and the channel is closed.
func NewEngine ¶
NewEngine returns an engine that stores into holder. svc validates the flags and owns the compiled-query caches; the caller owns it. A nil logger discards.
func (*Engine) Await ¶
Await returns when the engine has decided the content of the revision, or of a later one (the later content replaces it: the engine keeps the latest only): the Reload is the decision, applied, ignored or rejected with its code. Revision 0 means nothing to wait for. It waits on the end of the rounds, never polls, and ends with ctx.
func (*Engine) AwaitDecision ¶
AwaitDecision is Engine.Await with the generation the relay served when the decision was made, taken with the decision and not read afterwards: a later swap does not change it.
func (*Engine) Bootstrapped ¶
Bootstrapped reports whether the first round that carried a bootstrap file has ended, applied, ignored or rejected: the relay then knows what its bootstrap file says, although the runtime may not have swapped (a file equal to the empty runtime leaves the snapshot at zero).
func (*Engine) Changes ¶
Changes returns the channel of change events; it is closed when Run returns. See Engine for when an event can still be merged or cancelled: only before the engine hands it to this channel.
func (*Engine) Reload ¶
Reload hands a bootstrap configuration to the engine, with the same latest-wins rule as Engine.Submit.
func (*Engine) Result ¶
func (e *Engine) Result() RoundResult
Result returns the result of the last round, applied, ignored or rejected. A rejected round stores nothing, so its reason is not in the status of the running Runtime: it is read here (the wiring of the relay exposes it), and it is carried by the Status of the next Runtime as LastRejected. Result is safe to call from any goroutine; before the first round it returns the zero RoundResult. The result of a rejected or ignored round differs from the Status.LastReload of the stored runtime, which keeps the last applied round.
func (*Engine) Run ¶
Run is the reconcile loop. It returns when ctx is done; it starts no other goroutine, so nothing is left behind. Run must be called once.
type EntryProblem ¶
type EntryProblem struct {
// Object is the name of the document object.
Object string `json:"object"`
// Name is the flag set name (may be empty or invalid).
Name string `json:"name"`
// Reason says what is wrong; it never contains an API key.
Reason string `json:"reason"`
// Code is the stable reason.
Code controlplane.Code `json:"code"`
// Index is the position in the document.
Index int `json:"index"`
}
EntryProblem is a problem of one entry of a flag-set document.
type Evaluator ¶
type Evaluator struct {
// contains filtered or unexported fields
}
Evaluator evaluates the flags of a FlagSet. It is the replacement of the evaluation methods of the version 1 client, with the same results, and it is created once per process: it owns the flagdef.Service of the evaluations (the caches of parsed queries and scheduled rollouts), which is the service the Engine validates with, so a flag is never parsed twice. There is no client, cache, notifier or goroutine per flag set.
An Evaluator is immutable and safe for concurrent use. It lives outside FlagSet because the flag sets are shared between generations while the service and the enrichment belong to the process.
Ownership of what it returns (the read-only contract of the version 1 client):
- The flags, and everything inside them, are shared by every flag set that lists the same object and by every evaluation. The value of an evaluation (Evaluator.RawVariation, the values of Evaluator.AllFlagsState and Evaluator.GetFlagStates, the value of a tracked event) and the containers that the metadata holds (nested objects and arrays) are those of the flag: they are READ-ONLY. Encode them, do not change them. A caller that must change one takes a copy with flagdef.CloneValue or flagdef.CloneMetadata.
- The metadata map itself, and the result structs, are new for every evaluation (the engine builds them): the caller owns them and may add keys, as Evaluator.ResponseMetadata does.
- Evaluator.JSONVariationDetails and Evaluator.JSONArrayVariationDetails return a copy of the value: the caller owns it.
- The default value that the caller passed in is returned as given.
A handler must therefore never write into a result; the switch to config v2 adds a guard for it.
func NewEvaluator ¶
func NewEvaluator(svc *flagdef.Service, cfg *EvaluatorConfig) *Evaluator
NewEvaluator returns an Evaluator. svc is the service that the Engine of the same runtime is built with.
func (*Evaluator) AllFlagsState ¶
func (e *Evaluator) AllFlagsState(ctx context.Context, set *FlagSet, evalCtx ffcontext.Context) flagstate.AllFlags
AllFlagsState evaluates every flag of the flag set for a context. A nil flag set (not available) answers like an empty one: valid, no flags. The values and the nested metadata containers of the states are shared with the flags and READ-ONLY (see Evaluator).
func (*Evaluator) BoolVariationDetails ¶
func (e *Evaluator) BoolVariationDetails( ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, defaultValue bool, ) (model.VariationResult[bool], error)
BoolVariationDetails evaluates a boolean flag.
func (*Evaluator) ConfigTag ¶ added in v0.3.0
ConfigTag returns what the configuration endpoint answer is made of, as a 64-bit hash, and whether it is known: the flags it lists (every flag of the flag set when keys is empty, else the ones of keys that the flag set holds), each with its own encoding and the segments its rules use, and the enrichment that the body shows (the configured one, without the environment that the evaluations add: it is not in the body). Two flag sets (on two replicas, before and after a restart) with the same result give the same body for the same keys. It does not follow what the body does not hold: the members of a segment, the other flags of the set, the name and the state. It does not allocate, and costs the number of flags it lists.
The hash is 64-bit FNV-1a, not a collision-resistant one (the old tag was SHA-1 of the body): it guards against a stale answer after an honest change, not against someone who writes flag content, who already decides the body. A crafted collision only lets that writer keep a client on an older configuration.
func (*Evaluator) EachFlagState ¶
func (e *Evaluator) EachFlagState( ctx context.Context, set *FlagSet, evalCtx ffcontext.Context, keys []string, visit StateVisitor, )
EachFlagState evaluates the flags named in keys, or every flag when there are none, and hands the state of each to visit, in ascending key order, each flag once: it is Evaluator.GetFlagStates without the table of the states, for a caller that wants them sorted. A name that the flag set does not hold is left out. The values and the nested metadata containers of the states are shared with the flags and READ-ONLY (see Evaluator); the metadata map of a state belongs to the visit.
func (*Evaluator) EvaluationContextEnrichment ¶
EvaluationContextEnrichment returns a deep copy of the configured enrichment of the flag set, without the environment: the "evaluationContextEnrichment" of the flag configuration endpoint. The caller owns it.
func (*Evaluator) Float64VariationDetails ¶
func (e *Evaluator) Float64VariationDetails( ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, defaultValue float64, ) (model.VariationResult[float64], error)
Float64VariationDetails evaluates a number flag.
func (*Evaluator) GetFlagStates ¶
func (e *Evaluator) GetFlagStates( ctx context.Context, set *FlagSet, evalCtx ffcontext.Context, flagsToEvaluate []string, ) flagstate.AllFlags
GetFlagStates evaluates the flags named in flagsToEvaluate, or every flag when the list is empty. A name that the flag set does not hold is left out. The values and the nested metadata containers of the states are shared with the flags and READ-ONLY (see Evaluator).
func (*Evaluator) IntVariationDetails ¶
func (e *Evaluator) IntVariationDetails( ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, defaultValue int, ) (model.VariationResult[int], error)
IntVariationDetails evaluates an integer flag.
func (*Evaluator) JSONArrayVariationDetails ¶
func (e *Evaluator) JSONArrayVariationDetails( ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, defaultValue []any, ) (model.VariationResult[[]any], error)
JSONArrayVariationDetails evaluates an array flag. The value is a copy that the caller owns; the nested containers of the metadata are shared and READ-ONLY (see Evaluator).
func (*Evaluator) JSONVariationDetails ¶
func (e *Evaluator) JSONVariationDetails( ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, defaultValue map[string]any, ) (model.VariationResult[map[string]any], error)
JSONVariationDetails evaluates an object flag. The value is a copy that the caller owns; the nested containers of the metadata are shared and READ-ONLY (see Evaluator).
func (*Evaluator) PreTag ¶
PreTag returns what the bulk evaluation of keys in the flag set is tagged with, and whether it can be tagged before it runs: every flag it evaluates is pre-taggable and the enrichment of the evaluator can be hashed. It does not allocate.
func (*Evaluator) RawVariation ¶
func (e *Evaluator) RawVariation( ctx context.Context, set *FlagSet, flagKey string, evalCtx ffcontext.Context, sdkDefaultValue any, ) (model.RawVarResult, error)
RawVariation is the evaluation of a flag without a type, as the engine client's RawVariation: the value is whatever the flag holds. An object or array value, and the nested containers of the metadata, are shared with the flag and READ-ONLY (see Evaluator); the metadata map itself belongs to the caller.
func (*Evaluator) ResponseMetadata ¶
func (e *Evaluator) ResponseMetadata(res *model.RawVarResult) map[string]any
ResponseMetadata returns the metadata of the OFREP response of an evaluation: the metadata of the result plus, for a cacheable result, the legacy key and (unless DisableSemaphoreMetadata is set) the Semaphore key, as the version 1 handler adds them, and (unless DisableSemaphoreMetadata is set) MetadataSegmentStatus for an evaluation that looked at a segment. The metadata map of a result is owned by the caller (see Evaluator), so the keys are added to it without a copy and the flag is never touched; a result without metadata gets a new map only when it is cacheable.
type EvaluatorConfig ¶
type EvaluatorConfig struct {
// EvaluationContextEnrichment is merged into the context of every evaluation of every flag set that has no
// entry of its own in FlagSetEnrichment (the version 1 evaluationContextEnrichment).
EvaluationContextEnrichment map[string]any
// FlagSetEnrichment replaces EvaluationContextEnrichment for the flag sets it names (by flag set name).
FlagSetEnrichment map[string]map[string]any
// TrackEvent receives the event of an evaluation that must be tracked: the evaluation says trackEvents (the
// setting of the flag) and the hook is set. A nil hook costs nothing. The hook runs on the goroutine of the
// evaluation and must not block; the events package of the relay proxy plugs its queue in here.
//
// The event is READ-ONLY for the hook and for whatever it hands the event to (the exporters): its Value is the
// value of the flag, shared with the flag set and with every other evaluation, and its Metadata is the
// exporter-metadata map of the request context, as in version 1. The hook must encode or copy them, never
// change them; [flagdef.CloneValue] and [flagdef.CloneMetadata] make a copy.
TrackEvent func(*exporter.FeatureEvent)
// Environment is added to the enrichment under "env" when it is not empty.
Environment string
// DisableSemaphoreMetadata keeps the Semaphore metadata key (semaphore_cacheable) out of the response metadata
// of [Evaluator.ResponseMetadata]; the legacy key is always sent (the disableSemaphoreMetadata setting).
DisableSemaphoreMetadata bool
}
EvaluatorConfig is the configuration of an Evaluator. It is read once, by NewEvaluator; the Evaluator keeps no reference to the maps.
type FlagChange ¶
type FlagChange struct {
// Flags are the hashes of the flags by key. The map is shared by every call on the same flag set: it is
// READ-ONLY.
Flags map[string]uint32 `json:"flags"`
// Hash is the hash of the whole flag set.
Hash uint32 `json:"hash"`
}
FlagChange is the answer of the flag change endpoint: a hash of the flag set and one of every flag.
type FlagRejection ¶
type FlagRejection struct {
// Flag is the flag key.
Flag string `json:"flag"`
// Reason says what is wrong.
Reason string `json:"reason"`
// Kept says that the flag keeps its previous definition.
Kept bool `json:"kept"`
}
FlagRejection is one flag that failed validation.
type FlagSet ¶
type FlagSet struct {
ModifiedAt time.Time
Flags map[string]*flagdef.InternalFlag
// Segments is what the rules of the flag set can use as segments, nil when the flag set has none.
Segments *SetSegments
Name string
State SetState
Hash uint64
APIKeys int
Rejected int
// contains filtered or unexported fields
}
FlagSet is the immutable flag table of one flag set. It is reused by pointer across generations while its definition and the content of its sources are unchanged.
func (*FlagSet) Change ¶
func (f *FlagSet) Change() (FlagChange, error)
Change returns the flag change answer: the hashes are those of the JSON encoding of the flags, byte for byte as the version 1 endpoint computes them. A flag set is immutable, so the answer is computed once, by the first call (each flag is encoded once), and every later call returns the same value without allocating; the map of the answer is shared and READ-ONLY. A flag set that a later generation carries over by pointer keeps its memo; a rebuilt one computes its own. A nil flag set has the hash of the empty set.
func (*FlagSet) ChangeTag ¶ added in v0.3.0
ChangeTag returns the tag of the body that the flag change endpoint sends for this flag set: tagOf of the JSON document `{"flags":{...},"hash":n}` and its final newline, byte for byte what the endpoint writes. The flag set is immutable, so the document is encoded and tagged once, by the first call, and every later call returns the same string without allocating; every caller passes the same tagOf. A flag set that a later generation carries over by pointer keeps its tag. The error is the one of FlagSet.Change; a nil flag set has no tag.
func (*FlagSet) ConfigETag ¶
ConfigETag is the identity of the configuration the flag set serves: the hash of its flags (and of the segments they use), in hexadecimal. It depends on the content only, so every replica that serves the same content has the same value, and a rebuild that changes nothing keeps it.
func (*FlagSet) Configuration ¶
Configuration returns the flags of the flag set as the flag configuration endpoint lists them. A name in keys that the flag set does not hold is left out; with no keys every flag is returned. The map is new for each call, never nil, and the caller may change it; the flags in it are the flags of the flag set itself, shared with every other flag set that lists the same object and with the next generation, and are READ-ONLY: encode them, do not change them. A caller that must change a flag takes a copy with its DeepCopy method.
func (*FlagSet) EncodedBytes ¶ added in v0.3.0
EncodedBytes is the number of bytes the encodings of the flag set hold: what it adds to the memory of a generation (the encodings of a flags object are shared by every flag set and generation that lists the object).
func (*FlagSet) EncodedValue ¶ added in v0.3.0
func (f *FlagSet) EncodedValue(flagKey, variation string) flagstate.EncodedValue
EncodedValue returns the encoding of a variation value of a flag, made when the flag was loaded, or the zero value when there is none: the value is a scalar, is large, its flag has scheduled steps, or the flag set holds no such variation. The result is shared and read only.
func (*FlagSet) Flag ¶
func (f *FlagSet) Flag(name string) (*flagdef.InternalFlag, bool)
Flag returns the flag with a name. It does not allocate.
func (*FlagSet) PreTaggable ¶
PreTaggable reports whether every flag that a bulk evaluation of keys evaluates is pre-taggable: keys are the requested flags, every flag of the flag set when there are none. A key that the flag set does not hold is not evaluated, so it does not count. It does not allocate. A nil flag set is not pre-taggable.
func (*FlagSet) SegmentCatalog ¶
SegmentCatalog is the catalog of the segments of the flag set, nil when it has none. It does not allocate.
func (*FlagSet) SegmentCatalogFor ¶
SegmentCatalogFor is the catalog that the flag evaluates against: the one of the flag set it comes from. A flag set of one source has one catalog; the merged public flag set keeps the catalog of the source of each flag.
func (*FlagSet) SegmentUse ¶
SegmentUse tells which segments the rules of a flag use (sorted names, scheduled steps included; nil for a flag that uses none) and whether the flag needs the server to be evaluated: one of them is dynamic (its members live in a store) or cannot be resolved by the flag set (no source defines it). It does not allocate.
type FlagSetStatus ¶
type FlagSetStatus struct {
// Name is the name of the flag set.
Name string `json:"name"`
// State is the state of the flag set.
State SetState `json:"state"`
// Sources are the names of its source objects, in order.
Sources []string `json:"sources"`
// Problems are the reported problems of this flag set.
Problems []Problem `json:"problems"`
// Flags is the number of flags served.
Flags int `json:"flags"`
// APIKeys is the number of API keys of the flag set.
APIKeys int `json:"apiKeys"`
// Rejected is the number of rejected flags in its sources.
Rejected int `json:"rejected"`
// Segments counts the segments of the flag set (nil when it has none).
Segments *SegmentCounts `json:"segments,omitempty"`
}
FlagSetStatus is the status of one flag set.
type Holder ¶
type Holder struct {
// contains filtered or unexported fields
}
Holder is the one place readers get the current Runtime from. The zero value is usable: the first Load stores one empty Runtime, so Load does not allocate afterwards. NewHolder stores it up front.
type Hooks ¶
type Hooks struct {
// OnParse is called for every object parsed.
OnParse func(ParseEvent)
// BeforeSwap is called with the candidate just before the store. An error refuses the candidate: nothing is
// stored and the round is rejected with [CodeVetoed].
BeforeSwap func(candidate *Runtime) error
// OnEmit is called after a change was handed to the channel of [Engine.Changes].
OnEmit func(Change)
// AfterSwap is called with the new runtime right after it is stored, before the changes of the swap are queued.
AfterSwap func(*Runtime)
// AfterRound is called at the end of every round, after the store and the change notifications.
AfterRound func(RoundResult)
}
Hooks are injection points for tests and for the wiring PR. A nil hook is not called. Hooks run on the engine goroutine: a blocking hook blocks the engine.
type Object ¶
type Object struct {
// Kind is [KindFlags], [KindFlagSets] or [KindSegments].
Kind string
// Format is "yaml", "json" or (flags only) "toml".
Format string
// Checksum identifies the bytes (the manifest value). When empty, the checksum is computed from Bytes.
Checksum string
// State is the state of the object; empty means [ObjectOK].
State ObjectState
// Reason says why the state is not ok; it is shown in the status.
Reason string
// Bytes are the verified bytes; only read when the state is ok, or stale for a name never loaded.
Bytes []byte
}
Object is one object of a Content.
type ObjectState ¶
type ObjectState string
ObjectState is the state of an Object in a Content.
const ( // ObjectOK: Bytes hold the verified content of the object. ObjectOK ObjectState = "ok" // ObjectStale: the content could not be refreshed; keep the last good content. A stale object that carries // Bytes and whose name this runtime never loaded (a restart that restored the manifest reader's state) is read // from them as the last good content, and is reported stale. ObjectStale ObjectState = "stale" // ObjectMissing: the object is listed but its content is not available; keep the last good content. ObjectMissing ObjectState = "missing" // ObjectPending: the object was never loaded. ObjectPending ObjectState = "pending" // ObjectInvalid is only reported in a [Status]: the bytes could not be decoded and the last good content // is kept. It is not accepted as input. ObjectInvalid ObjectState = "invalid" )
The states of an input object. An empty state means ObjectOK.
type ObjectStatus ¶
type ObjectStatus struct {
// Since is the time the object left the state ok, as this process saw it (the clock of the build that first
// saw it not ok); zero for an object that is ok.
Since time.Time `json:"since,omitzero"`
// Name is the object name.
Name string `json:"name"`
// Kind is the object kind.
Kind string `json:"kind"`
// State is the state: ok, stale, missing, pending or invalid (undecodable, last good content kept).
State ObjectState `json:"state"`
// Checksum is the checksum of the content held.
Checksum string `json:"checksum"`
// Reason says why the state is not ok.
Reason string `json:"reason"`
// Rejected lists the flags that failed validation.
Rejected []FlagRejection `json:"rejected"`
// UnknownFieldPaths lists the first unknown field paths noticed when decoding this object (bounded).
UnknownFieldPaths []string `json:"unknownFieldPaths,omitempty"`
// Flags is the number of flags held (flag sets held, for a document).
Flags int `json:"flags"`
// EncodedBytes is the number of bytes of the stored variation value encodings that the object holds (not part of
// the /info document: the metric semaphore_config_encoded_bytes reports the sum).
EncodedBytes int `json:"-"`
// UnknownFields counts the unknown fields noticed when decoding this object.
UnknownFields int `json:"unknownFields,omitempty"`
}
ObjectStatus is the status of one source object.
type Option ¶
type Option func(*Engine)
Option configures an Engine.
func WithChangeBuffer ¶
WithChangeBuffer sets the size of the change channel; values below 1 mean 1.
func WithInitialBootstrap ¶
WithInitialBootstrap sets the configuration the process started with: the baseline for pendingRestart. Without it the first configuration given to Engine.Reload is the baseline.
func WithSecretOptions ¶
func WithSecretOptions(opts bootstrap.LoadOptions) Option
WithSecretOptions sets how the admin keys that are secret references are resolved.
func WithSegmentStores ¶
func WithSegmentStores(stores SegmentStores) Option
WithSegmentStores tells the engine what the connections of the bootstrap file can serve, so that a dynamic segment that names one that cannot is rejected when its generation is built. The connections are settings that need a restart, so the table of the process start is the one that counts.
func WithSegments ¶
func WithSegments(env *SegmentEnv) Option
WithSegments tells the engine how to serve the dynamic segments: the process-level binder, the settings of the resolvers and the observer that counts what they do. Without it the dynamic segments are not served.
func WithWithdrawnCap ¶
WithWithdrawnCap sets how many withdrawn flag-set names the status keeps (default DefaultWithdrawnCap).
type Outcome ¶
type Outcome string
Outcome is the result of one reconcile round.
const ( // OutcomeApplied: a new Runtime was stored. OutcomeApplied Outcome = "applied" // OutcomeRejected: the candidate was invalid; nothing was stored. OutcomeRejected Outcome = "rejected" // OutcomeIgnored: the input was older than, or the same as, what runs; nothing was stored. OutcomeIgnored Outcome = "ignored" )
The outcomes of a round.
type ParseEvent ¶
type ParseEvent struct {
// Name is the object name.
Name string
// Kind is the object kind.
Kind string
// Checksum is the checksum that was parsed.
Checksum string
}
ParseEvent tells that an object was parsed. It is delivered to BuilderOptions.OnParse.
type PreTag ¶
type PreTag struct {
// Name is the name of the flag set.
Name string
// State is the state of the flag set (a pending flag set serves no flag).
State SetState
// Content is [FlagSet.Hash] (the hash of the flags and of the segments they use) for the evaluation of every flag,
// and for the evaluation of a list of flags a hash of the list and of those flags alone: a change to another flag
// does not change it.
Content uint64
// Enrichment is the hash of the evaluation context enrichment that the evaluator merges into every evaluation of
// the flag set (the environment included).
Enrichment uint64
// Flags is the number of flags of the flag set for the evaluation of every flag, zero for a list of flags.
Flags int
}
PreTag is what a bulk evaluation needs of a flag set to tag its answer before it evaluates a flag: the fields that say which content and which evaluation environment the answer is made from. Two flag sets with the same PreTag give the same answer to the same request, as long as every flag of the request is FlagSet.PreTaggable.
type Problem ¶
type Problem struct {
Code controlplane.Code `json:"code"`
Subject string `json:"subject,omitempty"`
Reason string `json:"reason"`
}
Problem is one reported problem of a flag set. Subject is a source name or empty.
type PublicStatus ¶
type PublicStatus struct {
// Sets are the names of the flag sets published without an API key, sorted.
Sets []string `json:"sets"`
// Flags is the number of flags of the public namespace.
Flags int `json:"flags"`
// Present says that a request without a key is served.
Present bool `json:"present"`
}
PublicStatus is the status of the public flag set of a runtime.
type Rebuilt ¶
Rebuilt is a flag set that has a new pointer in a Built. Old is nil for a new flag set, and New is a withdrawn flag set (no flags) for a removed one.
type Reload ¶
type Reload struct {
// Outcome is the result.
Outcome Outcome `json:"outcome"`
// Code is the stable reason.
Code string `json:"code"`
// Detail says more, in words.
Detail string `json:"detail"`
// Generation is the generation the round was about (the attempted one for a rejection).
Generation uint64 `json:"generation"`
// Snapshot is the snapshot number stored by an applied round.
Snapshot uint64 `json:"snapshot"`
}
Reload is the result of one round. It never contains an API key.
type Reloadability ¶
type Reloadability struct {
// Path is the bootstrap key path that the rule covers, with every key below it.
Path string
// Setting is the name in Status.PendingRestart; empty for a setting that applies live.
Setting string
// Live is true when a reload applies the setting in place.
Live bool
}
Reloadability says what a reload of the bootstrap file does with one setting.
func ReloadOf ¶
func ReloadOf(path string) (Reloadability, bool)
ReloadOf returns the rule that covers a bootstrap key path: the longest rule path that the key equals or sits below.
func Reloadabilities ¶
func Reloadabilities() []Reloadability
Reloadabilities returns the reload table: one entry per setting of the bootstrap file, in the order of the engine.
type RoundResult ¶
type RoundResult struct {
Reload
// Events is the number of flag sets for which the round left a change event waiting in the pending table of the
// engine, not yet handed to the channel of the consumer. A new change counts once, a change merged into a
// waiting one counts once (per flag set and round), and a change that cancels out (a flag set created and
// withdrawn, or flags gained and lost, while it is still in the pending table) counts zero. A round that is
// not applied has none.
Events int `json:"events"`
// Revision is the revision of the snapshot whose content the round took, zero for a round without content. It is
// the signal that a snapshot was decided: [Engine.Await] and the persistence of the applied state use it.
Revision uint64 `json:"-"`
// ContentApplied tells that the round stored the content of Revision. An applied round is also a bootstrap change
// (an admin key) that came with content the engine rejected: it is not a content decision.
ContentApplied bool `json:"-"`
}
RoundResult is the result of one round as the engine reports it (Engine.Result, Hooks.AfterRound): the Reload of the round itself, plus what the round did to the queue of change events. After an applied round the Reload is the one in Status.LastReload of the stored runtime; after a rejected or ignored round it is not (the running runtime keeps its previous LastReload).
type Route ¶
type Route uint8
Route is what an API key resolves to in one Runtime. The HTTP layer maps it to a status code; this package never imports HTTP.
const ( // RouteUnknown: no flag set and no admin key has this key (HTTP 401). A key of a removed flag set is // unknown from the generation that removed it. RouteUnknown Route = iota // RouteFlagSet: the key routes to a flag set that serves its flags. RouteFlagSet // RoutePending: the key routes to a flag set that is not available (state pending: nothing loaded yet, or // its entry was invalid and it never had a definition). Follow upstream: a single evaluation answers // FLAG_NOT_FOUND, a bulk evaluation and the listings answer 200 with an empty set. Never 503. The returned // flag set holds no flag, so the evaluator gives these answers by itself. RoutePending // RouteAdmin: the key is an admin key of the bootstrap file; it routes to no flag set. RouteAdmin )
The routes of an API key.
func (Route) Err ¶
Err returns nil for a route that serves flags (or is an admin key), ErrUnknownKey for RouteUnknown and ErrFlagSetUnavailable for RoutePending. The errors are sentinels: the call does not allocate and never holds a key.
type Runtime ¶
type Runtime struct {
// FlagSets are the flag sets by name. A flag set that did not change is the same pointer as in the
// previous Runtime.
FlagSets map[string]*FlagSet
// ByKey routes an API key to its flag set. It is rebuilt for every generation that changes a flag set
// or a key: O(keys), not O(flags).
ByKey map[string]*FlagSet
// AdminKeys are the admin keys of the bootstrap file.
AdminKeys map[string]struct{}
// Public is the flag set that serves the requests without an API key: the flag sets published without a key,
// merged into one namespace. Nil when the generation has none: such a request is refused.
Public *FlagSet
// Status is the status tree of this runtime.
Status *Status
// ConfigDate is the createdAt of the manifest generation this runtime serves: the configuration date of every flag
// set of it, the same on every replica that serves the generation. Zero when the manifest has none.
ConfigDate time.Time
// Generation is the manifest generation of the content.
Generation uint64
// Snapshot is a local counter, strictly increasing with every successful swap.
Snapshot uint64
// contains filtered or unexported fields
}
Runtime is one immutable generation of what the relay serves. Nothing may mutate a Runtime or anything it reaches (the maps, the flag sets, the flags, the variation values, the status): they are shared between generations and read without a lock.
func (*Runtime) DynamicSegmentNames ¶
DynamicSegmentNames returns the sorted, distinct names of the dynamic segments that the flag sets of the runtime serve.
func (*Runtime) FlagSetByName ¶
FlagSetByName returns the flag set with a name. It does not allocate.
func (*Runtime) Route ¶
Route resolves an API key: the flag set it routes to (nil unless the route is RouteFlagSet or RoutePending) and the route. A flag set key wins over an admin key.
The lookup does not allocate and takes no lock. A key longer than the longest configured key is refused without being hashed, the other keys go through the [keyIndex]: one seeded hash, then a comparison that reads every byte of a key whose hash is equal, so the time does not depend on how much of a key is right and an attacker chooses no collision. A runtime that was not built by the engine has no index and falls back to its maps. No key is copied, logged or put in an error.
func (*Runtime) SegmentBindings ¶
func (r *Runtime) SegmentBindings() SegmentBindingsStatus
SegmentBindings reads the state of the bindings of the runtime. It calls no store.
func (*Runtime) SegmentConnections ¶
SegmentConnections returns the names of the connections that the flag sets of the runtime use, sorted. A connection that an earlier generation bound and this one does not use is not in it.
type SegmentBinder ¶
type SegmentBinder interface {
// Bind returns the binding of the definitions on the named connection. A missing key of the store is read as
// missing says.
Bind(connection string, missing segment.MissingKey, defs []BoundDefinition) (*Binding, error)
}
SegmentBinder gives a generation the providers of the process: one connection serves the definitions of any number of generations, and nothing here depends on a kind of store. Bind must not block and must not fail for a store that is down: the lookups of such a binding are Unknown until the store is back.
type SegmentBindingsStatus ¶
type SegmentBindingsStatus struct {
// Connections is the state of the held sets of each connection, sorted by name.
Connections []ConnectionSnapshots `json:"connections,omitempty"`
// Breakers is the number of segments whose circuit breaker is open or half open, for each connection that has
// lookup segments, sorted by name.
Breakers []ConnectionBreakers `json:"breakers,omitempty"`
// Live is the number of bindings that the flag sets of the runtime use: one for each segments object, connection
// and reading of a missing key, however many flag sets share it.
Live int `json:"live"`
}
SegmentBindingsStatus is the shared bindings of the dynamic segments that the runtime serves.
type SegmentCounts ¶
type SegmentCounts struct {
// UnresolvedNames is the first of the unresolved names, sorted, at most [MaxUnresolvedNames]. Names only.
UnresolvedNames []string `json:"unresolvedNames,omitempty"`
// Static is the number of static segments (members in the document).
Static int `json:"static"`
// Dynamic is the number of dynamic segments (members in a store), the rejected ones included.
Dynamic int `json:"dynamic"`
// RejectedDefinitions is the number of dynamic definitions, among Dynamic, that the connections of the bootstrap
// file cannot serve.
RejectedDefinitions int `json:"rejectedDefinitions,omitempty"`
// Unresolved is the number of segment names that the flags of the flag set use and that no segments object of
// the flag set defines (a typo, or an object that is not in segmentSources): they answer "not a member" for ever.
Unresolved int `json:"unresolved,omitempty"`
}
SegmentCounts is the number of segments of a flag set, in the status and in /info.
type SegmentEnv ¶
type SegmentEnv struct {
// Binder gives the providers. Nil means no dynamic segment is served.
Binder SegmentBinder
// Observer (optional) receives what the resolvers do; one value for the process.
Observer resolver.Observer
// ObserverFor (optional) gives the observer of the resolvers of one connection; it wins over Observer.
ObserverFor func(connection string) resolver.Observer
// Resolver holds the settings of the resolvers. Nil means the defaults.
Resolver *bootstrap.SegmentResolver
// Traced is true when the relay exports traces; the lookups of a request are then a span. Off, they cost nothing.
Traced bool
// PullTimeout is the deadline of the refresh of one snapshot segment (the version read and the pull of the
// members). Zero means [DefaultPullTimeout].
PullTimeout time.Duration
}
SegmentEnv is what a build needs to bind dynamic segments: the process-level binder, the resolver settings of the bootstrap file and the observer of the resolvers. The zero value serves no dynamic segment.
type SegmentPoll ¶
type SegmentPoll struct {
// Wait is the clock of the loop. Required.
Wait Wait
// Jitter returns a duration in [0, limit): the spread of the first poll of a binding. Nil means no spread.
Jitter func(limit time.Duration) time.Duration
// Logger (optional) receives one line for each change of the state of a connection (down, then works again), and one
// for a set that fails while its store works. The failures of a store that is down are detail (debug). Nil discards.
Logger *slog.Logger
// OnError (optional) receives the failures of a poll. A holder that fails the same way as before is reported once.
// It is called from the pass of a connection, so it may run beside another call.
OnError func(error)
// OnPass (optional) is called with true when the loop starts the pass of a connection and with false when the pass
// ends: for a test or a metric, never on the request path.
OnPass func(connection string, running bool)
// OnIdle (optional) is called after a pass ended and its connection is free to start another: for a test or a
// metric, never on the request path.
OnIdle func(connection string)
// OnConnection (optional) is called when the store of a connection starts failing (down) or works again, never
// for each evaluation or poll. It is the only place that commits that state and runs on the loop, in order, from the
// current bindings: like Logger it must return promptly.
OnConnection func(connection string, down bool)
// Tick is the resolution of the loop: a binding is polled when its interval is due.
Tick time.Duration
// JoinTimeout bounds the wait for the passes when the loop ends. Zero means [DefaultJoinTimeout].
JoinTimeout time.Duration
}
SegmentPoll configures RunSegmentVersions.
type SegmentRejection ¶
type SegmentRejection struct {
// Object is the name of the segments object.
Object string
// Checksum is the checksum of the content.
Checksum string
// Reason says what is wrong, with the path of each field: it quotes no value of the document.
Reason string
// Definitions is the number of dynamic definitions that the connections of the bootstrap file cannot serve and
// that were rejected alone: the object and its other definitions are applied. Zero means that the whole object was
// rejected and keeps its last good content.
Definitions int
}
SegmentRejection is a segments object that the build met with a problem. It is reported once, for the build that met the content, not for each build that finds the same content again.
type SegmentStore ¶
type SegmentStore struct {
// Store is a value of the type that serves the segments of the connection kind: it is only inspected for the
// [segment] interfaces it implements (a nil pointer of the type is enough), no connection is opened and no method
// is called. It is nil for a kind that cannot serve segments (a bucket, a stream).
Store any
// Kind is the type of the connection, as the bootstrap file names it, for example "redis". It is used in the
// reasons only.
Kind string
}
SegmentStore is what the relay knows about one connection of the bootstrap file when it checks a dynamic segment: the kind of the connection and a value of the type that serves segments for that kind.
type SegmentStores ¶
type SegmentStores interface {
// SegmentStore returns the facts of the named connection; false when the bootstrap file has no such connection.
SegmentStore(connection string) (SegmentStore, bool)
}
SegmentStores tells the relay which connections of the bootstrap file exist and what each can serve. The relay only uses the interfaces of segment: nothing here depends on a kind of store. A nil SegmentStores means that the connections are not known and the definitions are not checked against them.
type SegmentView ¶
type SegmentView struct {
// contains filtered or unexported fields
}
SegmentView is the dynamic segments of one generation of a flag set: each served definition is bound to the binding of its segments object (see [segBinding]), which every flag set and every generation that uses the object shares. The view is built off to the side with the flag set, swapped in with it and carried over by pointer while the flag set is. It holds no connection: dropping it releases what nothing else references.
func (*SegmentView) Connections ¶
func (v *SegmentView) Connections() []string
Connections returns the names of the connections that the view uses, sorted.
func (*SegmentView) Contains ¶
Contains implements segment.Provider: the lookups go to the resolver of their segment, one call for each connection that they reach. A lookup of a segment the view does not serve stays Unknown.
func (*SegmentView) Health ¶
func (v *SegmentView) Health() (int, int)
Health returns the number of served segments that are healthy, then the number whose store failed on the last call or whose breaker is open.
func (*SegmentView) RefreshVersions ¶
RefreshVersions polls the bindings of the view that are due at now: one step of the loop for one view, off the request path. The error joins the failures; a segment whose version cannot be read keeps its version.
func (*SegmentView) Serves ¶
func (v *SegmentView) Serves(name string) bool
Serves reports whether the view answers the segment.
type SetSegments ¶
type SetSegments struct {
// Catalog defines the segments of the flag set. A static segment is answered from memory; a dynamic segment has
// a definition and no provider yet, so it answers by its failure policy and the evaluation reports
// NOT_CONFIGURED.
Catalog *segment.Catalog
// View binds the served dynamic definitions of the catalog to the providers of the process, nil when none is
// served. It is built with the catalog and carried over with it.
View *SegmentView
// Static and Dynamic are the numbers of segments of each kind.
Static, Dynamic int
// RejectedDefinitions counts the dynamic definitions that the connections of the bootstrap file cannot serve:
// they are rejected alone, stay in the catalog and answer as a segment without a provider.
RejectedDefinitions int
// contains filtered or unexported fields
}
SetSegments is what the rules of a flag set can use as segments: the catalog of the generation, with the members of the static segments in memory. It is built when the flag set is built and never changed; an unchanged flag set keeps the same one, and the member sets are shared with the segments objects that hold them.
type SetState ¶
type SetState string
SetState is the state of a flag set.
const ( // StateServing: every source is current and every flag is valid. StateServing SetState = "serving" // StateDegraded: the flag set serves, but a source is stale or missing, a flag was rejected, an entry // problem was reported, or a source does not resolve. StateDegraded SetState = "degraded" // StatePending: no source of the flag set was ever loaded, or its entry is invalid and it never had a valid // definition; it serves zero flags (its keys still route to it). StatePending SetState = "pending" // StateWithdrawn: the publisher removed the flag set. It is the state of the entries of Status.Withdrawn and // of the Removed change event; a withdrawn flag set is not in FlagSets and its keys are not routed. StateWithdrawn SetState = "withdrawn" )
The states of a flag set (issue 6).
type StateVisitor ¶
type StateVisitor interface {
// Expect is called once, before the first Visit, with the most states that will be visited.
Expect(count int)
// Visit receives the state of one flag. The state is valid during the call only (the next flag reuses it): the
// visitor copies what it keeps. The metadata map of the state belongs to the visitor.
Visit(key string, state *flagstate.FlagState)
}
StateVisitor receives the states of Evaluator.EachFlagState.
type Stats ¶
type Stats struct {
// Parsed is the number of objects parsed (flags objects and flag-set documents).
Parsed int
// Rebuilt is the number of flag sets that got a new pointer (new, changed or withdrawn).
Rebuilt int
// Reused is the number of flag sets carried over by pointer.
Reused int
// Encoded is the number of object and array variation values that were encoded: the ones of the flags that are new
// or changed (a flag that did not change keeps the encodings it has).
Encoded int
}
Stats counts the work of one build.
type Status ¶
type Status struct {
// FlagSets are the flag sets by name, including those that have no runtime entry (an invalid entry with
// nothing to fall back on is reported with state pending).
FlagSets map[string]*FlagSetStatus `json:"flagSets"`
// Objects are the source objects (flags and flag-set documents) by name.
Objects map[string]*ObjectStatus `json:"objects"`
// LastRejected is the last candidate that was rejected, kept until a later rejection replaces it. A rejected
// round stores nothing, so it shows here only after the next swap; the result of the last round, rejected or
// not, is read from [Engine.Result].
LastRejected *Reload `json:"lastRejected,omitempty"`
// Entries are the problems of the entries of the flag-set documents, in document order.
Entries []EntryProblem `json:"entries"`
// Withdrawn lists the flag sets removed by the publisher, oldest first, up to the cap of the builder. A
// withdrawn flag set is not in FlagSets and its keys are not routed.
Withdrawn []WithdrawnSet `json:"withdrawn"`
// PendingRestart names the bootstrap settings that changed but need a restart; the values are never listed.
PendingRestart []string `json:"pendingRestart"`
// Public says which flag sets serve the requests without a key.
Public *PublicStatus `json:"public"`
// LastReload is the round that produced this runtime.
LastReload Reload `json:"lastReload"`
// DisabledAdminKeys is the number of admin keys that are not accepted because a flag set publishes the same
// key (never the keys themselves).
DisabledAdminKeys int `json:"disabledAdminKeys"`
// Generation is the manifest generation.
Generation uint64 `json:"generation"`
// Snapshot is the snapshot number.
Snapshot uint64 `json:"snapshot"`
}
Status is the immutable status tree of one Runtime. It never contains an API key or an admin key.
type StoreTable ¶
type StoreTable map[string]SegmentStore
StoreTable is a SegmentStores held in a map by connection name.
func (StoreTable) SegmentStore ¶
func (t StoreTable) SegmentStore(connection string) (SegmentStore, bool)
SegmentStore returns the facts of the named connection.
type Wait ¶
Wait is the clock seam of the watcher of the versions: it returns after d, or with the error of ctx when it ends first. Production waits on a timer; a test drives the ticks.
type WithdrawnSet ¶
WithdrawnSet is a flag set that a publisher removed, with the generation that removed it. Keys are never listed.
Source Files
¶
- adminkeys.go
- bootstrap.go
- builder.go
- content.go
- diff.go
- doc.go
- encoded.go
- engine.go
- errors.go
- evaluator.go
- flagview.go
- hash.go
- objects.go
- objectstatus.go
- parse.go
- pass.go
- pretag.go
- public.go
- queue.go
- refcache.go
- reload.go
- reloadlog.go
- route.go
- segbinding.go
- segcatalog.go
- segments.go
- segpoll.go
- segprefetch.go
- segstores.go
- segview.go
- sets.go
- state.go
- status.go
- types.go