operator

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: Apache-2.0 Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultReconcileInterval       = 30 * time.Second
	DefaultReconcileInitialBackoff = 500 * time.Millisecond
	DefaultReconcileMaxBackoff     = 30 * time.Second
	DefaultRegisterInterval        = 30 * time.Second
)

Variables

This section is empty.

Functions

func DialGateway added in v0.1.0

func DialGateway(cfg GatewayConfig) (*grpc.ClientConn, error)

DialGateway opens a client connection to the gateway cfg describes, in plaintext or over TLS as its tls block says.

The connection dials lazily, so an unreachable gateway surfaces on the first RPC rather than here.

func MetricsServiceName added in v0.1.0

func MetricsServiceName(name string) string

MetricsServiceName returns the gRPC service name under which the named operator reports metrics through a gateway.

func NewMethodRequest

func NewMethodRequest(method string) (proto.Message, error)

NewMethodRequest builds an empty request for the spelled unary method, resolved against the descriptors linked into this binary.

func ReadinessServiceName

func ReadinessServiceName(name string) string

ReadinessServiceName identifies an operator's scoped readiness API.

func Run

func Run[C any](
	use string,
	short string,
	factory func(*C, *zap.Logger) (Runnable, error),
) error

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.

Note that xcmd.Interrupted is treated as a clean shutdown.

func RunOperator

func RunOperator[C any](
	path string,
	factory func(*C, *zap.Logger) (Runnable, error),
) error

RunOperator loads the config specified by path and runs the Runnable returned by build until the process is interrupted or any goroutine returns an error.

Types

type Actuator

type Actuator[T any] interface {
	Apply(ctx context.Context, state T) error
	Close() error
}

Actuator applies a desired state of type T to a single downstream target, typically a single gateway.

type ApplyMetrics added in v0.1.0

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

ApplyMetrics records the outcomes of applying state to one target.

func NewApplyMetrics added in v0.1.0

func NewApplyMetrics(prefix string, labels ...*commonpb.Label) *ApplyMetrics

NewApplyMetrics constructs a collector for apply outcomes.

func (*ApplyMetrics) Collect added in v0.1.0

func (m *ApplyMetrics) Collect() []*commonpb.Metric

func (*ApplyMetrics) Observe added in v0.1.0

func (m *ApplyMetrics) Observe(err error)

Observe records one apply attempt and whether it failed.

type FanOutActuator

type FanOutActuator[T any] struct {
	// contains filtered or unexported fields
}

FanOutActuator applies state to several Actuators concurrently.

func NewFanOutActuator

func NewFanOutActuator[T any](
	actuators []Actuator[T],
	options ...FanOutOption,
) *FanOutActuator[T]

NewFanOutActuator constructs a fan-out actuator from a slice of underlying actuators.

func (*FanOutActuator[T]) Apply

func (m *FanOutActuator[T]) Apply(ctx context.Context, state T) error

Apply runs Apply on every underlying Actuator concurrently and joins all observed errors.

func (*FanOutActuator[T]) Close

func (m *FanOutActuator[T]) Close() error

Close closes every underlying Actuator serially and joins their errors.

type FanOutOption

type FanOutOption func(*fanOutOptions)

FanOutOption configures NewFanOutActuator.

func WithFanOutLog

func WithFanOutLog(log *zap.Logger) FanOutOption

WithFanOutLog sets the logger for the fan-out actuator.

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

func (m *FunctionActuator) Apply(ctx context.Context, function *ynpb.Function) error

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.

func (*GRPCServer) Run

func (m *GRPCServer) Run(ctx context.Context, listener net.Listener) error

Run serves until the supplied context is cancelled.

On cancellation it performs a graceful stop and drains Serve's return value.

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.

func (*GatewayRegRunner) Run

func (m *GatewayRegRunner) Run(ctx context.Context) error

Run heartbeats the given service set to every configured gateway.

type GatewayRegRunnerOption

type GatewayRegRunnerOption func(*gatewayRegRunnerOptions)

GatewayRegRunnerOption configures NewGatewayRegistrationRunner.

func WithGatewayRegInterval

func WithGatewayRegInterval(d time.Duration) GatewayRegRunnerOption

WithGatewayRegInterval sets the period between registration attempts.

func WithGatewayRegLog

func WithGatewayRegLog(log *zap.Logger) GatewayRegRunnerOption

WithGatewayRegLog sets the logger for the registration runner.

type MetricsCollector added in v0.1.0

type MetricsCollector interface {
	Collect() []*commonpb.Metric
}

