Documentation
¶
Index ¶
- Constants
- func DialGateway(cfg GatewayConfig, options ...xgrpc.CertificateStoreOption) (*grpc.ClientConn, error)
- func DialGatewayWith(cfg GatewayConfig, dialOptions []grpc.DialOption, ...) (*grpc.ClientConn, error)
- func LoadDescriptorSet(path string) (*protoregistry.Files, error)
- func MetricsServiceName(name string) string
- func NewMethodRequest(method string, files *protoregistry.Files) (proto.Message, error)
- func ReadinessServiceName(name string) string
- func Run[C any](use string, short string, factory func(*C, *zap.Logger) (Runnable, error)) error
- func RunOperator[C any](path string, factory func(*C, *zap.Logger) (Runnable, error)) error
- type Actuator
- type FunctionActuator
- type FunctionActuatorOption
- type GRPCServer
- type GRPCServerConfig
- type GRPCServerOption
- type GatewayConfig
- type GatewayRegRunner
- type GatewayRegRunnerOption
- type Latest
- type MetricsCollector
- type MetricsConfig
- type NoopReconcilerMetricsObserver
- type Operator
- type Option
- func WithGRPCServer(cfg GRPCServerConfig, services ...ServiceRegistrar) Option
- func WithGatewayDialOptions(dialOptions ...grpc.DialOption) Option
- func WithGateways(register RegisterConfig, gateways ...GatewayConfig) Option
- func WithListener(listener net.Listener) Option
- func WithLog(log *zap.Logger) Option
- func WithMetrics(cfg MetricsConfig, collectors ...MetricsCollector) Option
- func WithPreRun(fn PreRun) Option
- func WithReadiness(name string, tracker *readiness.Tracker) Option
- func WithReconcile(cfg ReconcileConfig) Option
- func WithWorkers(workers ...Runner) Option
- type PreRun
- type Rebuilder
- type ReconcileConfig
- type Reconciler
- type ReconcilerMetrics
- type ReconcilerMetricsObserver
- type ReconcilerOption
- type ReconcilerState
- type RegisterConfig
- type Runnable
- type Runner
- type ServiceRegistrar
- type StaticConfig
- type StaticOption
- type StaticTarget
- type Target
- type Version
Constants ¶
const ( DefaultReconcileInterval = 30 * time.Second DefaultReconcileInitialBackoff = 500 * time.Millisecond DefaultReconcileMaxBackoff = 30 * time.Second DefaultRegisterInterval = 30 * time.Second )
const RebuildWindow = 200 * time.Millisecond
RebuildWindow is the quiet time after a build before the next one may start.
A change after a quiet spell is built at once; changes coming faster are folded into one build when the window ends.
Variables ¶
This section is empty.
Functions ¶
func DialGateway ¶ added in v0.1.0
func DialGateway(cfg GatewayConfig, options ...xgrpc.CertificateStoreOption) (*grpc.ClientConn, error)
DialGateway opens a client connection to the gateway cfg describes, in plaintext or over TLS as its tls block says.
The options configure the store presenting the client certificate. The connection dials lazily, so an unreachable gateway surfaces on the first RPC rather than here.
func DialGatewayWith ¶ added in v0.5.0
func DialGatewayWith( cfg GatewayConfig, dialOptions []grpc.DialOption, options ...xgrpc.CertificateStoreOption, ) (*grpc.ClientConn, error)
DialGatewayWith is DialGateway with extra gRPC dial options.
The transport credentials the tls block selects are applied after the extra options, so that none of them can replace the credentials. A context dialer among them lets the connection run over an in-memory transport; the endpoint then needs a scheme that skips name resolution, such as passthrough.
func LoadDescriptorSet ¶ added in v0.6.0
func LoadDescriptorSet(path string) (*protoregistry.Files, error)
LoadDescriptorSet reads a module's descriptor set: a FileDescriptorSet in the protobuf binary encoding, as protoc writes it with --descriptor_set_out.
A file of the set resolves its imports in the set first, then among the files linked into this binary, so a set written without --include_imports serves as well as a full one.
func MetricsServiceName ¶ added in v0.1.0
MetricsServiceName returns the gRPC service name under which the named operator reports metrics through a gateway.
func NewMethodRequest ¶
NewMethodRequest builds an empty request for the spelled unary method, resolved in the descriptor set, or among the descriptors linked into this binary when files is nil.
A method resolved in a set takes a dynamic message of the set's request type, even when this binary links that type.
func ReadinessServiceName ¶
ReadinessServiceName identifies an operator's scoped readiness API.
func Run ¶
Run is the generic entry point for an operator binary.
It wires up:
- CLI command setup with required --config flag.
- Loading and validating the YAML config.
- Initializing logging from the config.
- Constructing the Runnable from the build callback.
- Running the Runnable in an errgroup alongside xcmd.WaitInterrupted and, when the config enables it, the debug server.
Note that xcmd.Interrupted is treated as a clean shutdown.
Types ¶
type Actuator ¶
Actuator applies a desired state of type T to a single downstream target, typically a single gateway.
type FunctionActuator ¶
type FunctionActuator struct {
// contains filtered or unexported fields
}
FunctionActuator publishes network functions to a gateway, leaving alone the ones the gateway already holds.
func NewFunctionActuator ¶
func NewFunctionActuator( client ynpb.FunctionServiceClient, options ...FunctionActuatorOption, ) *FunctionActuator
NewFunctionActuator returns a FunctionActuator publishing through client.
func (*FunctionActuator) Apply ¶
Apply publishes function to the gateway unless it already holds it.
func (*FunctionActuator) Close ¶
func (m *FunctionActuator) Close() error
Close is a no-op, the client's connection belongs to the caller.
type FunctionActuatorOption ¶
type FunctionActuatorOption func(*functionActuatorOptions)
FunctionActuatorOption configures NewFunctionActuator.
func WithFunctionLog ¶
func WithFunctionLog(log *zap.Logger) FunctionActuatorOption
WithFunctionLog sets the logger for the function actuator.
func WithIgnorePDump ¶
func WithIgnorePDump() FunctionActuatorOption
WithIgnorePDump leaves pdump modules on both sides out of the check whether the gateway already holds the wanted function.
type GRPCServer ¶
type GRPCServer struct {
// contains filtered or unexported fields
}
GRPCServer wraps a grpc.Server with the operator's service set.
func NewGRPCServer ¶
func NewGRPCServer( cfg GRPCServerConfig, services []ServiceRegistrar, options ...GRPCServerOption, ) (*GRPCServer, []string)
NewGRPCServer constructs a GRPCServer with the supplied service registrars applied to a fresh grpc.Server and returns registered service names.
type GRPCServerConfig ¶
type GRPCServerConfig struct {
// Endpoint is the address the gRPC server binds.
Endpoint xcfg.NonEmptyString `yaml:"endpoint"`
// AdvertiseEndpoint is the address registered with gateways.
//
// Empty uses the bound address. Set it for an unreachable wildcard or
// loopback bind.
AdvertiseEndpoint string `yaml:"advertise_endpoint"`
}
GRPCServerConfig describes how to expose the operator's gRPC server.
func (*GRPCServerConfig) Validate ¶
func (m *GRPCServerConfig) Validate() error
Validate checks the advertised endpoint without resolving its host.
type GRPCServerOption ¶
type GRPCServerOption func(*grpcServerOptions)
func WithGRPCLog ¶
func WithGRPCLog(log *zap.Logger) GRPCServerOption
WithGRPCLog sets the logger used by the gRPC server wrapper.
type GatewayConfig ¶
type GatewayConfig struct {
// Name is a human-readable label used in logs and status reports.
Name string `yaml:"name"`
// Endpoint is the gRPC address of the Gateway.
Endpoint xcfg.NonEmptyString `yaml:"endpoint"`
// TLS enables TLS towards the Gateway when present, plaintext otherwise.
TLS *xgrpc.ClientTLSConfig `yaml:"tls"`
}
GatewayConfig holds the name and gRPC endpoint of a single Gateway.
type GatewayRegRunner ¶
type GatewayRegRunner struct {
// contains filtered or unexported fields
}
GatewayRegRunner periodically re-registers operator services in all configured gateways.
func NewGatewayRegRunner ¶
func NewGatewayRegRunner( gateways []GatewayConfig, services []string, endpoint string, options ...GatewayRegRunnerOption, ) *GatewayRegRunner
NewGatewayRegRunner creates a registration runner for all configured gateways, advertising the given endpoint verbatim to each of them.
type GatewayRegRunnerOption ¶
type GatewayRegRunnerOption func(*gatewayRegRunnerOptions)
GatewayRegRunnerOption configures NewGatewayRegRunner.
func WithGatewayRegDialOptions ¶ added in v0.5.0
func WithGatewayRegDialOptions(options ...grpc.DialOption) GatewayRegRunnerOption
WithGatewayRegDialOptions adds gRPC dial options to every gateway connection of the runner; they cannot replace its transport credentials.
func WithGatewayRegInterval ¶
func WithGatewayRegInterval(d time.Duration) GatewayRegRunnerOption
WithGatewayRegInterval sets the period between registration attempts.
A non-positive period falls back to the default.
func WithGatewayRegLog ¶
func WithGatewayRegLog(log *zap.Logger) GatewayRegRunnerOption
WithGatewayRegLog sets the logger for the registration runner.
type Latest ¶ added in v0.5.0
type Latest[T any] struct { // contains filtered or unexported fields }
Latest holds the newest published desired state and tells its readers when a newer one replaces it.
A published value is immutable: neither its publisher nor a reader changes it. A reader that lags behind sees only the newest value, never the ones published in between.
func (*Latest[T]) Load ¶ added in v0.5.0
Load returns the newest version.
The first load of a version tells the publisher that a reader took it, see Loaded.
type MetricsCollector ¶ added in v0.1.0
MetricsCollector exposes operator metrics to a metrics service.
type MetricsConfig ¶ added in v0.5.0
type MetricsConfig struct {
// Name scopes the metrics service, see MetricsServiceName.
Name string
// Prefix starts the name of every reconcile and gateway apply family.
Prefix string
// Labels go on every reconcile and gateway apply series.
Labels []*commonpb.Label
}
MetricsConfig names the metrics an operator serves.
type NoopReconcilerMetricsObserver ¶
type NoopReconcilerMetricsObserver struct{}
NoopReconcilerMetricsObserver is the default observer wired into reconciler options when no metrics sink is attached.
func (NoopReconcilerMetricsObserver) OnBackoffReset ¶
func (NoopReconcilerMetricsObserver) OnBackoffReset()
OnBackoffReset intentionally discards backoff reset events.
func (NoopReconcilerMetricsObserver) OnBackoffScheduled ¶
func (NoopReconcilerMetricsObserver) OnBackoffScheduled(time.Duration)
OnBackoffScheduled intentionally discards scheduled backoff events.
func (NoopReconcilerMetricsObserver) OnReconcileCompleted ¶
func (NoopReconcilerMetricsObserver) OnReconcileCompleted(error)
OnReconcileCompleted intentionally discards completion events.
func (NoopReconcilerMetricsObserver) OnStateChanged ¶
func (NoopReconcilerMetricsObserver) OnStateChanged(ReconcilerState)
OnStateChanged intentionally discards state transition events.
type Operator ¶
type Operator[T any] struct { // contains filtered or unexported fields }
Operator is the generic operator skeleton.
It always runs the optional PreRun hook, the reconciler, and any configured workers.
The embedded gRPC server, gateway-registration loop, readiness and metrics are opt-in via WithGRPCServer, WithGateways, WithReadiness and WithMetrics respectively.
func NewOperator ¶
NewOperator returns an operator that applies the published desired state to every target.
func (*Operator[T]) Run ¶
Run runs the optional PreRun hook, then runs the reconciler and any configured workers in an errgroup.
When WithGRPCServer was supplied, it binds the listener and runs the gRPC server. The gateway-registration loop runs only when WithGateways supplied a non-empty gateway list.
Run blocks until the supplied context is cancelled or any part fails. Either way the shutdown drains the readiness first, stops the reconciler, the workers and the registration next, and stops the server last, so its clients see the drain while it still answers.
type Option ¶
type Option func(*options)
Option configures the Operator.
func WithGRPCServer ¶
func WithGRPCServer(cfg GRPCServerConfig, services ...ServiceRegistrar) Option
WithGRPCServer enables an embedded gRPC server on the configured endpoint.
The server exposes the supplied services independently of gateway registration, so operators may serve metrics or APIs without registering. When this option is not supplied, the operator does not bind a listener.
func WithGatewayDialOptions ¶ added in v0.5.0
func WithGatewayDialOptions(dialOptions ...grpc.DialOption) Option
WithGatewayDialOptions adds gRPC dial options to the connections that register the operator in its gateways; they cannot replace the transport credentials the gateway config selects.
A context dialer among them lets the registration run over an in-memory transport; the gateway endpoints then need a scheme that skips name resolution, such as passthrough.
func WithGateways ¶
func WithGateways(register RegisterConfig, gateways ...GatewayConfig) Option
WithGateways enables gateway registration against the supplied gateways.
An empty gateway list leaves registration disabled. Registration also requires an embedded gRPC server.
func WithListener ¶ added in v0.5.0
WithListener hands the embedded gRPC server an already open listener to serve instead of binding the endpoint its config names.
It takes effect only with WithGRPCServer. The listener is advertised to the gateways under its own address unless the config names another, and the server closes it when it stops. A nil listener binds the endpoint.
func WithLog ¶
WithLog sets the logger used by the Operator and its sub-components when no more specific logger is supplied.
func WithMetrics ¶
func WithMetrics(cfg MetricsConfig, collectors ...MetricsCollector) Option
WithMetrics serves the operator's metrics under the configured name: the reconcile families, the apply families of every target, labelled with its name as the gateway, then the families of every collector.
The embedded server, when enabled, serves them in place of a metrics service registered by hand: a second registration under that name stops the process at startup.
func WithPreRun ¶
WithPreRun registers a hook executed once before any goroutine starts.
Useful for seeding the desired state from static configuration.
func WithReadiness ¶ added in v0.5.0
WithReadiness reports the tracker as the operator's readiness.
The embedded server, when enabled, serves the tracker under the given name, see ReadinessServiceName, in place of a readiness service registered by hand: a second registration under that name stops the process at startup. Every shutdown drains the tracker before the work stops, so one built with the drain latch keeps an apply cut off by the shutdown from overwriting the drain.
func WithReconcile ¶
func WithReconcile(cfg ReconcileConfig) Option
WithReconcile sets the reconcile-loop timing parameters.
Zero-valued fields set the corresponding default value.
func WithWorkers ¶
WithWorkers attaches additional long-running goroutines to the operator's errgroup.
Returning a non-nil error from any worker tears down the operator.
type PreRun ¶
PreRun is an optional one-shot hook executed before the operator starts its goroutines.
Operators use it to seed in-memory state from static configuration so the first reconcile pass observes it.
type Rebuilder ¶ added in v0.5.0
type Rebuilder[T any] struct { // contains filtered or unexported fields }
Rebuilder publishes the desired state that a build function assembles from sources changing on their own: once when it starts, then after changes, at most once per window.
A build starts only once a reader loaded the previous one, so the builds keep pace with the fastest reader and every reader shares them.
func NewRebuilder ¶ added in v0.5.0
NewRebuilder returns a Rebuilder publishing what build returns.
func (*Rebuilder[T]) Invalidate ¶ added in v0.5.0
func (m *Rebuilder[T]) Invalidate()
Invalidate tells the rebuilder that the sources changed.
It never blocks, and changes reported before the next build starts make one build.
type ReconcileConfig ¶
type ReconcileConfig struct {
// Interval is the steady-state period between successful reconcile
// passes.
Interval xcfg.NonZero[time.Duration] `yaml:"interval"`
// InitialBackoff is the first sleep after a failed pass. It grows
// exponentially.
InitialBackoff xcfg.NonZero[time.Duration] `yaml:"initial_backoff"`
// MaxBackoff caps the exponential backoff sleep.
MaxBackoff xcfg.NonZero[time.Duration] `yaml:"max_backoff"`
}
ReconcileConfig holds timing parameters for the reconcile loop.
func (*ReconcileConfig) Validate ¶
func (m *ReconcileConfig) Validate() error
type Reconciler ¶
type Reconciler[T any] struct { // contains filtered or unexported fields }
Reconciler drives an Actuator from the latest desired state until its context is cancelled.
The loop has three states observable through ReconcilerMetricsObserver:
- Idle (nothing published yet: block on ctx and the first publication).
- Applying (Apply runs to completion — retried with backoff on failure, preempted by a newer desired state between retries).
- Sleeping (interval after success, backoff delay after failure — preempted by a newer desired state or ctx).
Apply is never cancelled mid-flight by a newer desired state — preemption happens between applies, not within them.
func NewReconciler ¶
func NewReconciler[T any]( actuator Actuator[T], latest *Latest[T], options ...ReconcilerOption, ) *Reconciler[T]
NewReconciler constructs a Reconciler that applies the published desired state through the supplied actuator.
type ReconcilerMetrics ¶ added in v0.1.0
type ReconcilerMetrics struct {
// contains filtered or unexported fields
}
ReconcilerMetrics records the standard reconcile lifecycle metrics.
func NewReconcilerMetrics ¶ added in v0.1.0
func NewReconcilerMetrics( prefix string, labels ...*commonpb.Label, ) *ReconcilerMetrics
NewReconcilerMetrics constructs a collector and observer for the standard reconcile lifecycle metric families.
func (*ReconcilerMetrics) Collect ¶ added in v0.1.0
func (m *ReconcilerMetrics) Collect() []*commonpb.Metric
func (*ReconcilerMetrics) OnBackoffReset ¶ added in v0.1.0
func (m *ReconcilerMetrics) OnBackoffReset()
OnBackoffReset clears the retry delay after reconciliation recovers.
func (*ReconcilerMetrics) OnBackoffScheduled ¶ added in v0.1.0
func (m *ReconcilerMetrics) OnBackoffScheduled(delay time.Duration)
OnBackoffScheduled records the delay before the next reconcile attempt.
func (*ReconcilerMetrics) OnReconcileCompleted ¶ added in v0.1.0
func (m *ReconcilerMetrics) OnReconcileCompleted(err error)
OnReconcileCompleted records one reconcile attempt and whether it failed.
func (*ReconcilerMetrics) OnStateChanged ¶ added in v0.1.0
func (m *ReconcilerMetrics) OnStateChanged(state ReconcilerState)
OnStateChanged records the reconcile loop's current lifecycle state.
type ReconcilerMetricsObserver ¶
type ReconcilerMetricsObserver interface {
OnReconcileCompleted(err error)
OnBackoffScheduled(delay time.Duration)
OnBackoffReset()
OnStateChanged(state ReconcilerState)
}
ReconcilerMetricsObserver receives semantic events from the reconcile loop and translates them into metrics.
type ReconcilerOption ¶
type ReconcilerOption func(*reconcilerOptions)
ReconcilerOption configures NewReconciler.
func WithReconcileBackoff ¶
func WithReconcileBackoff(initial, max time.Duration) ReconcilerOption
WithReconcileBackoff sets the initial and maximum sleep durations for the exponential backoff applied after failed reconcile passes.
func WithReconcileInterval ¶
func WithReconcileInterval(d time.Duration) ReconcilerOption
WithReconcileInterval sets the steady-state period between successful reconcile passes.
func WithReconcilerLog ¶
func WithReconcilerLog(log *zap.Logger) ReconcilerOption
WithReconcilerLog sets the logger used by the reconcile loop.
func WithReconcilerMetrics ¶
func WithReconcilerMetrics(metrics ReconcilerMetricsObserver) ReconcilerOption
WithReconcilerMetrics attaches the metrics observer for the reconcile loop.
type ReconcilerState ¶
type ReconcilerState int
ReconcilerState is the current state of the reconcile loop.
const ( // ReconcilerStateIdle indicates the loop is waiting for the first // desired state to be published. ReconcilerStateIdle ReconcilerState = iota // ReconcilerStateApplying indicates the loop is invoking the // Actuator (possibly retrying with backoff). ReconcilerStateApplying // ReconcilerStateSleeping indicates the loop is sleeping between // passes — either the steady-state interval after success or the // backoff delay after failure — cut short by a newer desired state or // context cancellation. ReconcilerStateSleeping )
type RegisterConfig ¶
type RegisterConfig struct {
// Interval sets heartbeat period between registration refreshes.
Interval xcfg.NonZero[time.Duration] `yaml:"interval"`
}
RegisterConfig holds the gateway registration heartbeat parameter.
type Runnable ¶
Runnable is the minimal lifecycle surface the generic CLI helper drives.
Operators satisfy it via *Operator[T].
func NewStaticModuleOperator ¶
func NewStaticModuleOperator( name string, cfg StaticConfig, targets []StaticTarget, options ...StaticOption, ) (Runnable, error)
NewStaticModuleOperator builds an operator that pushes targets to every gateway on each reconcile pass and reports readiness and metrics under name.
type Runner ¶
Runner is a long-running goroutine driven by the operator's errgroup.
A non-nil return cancels the errgroup and tears the operator down.
type ServiceRegistrar ¶
ServiceRegistrar registers a gRPC service on server and returns its fully-qualified service name.
The name is used for gateway registration heartbeats.
func NewMetricsServiceRegistrar ¶ added in v0.1.0
func NewMetricsServiceRegistrar(name string, collectors ...MetricsCollector) ServiceRegistrar
NewMetricsServiceRegistrar returns a registrar for the shared metrics contract under an operator instance name.
func NewReadinessServiceRegistrar ¶ added in v0.1.0
func NewReadinessServiceRegistrar(name string, tracker *readiness.Tracker) ServiceRegistrar
NewReadinessServiceRegistrar serves the shared readiness contract under the operator's own name.
type StaticConfig ¶
type StaticConfig struct {
// Server is where the operator serves its readiness and metrics.
Server GRPCServerConfig
// Gateways lists the gateways every target is pushed to.
Gateways []GatewayConfig
// Register paces the registration heartbeat to the gateways.
Register RegisterConfig
// Reconcile paces the push and its retries.
Reconcile ReconcileConfig
}
StaticConfig is the part of an operator's configuration the static module operator consumes.
type StaticOption ¶
type StaticOption func(*staticOptions)
StaticOption configures NewStaticModuleOperator.
func WithStaticLog ¶
func WithStaticLog(log *zap.Logger) StaticOption
WithStaticLog sets the logger for the static module operator.
func WithStaticReload ¶ added in v0.6.0
func WithStaticReload(interval time.Duration, load func() ([]StaticTarget, error)) StaticOption
WithStaticReload polls a source independently of gateway reconciliation.
A nil snapshot means no change. Failed loads or invalid targets preserve the previous desired state and are retried at the next positive interval.
type StaticTarget ¶
type StaticTarget struct {
// Name labels the target in logs and errors, the module config's name
// for the module operators.
Name string
// Method is the unary gRPC method that replaces the module config,
// spelled as "package.Service/Method".
//
// Empty when the target only publishes a function.
Method string
// Descriptors resolves the method, its request and its reply, nil
// resolving them among the descriptors linked into this binary.
Descriptors *protoregistry.Files
// Request is the message the method receives, sent as is.
Request proto.Message
// Function is published after the configs, nil when the target owns
// none.
Function *ynpb.Function
// IgnorePdump leaves pdump modules on both sides out of the function
// comparison.
IgnorePdump bool
}
StaticTarget is one module config pushed to every gateway on each reconcile pass, or one function published after every config, or both.
type Target ¶ added in v0.5.0
type Target[T any] struct { // Name labels the gateway in metrics. Name string // Actuator applies the desired state to the gateway. Actuator Actuator[T] // Scope is the readiness scope every apply outcome is recorded in, empty // for a target that reports its readiness itself. Scope string }
Target is one gateway the operator reconciles.
type Version ¶ added in v0.5.0
type Version[T any] struct { // Value is the published state; nobody changes it afterwards. Value T // Number counts the publications from one; zero means nothing was // published yet. Number uint64 // Replaced is closed once a newer value is published. Replaced <-chan struct{} }
Version is one published value of the desired state.