controller

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 23 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.

README

controller-go

pleme-io's borealis-style Kubernetes controller chassis: a reconcile loop modeled as a shigoto-go per-object FSM, driven over a sigs.k8s.io/controller-runtime Manager, supervised by lifecycle-go. Build a Kubernetes operator by supplying a typed Reconciler, a Config, and the kind to watch — the chassis owns everything else.

Composition over framework (BOREALIS Law 2). The chassis is a thin layer over the universal interfaces of its domain: Reconciler over controller-runtime's reconcile contract, lifecycle.App for the run loop, http.Handler for the inbound webhook. It never owns your reconcile logic.

Weight is import-gated (BOREALIS Law 6). The Reconciler / Request / Result / per-object FSM core is pure stdlib + shigoto-go, so reconcile logic is offline-testable without a cluster. Only one file (manager.go) imports controller-runtime — the chassis is the single place that weight lives.

What

A single importable Go package (Biblioteca) providing the BOREALIS pattern-registry §4a chassis primitive:

  • Reconciler — the one interface you implement: a cluster-agnostic Reconcile(ctx, Request) (Result, error). It names no controller-runtime type, mirroring the standard level-based reconcile contract.
  • Request / Result — the stdlib-only typed reconcile in/out (mirrors controller-runtime's reconcile.Request/Result), with Done, Reconcile(), and RequeueAfter(d) constructors.
  • per-object reconcile FSM — every object's reconcile advances through the same pure, table-driven shigoto.Advance states (Pending → Ready → Reconciling → Synced | Errored → Backoff | Deadletter), with retry classification (honouring shigoto.ErrSkipRetry), backoff windows, and audit transitions via a shigoto.TransitionEmitter.
  • Controller — the chassis: New(cfg, reconciler, opts…) then Run(ctx) starts the manager under lifecycle.App.
  • Webhook — the inbound-webhook → enqueue-reconcile adapter: an http.Handler that decodes an external event and drives the same FSM as a watch event.

Why

Three concerns recur in every Kubernetes operator, and writing them per-operator is the duplication the PRIME DIRECTIVE forbids:

Concern Without the chassis With controller-go
Reconcile state + retry/backoff classification hand-rolled per-CR booleans + requeue math the shigoto per-object FSM (one fleet answer to "what state is this object in?")
Manager lifecycle (signals, drain, ordered teardown) bespoke signal.NotifyContext + mgr.Start glue run under lifecycle.App (the K8s shutdown choreography for free)
Out-of-band reconcile triggers (vendor webhook, UI) a parallel HTTP server that re-implements enqueue the Webhook adapter onto the same FSM

The chassis backs every operator (pattern-registry consumers C2 / C3 / C12) so producing a new, consistent, well-behaved Kubernetes controller is a declarative act, not a copy-paste of manager boilerplate.

Install

go get github.com/pleme-io/controller-go
import controller "github.com/pleme-io/controller-go"

Nix (build-verification check via the substrate go-library-flake):

nix build github:pleme-io/controller-go        # runs `go build ./...` in the sandbox
nix run github:pleme-io/controller-go#check-all # full GSDS check surface

Usage

A whole operator, end to end:

package main

import (
	"context"

	controller "github.com/pleme-io/controller-go"
	errs "github.com/pleme-io/errors-go"
)

type reconciler struct{}

func (reconciler) Reconcile(ctx context.Context, req controller.Request) (controller.Result, error) {
	// Fetch the object via your client, converge actual → desired state.
	// Return controller.Done when converged, controller.RequeueAfter(d) to
	// re-run later, or a non-nil error to requeue with backoff.
	return controller.Done, nil
}

func run() error {
	c, err := controller.New(controller.Config{Name: "my-operator"}, reconciler{},
		controller.For(controller.GVKConfig{Group: "apps", Version: "v1", Kind: "Deployment"}))
	if err != nil {
		return err
	}
	return c.Run(context.Background()) // blocks; runs the manager under lifecycle-go
}

func main() { errs.Exit(run()) } // the one process-exit funnel (errors-go)
Per-object reconcile FSM

Each object's reconcile is a shigoto FSM. Query and drive it:

state := c.StateOf(controller.Request{Namespace: "default", Name: "web"})
// state ∈ {StatePending, StateGated, StateReady, StateReconciling,
//          StateSynced, StateErrored, StateBackoff, StateDeadletter}

// Revive a deadlettered object (operator action — the only exit from terminal failure):
_ = c.Revive(controller.Request{Namespace: "default", Name: "web"})

Attach pure preconditions (no IO — model IO-dependent gates as a fact a prior reconcile records) and an audit sink:

import shigoto "github.com/pleme-io/shigoto-go"

c, _ := controller.New(cfg, reconciler{},
	controller.For(gvk),
	controller.WithGates(shigoto.GateFunc(func(ctx context.Context) (bool, error) {
		return dependencyReady(), nil // false → object parks in StateGated
	})),
	controller.WithEmitter(shigoto.NewJSONLEmitter(os.Stdout))) // greppable transition trail
Inbound-webhook → enqueue-reconcile

Config.Webhook.Addr stands up an HTTP server that drives the same FSM as a watch event when it receives POST {"namespace":"…","name":"…"}:

cfg := controller.Config{
	Name:    "my-operator",
	Webhook: controller.WebhookConfig{Addr: ":9443", Path: "/reconcile"},
}

Or mount the adapter on your own mux (it is a plain http.Handler):

wh, _ := controller.NewWebhook(c) // *Controller satisfies Enqueuer
mux.Handle("/reconcile", wh)

Configuration

Config is the typed, yaml-tagged runtime policy (BOREALIS Law 3) — loaded once at main via shikumi-go and handed to FromConfig(cfg, reconciler); the constructors never call shikumi.Load themselves. A zero Config is valid.

name: my-operator
kind:
  group: apps
  version: v1
  kind: Deployment
metrics_addr: ""          # "" disables the manager's metrics server (metrics-go owns /metrics)
leader_election: true
max_concurrent_reconciles: 4
reconcile_timeout: 30s    # 0 = no per-reconcile timeout
retry:
  kind: exponential       # none | fixed | exponential
  attempts: 5
  base: 1s
  max: 5m
  jitter: 0.2
webhook:
  addr: ":9443"           # "" disables the inbound webhook
  path: /reconcile
lifecycle:                # embedded lifecycle-go Config (signals, drain, grace, health)
  drain_interval: 5s
  shutdown_grace: 30s
  health:
    addr: ":8081"

Consume it:

c, err := controller.FromConfig(cfg, reconciler{})

Release

This library follows the pleme-io Go pull-model release: a semver git tag is pushed (no artifact upload); proxy.golang.org fetches the module lazily. Releases are cut through the substrate go-library-flake surface (forge tool release --language go) and the auto-release workflow declared in caixa.lisp. See CHANGELOG.md for the release history (Keep a Changelog format, SemVer).

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

View Source
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

View Source
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
View Source
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.

View Source
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.

View Source
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.

func (GVKConfig) IsZero

func (g GVKConfig) IsZero() bool

IsZero reports whether no kind was configured.

func (GVKConfig) String

func (g GVKConfig) String() string

String renders the GVK as "group/version, Kind=kind" for diagnostics.

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

func For(gvk GVKConfig) Option

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

func WithBuilder(hook any) Option

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

func WithGates(gates ...shigoto.Gate) Option

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

func WithLogger(log *slog.Logger) Option

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

func WithManager(mgr any) Option

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

type ReconcileFunc func(ctx context.Context, req Request) (Result, error)

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
})

func (ReconcileFunc) Reconcile

func (f ReconcileFunc) Reconcile(ctx context.Context, req Request) (Result, error)

Reconcile calls the wrapped function.

type ReconcileState

type ReconcileState = shigoto.JobPhase

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

func (r Request) Key() string

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

func RequeueAfter(d time.Duration) Result

RequeueAfter builds a Result that re-runs the reconcile after d. A non-positive d yields Done (no requeue).

func (Result) IsZero

func (r Result) IsZero() bool

IsZero reports whether the result requests neither a requeue nor a delayed requeue — i.e. the reconcile is done. Equivalent to r == Done.

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.

Jump to

Keyboard shortcuts

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