MetricsCollector exposes operator metrics to a metrics service.

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

OnStateChanged intentionally discards state transition events.

type ObservedActuator

type ObservedActuator[T any] struct {
	// contains filtered or unexported fields
}

ObservedActuator wraps an inner Actuator and invokes a callback with the per-gateway apply outcome after each Apply call.

The inner error is returned unchanged so FanOutActuator error joining and reconcile backoff are preserved.

func NewObservedActuator

func NewObservedActuator[T any](
	inner Actuator[T],
	id string,
	observe func(string, error),
) *ObservedActuator[T]

NewObservedActuator wraps inner with an observe callback keyed by id.

After each Apply, observe is called with the gateway id and the error returned by the inner actuator (nil on success).

func (*ObservedActuator[T]) Apply

func (m *ObservedActuator[T]) Apply(ctx context.Context, state T) error

Apply calls the inner actuator, reports the outcome via the observe callback, and returns the inner error unchanged.

func (*ObservedActuator[T]) Close

func (m *ObservedActuator[T]) Close() error

Close delegates to the inner actuator.

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 and gateway-registration loop are opt-in via WithGRPCServer and WithGateways respectively.

func NewOperator

func NewOperator[T any](
	actuator Actuator[T],
	source StateSource[T],
	options ...Option,
) *Operator[T]

func (*Operator[T]) Close

func (m *Operator[T]) Close() error

Close releases resources owned by the Operator.

func (*Operator[T]) Run

func (m *Operator[T]) Run(ctx context.Context) error

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 goroutine returns a non-nil error.

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 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 WithLog

func WithLog(log *zap.Logger) Option

WithLog sets the logger used by the Operator and its sub-components when no more specific logger is supplied.

func WithMetrics

func WithMetrics(observer ReconcilerMetricsObserver) Option

WithMetrics attaches the metrics observer for the reconcile loop.

func WithPreRun

func WithPreRun(fn PreRun) Option

WithPreRun registers a hook executed once before any goroutine starts.

Useful for seeding the source from static configuration.

func WithReconcile

func WithReconcile(cfg ReconcileConfig) Option

WithReconcile sets the reconcile-loop timing parameters.

Zero-valued fields set the corresponding default value.

func WithWorkers

func WithWorkers(workers ...Runner) Option

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

type PreRun func(ctx context.Context) error

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 a populated source.

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 a StateSource until its context is cancelled.

The loop has three states observable through ReconcilerMetricsObserver:

  • Idle (source returned ok=false: block on ctx and Wake).
  • Applying (Apply runs to completion — retried with backoff on failure, preemptable by Wake between retries).
  • Sleeping (interval after success, backoff delay after failure — preemptable by Wake or ctx).

Apply is never cancelled mid-flight by a concurrent Wake — preemption happens between applies, not within them.

func NewReconciler

func NewReconciler[T any](
	actuator Actuator[T],
	source StateSource[T],
	options ...ReconcilerOption,
) *Reconciler[T]

NewReconciler constructs a Reconciler bound to the supplied actuator and state source.

func (*Reconciler[T]) Run

func (m *Reconciler[T]) Run(ctx context.Context) error

Run executes the reconcile loop until the supplied context is cancelled.

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 blocked on Wake or
	// context cancellation because the source reported no work.
	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 — preemptable by Wake 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

type Runnable interface {
	Run(ctx context.Context) error
	Close() error
}

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

type Runner func(ctx context.Context) error

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

type ServiceRegistrar func(server *grpc.Server) string

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 StateSource

type StateSource[T any] interface {
	// Snapshot returns the current target along with an "ok" flag.
	//
	// When ok is false the source is idle: the reconcile loop transitions
	// to the Idle state and blocks on Wake or context cancellation rather
	// than invoking the Actuator.
	//
	// When ok is true the returned value is the state to apply on the next
	// pass: the source must hold it stable until either Advance is called
	// or a subsequent Snapshot replaces it.
	Snapshot() (T, bool)
	// Wake returns a buffered channel the source signals whenever new
	// state is available or whenever an in-flight reconcile pass should be
	// preempted.
	//
	// It is safe to call from any goroutine.
	Wake() <-chan struct{}
	// Advance is invoked by the reconcile loop after a successful Apply,
	// passing the same value Snapshot returned.
	//
	// Queue-style sources use it to pop the head element. Sources that publish
	// a single steady-state snapshot may treat it as a no-op.
	Advance(applied T)
}

StateSource produces the current desired state for the reconcile loop.

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.

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
	// 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.

Jump to

Keyboard shortcuts

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