Documentation
¶
Overview ¶
Package controller is pleme-io's borealis-style Kubernetes controller chassis: a reconcile loop modeled as a shigoto per-object FSM, driven over a sigs.k8s.io/controller-runtime Manager, supervised by lifecycle.App.
It exists so that a Kubernetes operator is a 3-line declarative act — supply a typed Reconciler, a Config, and the GroupVersionKind to watch — and the chassis owns everything else: the manager wiring, the per-object reconcile FSM, retry/backoff classification, an inbound-webhook→enqueue-reconcile adapter, and the lifecycle choreography (BOREALIS §2.5 / pattern-registry §4a).
The algebra, condensed:
- Reconciler — the one interface a consumer implements: a pure Reconcile(ctx, Request) (Result, error). It names no controller-runtime type, so a consumer's reconcile logic is offline-testable without a cluster.
- Request / Result — the typed reconcile in/out: a Request names the object (namespace/name), a Result asks for no-op, requeue, or requeue-after. They mirror controller-runtime's reconcile.Request/Result but live here as a stdlib-only public shape (Law 2, WORLDS-SEPARATE).
- ReconcileState — the per-object FSM state, a thin projection of the shigoto shigoto.JobPhase 10-state machine. Every reconcile of a given object advances through the same pure, table-driven shigoto.Advance transitions (Pending→Ready→Running→Succeeded|Failed→Retrying|Deadlettered), so "what state is this object's reconcile in?" has one fleet answer and the transitions are auditable via shigoto's shigoto.TransitionEmitter.
- Controller — the chassis: New composes a Reconciler + Config + a lifecycle.App; Controller.Run starts the controller-runtime manager under lifecycle supervision and blocks until shutdown.
- Webhook — the inbound-webhook→enqueue adapter: an http.Handler that decodes an external event and enqueues a reconcile Request onto a [Source], so an out-of-band signal (a vendor webhook, a UI button) drives the same FSM as a watch event.
Weight is import-gated (Law 6): the Reconciler/Request/Result/FSM core is pure stdlib + shigoto (offline-testable, no cluster); only Controller and [Manager] touch controller-runtime, which is the chassis's whole purpose.
type myReconciler struct{}
func (myReconciler) Reconcile(ctx context.Context, req controller.Request) (controller.Result, error) {
// ... fetch object via req, converge, return controller.Done.
return controller.Done, nil
}
c, _ := controller.New(cfg, myReconciler{},
controller.For(myGVK),
controller.WithLogger(log))
return c.Run(ctx) // blocks; runs the manager under lifecycle-go
Index ¶
- Constants
- Variables
- type Config
- type Controller
- type EnqueueFunc
- type Enqueuer
- type GVKConfig
- type Option
- type ReconcileFunc
- type ReconcileState
- type Reconciler
- type Request
- type Result
- type RetryConfig
- type RetryKindName
- type Webhook
- type WebhookConfig
- type WebhookOption
- type WebhookPayload
- type WebhookResponse
Constants ¶
const ( // StatePending — a reconcile was enqueued and awaits gate evaluation. StatePending = shigoto.Pending // StateGated — a gate is not yet satisfied; re-evaluated on the next pass. StateGated = shigoto.Gated // StateReady — every gate passed; awaiting an admission slot. StateReady = shigoto.Ready // StateReconciling — Reconcile is in flight. StateReconciling = shigoto.Running // StateSynced — Reconcile returned ok; the object is converged for now. StateSynced = shigoto.Succeeded // StateErrored — Reconcile returned an error; awaiting a retry decision. StateErrored = shigoto.Failed // StateBackoff — a retry is scheduled; the object is in its backoff window. StateBackoff = shigoto.Retrying // StateDeadletter — retries are exhausted (or the failure was // non-retryable). Only an operator revives it. StateDeadletter = shigoto.Deadlettered )
The reconcile-lifecycle aliases of the shigoto phases. They are the same underlying values (so shigoto.Advance drives them unchanged), aliased to the controller vocabulary so reconcile code reads in reconcile terms.
Variables ¶
var Done = Result{}
Done is the canonical "reconcile converged, nothing more to do" result. It is the zero Result, named for readability at reconcile return sites:
return controller.Done, nil
var ErrAlreadyRun = stderrors.New("controller: Run already called")
ErrAlreadyRun is returned by Controller.Run when it is called more than once. A Controller's lifecycle is single-shot, mirroring lifecycle.App.Run.
var ErrNoKind = stderrors.New("controller: no watched kind configured (use For or Config.Kind)")
ErrNoKind is returned by New when no watched kind was configured (via For or Config.Kind) AND no custom builder hook was supplied. The chassis needs to know what to reconcile.
var ErrNoReconciler = stderrors.New("controller: reconciler must not be nil")
ErrNoReconciler is returned by New / FromConfig when the required Reconciler argument is nil. A controller with no reconciler is meaningless, so this is a construction-time failure, not a runtime one.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Name is the controller name, stamped on every emitted reconcile
// [shigoto.Transition] and used to scope the manager. Default "controller".
Name string `yaml:"name" json:"name,omitempty"`
// Kind selects the watched object kind by group/version/kind. It is the
// yaml-facing alternative to the [For] option; if both are set, [For] wins.
// At least one of Kind or a [For]/builder hook must resolve to a watched
// kind, else [New] returns [ErrNoKind].
Kind GVKConfig `yaml:"kind" json:"kind"`
// MetricsAddr is the bind address for the controller-runtime metrics
// endpoint (e.g. ":8080"). Empty disables the manager's own metrics server —
// the fleet default, since metrics are owned by metrics-go / lifecycle-go's
// mount (BOREALIS §2.5a), not duplicated by the manager.
MetricsAddr string `yaml:"metrics_addr" json:"metrics_addr,omitempty"`
// LeaderElection enables controller-runtime leader election so only one
// replica reconciles at a time (the standard HA operator posture).
LeaderElection bool `yaml:"leader_election" json:"leader_election,omitempty"`
// LeaderElectionID is the name of the lease used for leader election. Default
// derived from Name when LeaderElection is true.
LeaderElectionID string `yaml:"leader_election_id" json:"leader_election_id,omitempty"`
// MaxConcurrentReconciles bounds the controller's reconcile worker count —
// the per-controller fan-out (controller-runtime's MaxConcurrentReconciles).
// Default 1 (serialised reconciles, the safest default).
MaxConcurrentReconciles int `yaml:"max_concurrent_reconciles" json:"max_concurrent_reconciles,omitempty"`
// ReconcileTimeout bounds a single reconcile call. Zero means no per-call
// timeout (the reconcile runs until it returns or ctx is cancelled). Default
// 0 (off) — most reconcilers honour ctx themselves.
ReconcileTimeout time.Duration `yaml:"reconcile_timeout" json:"reconcile_timeout,omitempty"`
// Retry is the reconcile retry policy applied to errored reconciles by the
// per-object FSM. The zero value is NoRetry (deadletter on first error) —
// controller-runtime's own work-queue backoff still requeues, but the FSM's
// retry policy decides Backoff-vs-Deadletter classification.
Retry RetryConfig `yaml:"retry" json:"retry"`
// Webhook configures the inbound-webhook→enqueue adapter. Empty Addr means
// no webhook server (the chassis only reconciles watch events).
Webhook WebhookConfig `yaml:"webhook" json:"webhook"`
// Lifecycle is the embedded [lifecycle.Config] governing signals, drain,
// shutdown grace, and the health-plane surface — the chassis runs the manager
// under a [lifecycle.App] built from this (Law 3 self-hosting; the chassis
// does not invent a second lifecycle knob).
Lifecycle lifecycle.Config `yaml:"lifecycle" json:"lifecycle"`
}
Config is the typed, yaml-tagged runtime policy of a Controller — the BOREALIS Law 3 config surface. It is loaded once at main through shikumi-go (defaults → env → file, file wins) and the sub-struct is handed to FromConfig; the constructors here NEVER call shikumi.Load themselves (BOREALIS §3.5). A zero Config is valid: the chassis fills every field with a sane default.
type Controller ¶
type Controller struct {
// contains filtered or unexported fields
}
Controller is the borealis-style Kubernetes controller chassis: a typed Reconciler whose per-object reconciles run through a shigoto FSM, driven over a sigs.k8s.io/controller-runtime Manager, supervised by a lifecycle.App. Construct it with New or FromConfig, then call Controller.Run exactly once.
The chassis composes (never owns) the three siblings it builds on:
- the reconcile FSM ([objectFSM]) is the per-object state engine (shigoto);
- the manager run loop is supervised by lifecycle.App (lifecycle-go);
- errored reconciles carry fleet-standard severity (errors-go).
Controller deliberately exposes the typed Reconciler/Request/Result shapes (not controller-runtime types) on its public surface so reconcile logic is offline-testable and the chassis stays the only place controller-runtime is imported (Law 2 / Law 6 / WORLDS-SEPARATE).
func FromConfig ¶
func FromConfig(cfg Config, r Reconciler, opts ...Option) (*Controller, error)
FromConfig constructs a Controller from an already-loaded Config sub-struct, the Reconciler, plus functional [Option]s. It is the canonical config-consuming constructor (BOREALIS §3.5 `pkg.FromConfig(cfg) (*T, error)`) and MUST NOT itself call shikumi.Load — the loader runs once at main, and a controller-go/cfg leaf is the shikumi adapter that produces the Config this takes. FromConfig and New share one construction path.
func New ¶
func New(cfg Config, r Reconciler, opts ...Option) (*Controller, error)
New constructs a Controller from a Config, a Reconciler, plus functional [Option]s — the canonical `pkg.New(required…, opts ...Option) (*T, error)` shape (BOREALIS §3.5). A zero Config is valid and yields sane defaults. New never itself loads config from disk — the loader lives once at main via shikumi (Law 3); use FromConfig to consume an already-loaded sub-struct.
New returns ErrNoReconciler if r is nil, ErrNoKind if no watched kind is configured (and no custom builder hook is supplied), and a wrapped error if the Config is internally inconsistent.
func (*Controller) Enqueue ¶
func (c *Controller) Enqueue(ctx context.Context, req Request) (ReconcileState, error)
Enqueue makes a Controller an Enqueuer: it drives one reconcile of the named object through the per-object FSM and returns the resulting state. This is the bridge that lets NewWebhook(controller) wire an inbound webhook to the same FSM the watch loop uses.
func (*Controller) Name ¶
func (c *Controller) Name() string
Name returns the controller name (Config.Name after defaults).
func (*Controller) Revive ¶
func (c *Controller) Revive(req Request) error
Revive transitions a deadlettered object's reconcile back to StatePending so it is retried from scratch — the only sanctioned exit from StateDeadletter (an operator action). Returns shigoto.ErrIllegalTransition if the object is not deadlettered.
func (*Controller) Run ¶
func (c *Controller) Run(ctx context.Context) error
Run starts the controller-runtime manager (building one from Config if none was supplied via WithManager) and runs it under a lifecycle.App, blocking until the app stops. It MUST be called at most once. The lifecycle choreography (signal handling, drain, ordered teardown) is owned by lifecycle-go; the chassis registers the manager's Start as a supervised lifecycle unit, so a manager that exits with an error tears the app down cleanly.
Run returns the first fatal error, or nil on a clean signalled shutdown.
func (*Controller) StateOf ¶
func (c *Controller) StateOf(req Request) ReconcileState
StateOf returns the current reconcile ReconcileState of the object named by req — the "what state is this object's reconcile in?" query, with one answer. It is the read side of the per-object FSM, safe to call concurrently with Run.
type EnqueueFunc ¶
type EnqueueFunc func(ctx context.Context, req Request) (ReconcileState, error)
EnqueueFunc adapts a plain function into an Enqueuer.
func (EnqueueFunc) Enqueue ¶
func (f EnqueueFunc) Enqueue(ctx context.Context, req Request) (ReconcileState, error)
Enqueue calls the wrapped function.
type Enqueuer ¶
type Enqueuer interface {
// Enqueue drives a reconcile of the named object. It returns the resulting
// [ReconcileState] and any reconcile error, so a webhook caller can be told
// whether the reconcile converged.
Enqueue(ctx context.Context, req Request) (ReconcileState, error)
}
Enqueuer accepts an out-of-band reconcile Request and drives it. It is the seam the Webhook adapter pushes decoded events onto, so the inbound-webhook path and the watch-event path converge on the same per-object reconcile FSM (pattern-registry §4a — "an inbound-webhook→enqueue adapter"). It is a pure stdlib interface (no controller-runtime), so the adapter is offline-testable.
type GVKConfig ¶
type GVKConfig struct {
// Group is the API group (empty for the core group, e.g. v1 Pods).
Group string `yaml:"group" json:"group,omitempty"`
// Version is the API version (e.g. "v1", "v1alpha1").
Version string `yaml:"version" json:"version,omitempty"`
// Kind is the resource kind (e.g. "Secret", "MyResource").
Kind string `yaml:"kind" json:"kind,omitempty"`
}
GVKConfig is the yaml-facing group/version/kind selector for the watched object. The chassis adapter resolves it to a controller-runtime client.Object via the manager's scheme.
type Option ¶
type Option func(*Controller)
Option configures a Controller at construction — the functional-options half of the canonical `New(required…, opts ...Option)` shape (BOREALIS §3.5).
func For ¶
For declares the watched object kind by group/version/kind — the programmatic alternative to Config.Kind. When both are set, For wins. It is the chassis's equivalent of controller-runtime's builder.For.
func WithBuilder ¶
WithBuilder supplies a hook to customise the controller-runtime builder before it is built — e.g. to add Owns/Watches/WithEventFilter. The hook receives the *builder.Builder; pass it as `func(*builder.Builder)`. Stored opaquely (the manager.go adapter applies it) so this file imports no controller-runtime.
func WithEmitter ¶
func WithEmitter(e shigoto.TransitionEmitter) Option
WithEmitter sets the shigoto.TransitionEmitter that receives every reconcile FSM transition — the audit/observability sink. The default is shigoto.NullEmitter (discard). A shigoto.JSONLEmitter over a log writer gives a greppable per-object reconcile-transition trail.
func WithGates ¶
WithGates registers per-object reconcile preconditions evaluated by the FSM before a reconcile runs. A gate that returns Wait (false, nil) parks the object in StateGated and requeues; a gate that refuses (non-nil error) skips it. Use it to model "do not reconcile until X is ready" without IO in the reconcile body (gates are pure — model IO-dependent preconditions as a fact a prior reconcile records, per shigoto's gate doctrine).
func WithLogger ¶
WithLogger sets the slog logger for chassis events (manager start/stop, reconcile FSM transitions, webhook enqueues). The default is a no-op logger.
func WithManager ¶
WithManager supplies a pre-built controller-runtime manager.Manager instead of letting Controller.Run build one from Config. Pass it as the concrete manager.Manager; the chassis stores it opaquely and the manager.go adapter type-asserts it. Use it when the manager must be shared (multiple controllers, a custom scheme/REST config).
type ReconcileFunc ¶
ReconcileFunc adapts a plain function into a Reconciler — the common authoring shape, so a consumer rarely declares a bespoke struct.
r := controller.ReconcileFunc(func(ctx context.Context, req controller.Request) (controller.Result, error) {
return controller.Done, nil
})
type ReconcileState ¶
ReconcileState is the per-object FSM state a single object's reconcile inhabits — a thin projection of shigoto's 10-state shigoto.JobPhase. Modeling reconcile as a shigoto FSM (pattern-registry §4a) means every object's reconcile advances through the same pure, table-driven shigoto.Advance transitions the rest of the fleet's work uses, and the transitions are auditable through shigoto's shigoto.TransitionEmitter.
The mapping from the reconcile lifecycle to shigoto phases:
Pending → a reconcile was enqueued, awaiting gate evaluation Ready → gates passed, awaiting a budget slot Reconciling → Reconcile is in flight (shigoto Running) Synced → Reconcile returned ok, converged (shigoto Succeeded) Errored → Reconcile returned an error (shigoto Failed) Backoff → a retry is scheduled, in its backoff window (shigoto Retrying) Deadletter → retries exhausted / non-retryable (shigoto Deadlettered)
ReconcileState is a comparable value (it IS the shigoto phase), so it is a usable map key and trivially serialisable.
type Reconciler ¶
type Reconciler interface {
// Reconcile converges the named object toward its desired state.
Reconcile(ctx context.Context, req Request) (Result, error)
}
Reconciler is the one interface a consumer implements — the typed, cluster-agnostic reconcile contract. It mirrors controller-runtime's reconcile.Reconciler but speaks the chassis's stdlib-only Request/Result shapes, so reconcile logic is offline-testable and names no controller-runtime type (Law 2 / WORLDS-SEPARATE).
Contract (the standard level-based reconcile contract):
- Reconcile MUST be idempotent: it is called repeatedly for the same object and must converge actual state toward desired state regardless of how many times it runs or what fired it.
- Reconcile MUST honour ctx cancellation (shutdown, per-reconcile timeout).
- A non-nil error requeues with backoff; a Result requests an explicit requeue; Done (the zero Result) with a nil error means converged.
- Reconcile MUST NOT assume the object still exists — a delete event also drives a reconcile, and the typical first step is a get that may 404.
type Request ¶
type Request struct {
// Namespace is the object's namespace (empty for cluster-scoped objects).
Namespace string `json:"namespace,omitempty"`
// Name is the object's name. Always set for a real reconcile.
Name string `json:"name"`
}
Request names the object a single reconcile is about — the typed input every Reconciler receives. It is the stdlib-only public mirror of controller-runtime's reconcile.Request (Law 2: a thin shape over the universal interface, named here so the core never forces a controller-runtime import on reconcile logic — WORLDS-SEPARATE / Law 6).
The chassis adapter (controller-go/runtime, build-tag gated) converts a controller-runtime reconcile.Request to this and back.
func (Request) Key ¶
Key returns the stable "namespace/name" key for the request — the same shape client-go's cache uses, and a natural map key / shigoto.JobID subject. A cluster-scoped object (empty Namespace) keys as just "name".
type Result ¶
type Result struct {
// Requeue asks the chassis to re-enqueue the request for immediate
// reprocessing (subject to the work queue's rate limiting).
Requeue bool `json:"requeue,omitempty"`
// RequeueAfter, when > 0, asks the chassis to re-enqueue the request after
// the given delay. It takes precedence over Requeue when both are set.
RequeueAfter time.Duration `json:"requeue_after,omitempty"`
}
Result is the typed reconcile outcome — the stdlib-only public mirror of controller-runtime's reconcile.Result. A zero Result means "done, do not requeue" (Done); set Result.Requeue to re-run immediately, or Result.RequeueAfter to re-run after a delay.
As in controller-runtime, returning a non-nil error from Reconciler.Reconcile also triggers a requeue with the controller's backoff — Result is for the success path's explicit requeue requests.
func Reconcile ¶
func Reconcile() Result
Reconcile builds a Result that re-runs the reconcile immediately (subject to the work queue's rate limiting). Use it for "I made progress but I'm not done converging yet".
func RequeueAfter ¶
RequeueAfter builds a Result that re-runs the reconcile after d. A non-positive d yields Done (no requeue).
type RetryConfig ¶
type RetryConfig struct {
// Kind selects the strategy: "none" (default), "fixed", or "exponential".
Kind RetryKindName `yaml:"kind" json:"kind,omitempty"`
// Attempts is the total attempts allowed for fixed / exponential.
Attempts uint32 `yaml:"attempts" json:"attempts,omitempty"`
// Delay is the constant delay for fixed.
Delay time.Duration `yaml:"delay" json:"delay,omitempty"`
// Base is the first backoff for exponential.
Base time.Duration `yaml:"base" json:"base,omitempty"`
// Max caps the exponential backoff.
Max time.Duration `yaml:"max" json:"max,omitempty"`
// Jitter is the ±fraction applied to the exponential backoff.
Jitter float64 `yaml:"jitter" json:"jitter,omitempty"`
}
RetryConfig is the yaml surface for the reconcile retry policy, converted to a shigoto.RetryPolicy by [RetryConfig.policy]. It keeps the controller config free of shigoto's enum spelling while reusing its battle-tested policy engine.
type RetryKindName ¶
type RetryKindName string
RetryKindName is the yaml-facing spelling of a shigoto.RetryPolicy kind.
const ( // RetryNone deadletters on the first reconcile error. RetryNone RetryKindName = "none" // RetryFixed retries with a constant delay. RetryFixed RetryKindName = "fixed" // RetryExponential retries with exponential backoff. RetryExponential RetryKindName = "exponential" )
type Webhook ¶
type Webhook struct {
// contains filtered or unexported fields
}
Webhook is the inbound-webhook→enqueue-reconcile adapter: an http.Handler that decodes a WebhookPayload and enqueues a reconcile onto an Enqueuer, so an out-of-band event drives the same reconcile FSM as a Kubernetes watch event.
It is a thin, composition-over-framework layer (Law 2) over net/http's http.Handler — the universal inbound interface — so it mounts on any mux (server-go, lifecycle-go's health mux, or its own server). Construct with NewWebhook.
func NewWebhook ¶
func NewWebhook(enq Enqueuer, opts ...WebhookOption) (*Webhook, error)
NewWebhook constructs the inbound-webhook adapter over enq — the canonical `New(required…, opts ...Option)` shape (BOREALIS §3.5). enq is typically the owning Controller (which satisfies Enqueuer via Controller.Enqueue), but any Enqueuer works, so the adapter is testable with a stub.
func (*Webhook) ServeHTTP ¶
func (w *Webhook) ServeHTTP(rw http.ResponseWriter, r *http.Request)
ServeHTTP decodes a WebhookPayload from the request body, enqueues a reconcile, and writes a WebhookResponse. It accepts only POST; a malformed body is 400, a missing name is 422, a reconcile error is 200 with the error in the response body (the webhook delivered; the reconcile is asynchronous in spirit even when driven synchronously here).
type WebhookConfig ¶
type WebhookConfig struct {
// Addr is the listen address for the webhook HTTP server (e.g. ":9443").
// Empty disables the webhook server.
Addr string `yaml:"addr" json:"addr,omitempty"`
// Path is the route the webhook handler is mounted on. Default "/reconcile".
Path string `yaml:"path" json:"path,omitempty"`
}
WebhookConfig configures the inbound-webhook→enqueue-reconcile adapter.
type WebhookOption ¶
type WebhookOption func(*Webhook)
WebhookOption configures a Webhook — the functional-options half of the canonical construct shape (BOREALIS §3.5).
func WithDefaultNamespace ¶
func WithDefaultNamespace(ns string) WebhookOption
WithDefaultNamespace sets the namespace applied when a payload omits one — for a single-namespace controller fronted by a webhook that only sends names.
func WithMaxBody ¶
func WithMaxBody(n int64) WebhookOption
WithMaxBody caps the decoded request body size in bytes (slowloris / OOM defence). Default 1 MiB. A non-positive value restores the default.
func WithWebhookLogger ¶
func WithWebhookLogger(log *slog.Logger) WebhookOption
WithWebhookLogger sets the logger for webhook events. Default no-op.
type WebhookPayload ¶
type WebhookPayload struct {
// Namespace is the object's namespace (empty for cluster-scoped objects).
Namespace string `json:"namespace,omitempty"`
// Name is the object's name (required).
Name string `json:"name"`
}
WebhookPayload is the JSON body an inbound webhook POSTs to enqueue a reconcile: it names the object to reconcile. It is intentionally minimal and generic — a vendor webhook, a UI button, or a CI step posts {"namespace":"…","name":"…"} and the chassis reconciles that object through the FSM. (WORLDS-SEPARATE: the payload names no vendor; a vendor-specific decoder is a private adapter that maps its body onto this shape.)
type WebhookResponse ¶
type WebhookResponse struct {
// Object is the "namespace/name" key that was reconciled.
Object string `json:"object"`
// State is the resulting [ReconcileState] name (e.g. "synced", "backoff").
State string `json:"state"`
// Error is the reconcile error message, empty on success.
Error string `json:"error,omitempty"`
}
WebhookResponse is the JSON body the Webhook returns: the resulting reconcile state and an error string if the reconcile failed.