kernel

package
v2.0.0-beta.6 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package kernel is the chok v2 component model: a declarative Descriptor, a small set of behaviour interfaces discovered by type assertion, and a single-actor control plane (Registry) that owns every lifecycle transition.

Design axioms (SPEC §1): invariants live in types, not docs; the kernel knows no battery names — ordering, draining and observability all flow through Descriptor fields and behaviour interfaces.

Index

Constants

View Source
const (
	DefaultInitTimeout   = 30 * time.Second
	DefaultCloseTimeout  = 15 * time.Second
	DefaultReloadTimeout = 10 * time.Second
)

Default lifecycle budgets (mini-SPEC §3.4); Config.Defaults overrides globally, Descriptor.Timeouts per component.

View Source
const DefaultInstance = "default"

DefaultInstance is the normalized name of the unnamed instance.

Variables

View Source
var ErrAlreadyStarted = errors.New("kernel: registry already started")

ErrAlreadyStarted is returned by Start on a second call — the registry, like the App, is single-use.

View Source
var ErrDraining = errors.New("kernel: draining")

ErrDraining is returned by Ready while the draining phase is in progress: readiness endpoints turn 503 before traffic is dropped.

View Source
var ErrNotStarted = errors.New("kernel: registry not started")

ErrNotStarted is returned by Reload when the registry has not completed startup (or has already stopped).

View Source
var ErrReloadInProgress = errors.New("kernel: reload already in progress")

ErrReloadInProgress is returned by Reload when another reload is still being processed. Concurrent triggers coalesce — the loser is told, never queued (v1 contract preserved, SPEC §3.3).

Functions

func Get

func Get[T any](k Kernel, kind string, instance ...string) (T, bool)

Get is the typed dependency accessor (SPEC §3.1 definition 2):

db, ok := kernel.Get[*db.Component](k, "db")          // default
ro, ok := kernel.Get[*db.Component](k, "db", "read")  // named

The second value is false when the component is absent, disabled, failed, closed, or not of type T.

func SectionKeyOf

func SectionKeyOf(d Descriptor) string

SectionKeyOf resolves the config section key a Descriptor addresses (mini-SPEC §1): ConfigKey for the default instance, ConfigKey + ".instances." + Instance for named ones, "" when the component has no configuration.

Types

type AppStarted

type AppStarted struct {
	Duration time.Duration
}

AppStarted fires once when startup completes (all components initialized, routes mounted, every Server ready).

type AppStopped

type AppStopped struct {
	Duration time.Duration
}

AppStopped fires after the last component closed, immediately before the bus itself drains and closes.

type Component

type Component interface {
	Describe() Descriptor
	Init(ctx context.Context, k Kernel) error
	Close(ctx context.Context) error
}

Component is the mandatory contract every subsystem implements.

Describe must be pure and callable before Init: the Registry reads it during assembly to build the dependency graph, derive the config section and order mounting. Init receives the Kernel for config, logging, bus access and dependency lookup. Close releases resources; it can no longer reach peers (the Kernel view has already shrunk — a structural guarantee, not a convention).

type ComponentClosed

type ComponentClosed struct {
	Key      Key
	Duration time.Duration
	Err      string // "" on clean close
}

ComponentClosed fires per component as Close completes during shutdown or startup rollback.

type ComponentDegraded

type ComponentDegraded struct {
	Key Key
	Err string
}

ComponentDegraded fires when an Optional component's Init fails and startup continues without it.

type ComponentInitialized

type ComponentInitialized struct {
	Key      Key
	Duration time.Duration
}

ComponentInitialized fires per component as Init succeeds.

type ComponentStatus

type ComponentStatus struct {
	Key        Key
	Descriptor Descriptor
	ConfigKey  string // derived section key ("" = none)
	State      State
	Err        string // last lifecycle error, "" when none
}

ComponentStatus is the observable record for one component — /componentz and Health render from this, disabled entries included (SPEC §3.1 definition 3: disabled is visible, not vanished).

type Config

type Config struct {
	Logger     Logger
	Store      *conf.Store
	Bus        *event.Bus
	Components []Component
	Routes     RoutesFunc     // optional user route callback
	PostReload PostReloadFunc // optional WithReloadFunc callback
	Defaults   Timeouts       // zero fields fall back to package defaults
	DrainDelay time.Duration
}

Config assembles a Registry.

type Dep

type Dep struct {
	Kind     string
	Instance string // "" ⇒ "default"
	Optional bool
}

Dep is a dependency edge in Descriptor.Needs.

type Descriptor

type Descriptor struct {
	// Kind names the capability: "db", "http", "account", ...
	// Required, non-empty.
	Kind string

	// Instance distinguishes multiple components of one Kind.
	// "" means "default". Named instances resolve their config at
	// ConfigKey + ".instances." + Instance (M1 mini-SPEC §1).
	Instance string

	// ConfigKey is the yaml section this component owns. "" means the
	// component has no configuration: it is always enabled and, when
	// it implements Reloader, it is dispatched on every config reload
	// after all sectioned components (SPEC §3.4).
	ConfigKey string

	// Options is a zero-value sample of the ConfigKey section's typed
	// Options struct. The App collects these at assembly time to drive
	// env binding, `default` tags, validation and reload tag diffing
	// (SPEC §3.4 "framework section types collected via Use()").
	// nil = the section stays untyped (ad-hoc decode only).
	Options any

	// Schema describes database tables this component owns and is
	// responsible for evolving. It is descriptive metadata only: declaring
	// a table does not execute migration behavior. Repository generators
	// aggregate the declarations of chok's built-in modules; downstream
	// components remain responsible for consuming their own declarations.
	Schema SchemaOwner

	// Needs declares dependencies on other components by (Kind,
	// Instance). Hard dependencies gate startup ordering and fail
	// startup when missing or disabled; Optional ones degrade to
	// absence.
	Needs []Dep

	// Timeouts bounds Init / Close / Reload for this component.
	// Zero values fall back to the App-level defaults.
	Timeouts Timeouts

	// Optional marks the whole component non-critical: Init failure
	// logs a warning and reports Degraded instead of aborting startup.
	Optional bool

	// MountOrder orders Mounter invocation within the mount phase:
	// <= 0 mounts before the user Routes callback (ties broken by
	// topological start order), > 0 mounts after it in ascending
	// order. A docs-style component that must see every route (e.g.
	// swagger) declares a large positive value itself — the kernel
	// has no name-based special cases.
	MountOrder int
}

Descriptor is the component's static self-declaration. It replaces v1's seven single-method declaration interfaces (Dependent, ConfigKeyer, Optionaler, *Timeouter, ...) with plain data.

type Drainer

type Drainer interface {
	Drain(ctx context.Context)
}

Drainer is notified at the start of the draining phase (broadcast, parallel, short timeout) so implementations can flip readiness endpoints to 503 or stop accepting new work before Serve contexts are cancelled. The kernel does not know which component is "health".

type HealthEntry

type HealthEntry struct {
	Key      Key
	Status   HealthStatus
	Err      string
	Duration time.Duration
}

HealthEntry is one component's health line.

type HealthReport

type HealthReport struct {
	Status  HealthStatus
	Entries []HealthEntry
}

HealthReport aggregates probe results: any required component down ⇒ Down; optional failures and degraded components ⇒ Degraded; disabled entries are informational.

type HealthStatus

type HealthStatus string

HealthStatus classifies one component's probe outcome.

const (
	HealthUp       HealthStatus = "up"
	HealthDegraded HealthStatus = "degraded"
	HealthDown     HealthStatus = "down"
	HealthDisabled HealthStatus = "disabled" // informational, aggregates as OK
)

type Healther

type Healther interface {
	Health(ctx context.Context) error
}

Healther reports component health. Probed in parallel with a fan-in timeout by the registry's Health aggregation.

type Kernel

type Kernel interface {
	// Config returns the current immutable configuration snapshot.
	Config() *conf.Snapshot

	// Logger returns the root logger (owned by the App, alive strictly
	// longer than every component).
	Logger() Logger

	// Bus returns the process event bus.
	Bus() *event.Bus

	// Lookup returns the component registered under (kind, instance)
	// when it is enabled and currently usable (initialized, not yet
	// closed). Disabled, failed and closed components return false —
	// callers can never observe a half-initialized object.
	Lookup(kind string, instance ...string) (Component, bool)

	// Health probes every Healther (parallel, panic-isolated) and
	// aggregates; disabled entries appear as informational. Read
	// path — never enters the control actor.
	Health(ctx context.Context) HealthReport

	// Ready aggregates readiness: ErrDraining during the draining
	// phase, then required-component state plus every Readier.
	Ready(ctx context.Context) error

	// Components lists every assembled component's observable status
	// (Descriptor-sourced; disabled included) in assembly order.
	Components() []ComponentStatus
}

Kernel is what a component sees in Init: configuration, logging, the event bus and dependency lookup. Implemented by the Registry.

Dependency access happens in Init (SPEC §11.4): by Close time the published view has already shrunk, so "don't call Lookup in Close" is not a convention — the peer simply isn't there.

type Key

type Key struct {
	Kind     string
	Instance string
}

Key is the registry identity of a component: Descriptor.Kind plus the normalized instance name ("default" when Instance is "").

func KeyOf

func KeyOf(d Descriptor) Key

KeyOf derives the registry Key from a Descriptor.

func (Key) String

func (k Key) String() string

String renders "kind" for the default instance and "kind@instance" otherwise. Display form only — the @ form is NOT a config key (config addressing is nested, see mini-SPEC §1).

type Logger

type Logger interface {
	Debug(msg string, keysAndValues ...any)
	Info(msg string, keysAndValues ...any)
	Warn(msg string, keysAndValues ...any)
	Error(msg string, keysAndValues ...any)
	DebugContext(ctx context.Context, msg string, keysAndValues ...any)
	InfoContext(ctx context.Context, msg string, keysAndValues ...any)
	WarnContext(ctx context.Context, msg string, keysAndValues ...any)
	ErrorContext(ctx context.Context, msg string, keysAndValues ...any)
}

Logger is the kernel's consumer-side logging contract. The rich chok log.Logger satisfies it structurally; keeping the definition here (instead of importing the log package) leaves log free to import kernel for log.Module — the dependency arrow points one way: log → kernel → conf.

type Middleware

type Middleware = func(http.Handler) http.Handler

Middleware is the framework-wide middleware shape: a plain http.Handler decorator. Defined in kernel (stdlib-only) so the mount contract does not depend on the web implementation package; web aliases these types for user-facing code (SPEC §3.2).

type Migrator

type Migrator interface {
	Migrate(ctx context.Context) error
}

Migrator runs schema migration. Executed serially within each topological level, after that level's Init completes.

type Mounter

type Mounter interface {
	Mount(r Router) error
}

Mounter registers HTTP routes during the mount phase. The Router contract is stdlib-only (see router.go); the concrete implementation arrives with the web package (M2) — tests use doubles.

type PostReloadFunc

type PostReloadFunc func(ctx context.Context) error

PostReloadFunc is the user post-reload callback (WithReloadFunc): invoked synchronously as the last reload stage, only when config swap and component dispatch both succeeded; its error fails the reload (v1 contract, SPEC §9).

type Readier

type Readier interface {
	ReadyCheck(ctx context.Context) error
}

Readier gates readiness beyond plain health: Ready aggregation consults it (e.g. connection warm-up, initial cache fill).

type Registry

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

Registry is the single-actor control plane: every lifecycle transition (start / stop / reload) executes on one goroutine, and the read path (Lookup / Health / Ready / Components) works off an atomically-published immutable view. There is no lock order to memorize because there are no competing writers (SPEC §3.3).

func New

func New(cfg Config) (*Registry, error)

New assembles a Registry. Duplicate (kind, instance) keys fail fast — intentional replacement is the App's Override job, resolved before the Registry sees the list.

func (*Registry) Bus

func (r *Registry) Bus() *event.Bus

Bus implements Kernel.

func (*Registry) Components

func (r *Registry) Components() []ComponentStatus

Components lists every assembled component's observable status, disabled entries included, in assembly order.

func (*Registry) Config

func (r *Registry) Config() *conf.Snapshot

Config implements Kernel.

func (*Registry) Failed

func (r *Registry) Failed() <-chan error

Failed delivers the error of an unexpected Server exit: the App's run loop treats it as a shutdown trigger.

func (*Registry) Health

func (r *Registry) Health(ctx context.Context) HealthReport

Health probes every Healther in parallel with a fan-in budget and classifies the aggregate (SPEC §0.3 rules preserved).

func (*Registry) Logger

func (r *Registry) Logger() Logger

Logger implements Kernel.

func (*Registry) Lookup

func (r *Registry) Lookup(kind string, instance ...string) (Component, bool)

Lookup implements Kernel: only enabled, initialized, not-yet-closed components are visible (SPEC §3.1 definition 2).

func (*Registry) Ready

func (r *Registry) Ready(ctx context.Context) error

Ready aggregates readiness: draining fails immediately (503 before traffic drop), then every enabled required component must be Ready and every Readier must pass.

func (*Registry) Reload

func (r *Registry) Reload(ctx context.Context) error

Reload executes config swap → component dispatch → post-reload callback, failing fast between stages. Overlapping calls receive ErrReloadInProgress immediately.

func (*Registry) Start

func (r *Registry) Start(ctx context.Context) error

Start runs the full startup sequence and returns once every Server is ready (or with the startup error after rollback). Single-use.

func (*Registry) Stop

func (r *Registry) Stop(ctx context.Context) error

Stop drains and closes everything. Safe to call at any time; idempotent once stopped.

type ReloadApplied

type ReloadApplied struct {
	Duration time.Duration
	// Reloaded lists components that received a Reload call.
	Reloaded []string
	// RestartPending lists changed restart-only field paths that were
	// warn-logged and NOT applied to running components.
	RestartPending []string
}

ReloadApplied fires when a reload fully succeeds (config swapped, components dispatched, user callback returned nil).

type Reloader

type Reloader interface {
	Reload(ctx context.Context) error
}

Reloader receives config-driven reload dispatch. Components with a ConfigKey are called only when their section's hot fields changed (conf tag diff); components without a ConfigKey are called on every config change, after all sectioned components.

type Router

type Router interface {
	// Handle registers h for the method and pattern, wrapped by the
	// given middleware (outermost first).
	Handle(method, pattern string, h http.Handler, mw ...Middleware)

	// Group returns a sub-router rooted at prefix whose registrations
	// inherit the group middleware.
	Group(prefix string, mw ...Middleware) Router
}

Router is the route-registration contract handed to Mounter implementations and the user Routes callback during the mount phase. The kernel depends only on net/http here; the concrete implementation ships with the web package (M2). Tests assert mounting behaviour through doubles of this interface.

type RouterProvider

type RouterProvider interface {
	ProvideRouter() Router
}

RouterProvider is implemented by the (single) component that owns the HTTP router — the web module in the target architecture. The mount phase asks it for the Router handed to every Mounter and the Routes callback. Assembling more than one provider is a startup error; assembling Mounters (or Routes) with no provider is too.

This is a kernel-side discovery contract, not a battery name: any component may fill the role (fixtures use a test double).

type RoutesFunc

type RoutesFunc func(r Router) error

RoutesFunc is the user route-registration callback, invoked between MountOrder ≤ 0 and > 0 mounters during the mount phase.

type SchemaOwner

type SchemaOwner struct {
	Tables []string
}

SchemaOwner is a component's static database-schema declaration. Tables must be non-empty and uniquely owned when declarations are aggregated. Empty means the component owns no database schema.

type Server

type Server interface {
	Serve(ctx context.Context, ready func()) error
}

Server is the long-running behaviour: Serve blocks until ctx is cancelled, calling ready exactly once when it can accept work. All Servers run in parallel after mount; the registry aggregates ready before reporting the app started. In-flight work must finish before Serve returns — the draining phase waits for every Serve to return before any component Close runs, so dependencies stay alive during wind-down.

type State

type State string

State is a component's lifecycle position as published in the view.

const (
	StatePending  State = "pending"  // assembled, not yet initialized
	StateReady    State = "ready"    // Init succeeded
	StateDegraded State = "degraded" // Optional component whose Init failed
	StateDisabled State = "disabled" // enabled:false at startup
	StateClosed   State = "closed"   // Close completed (or rolled back)
	StateFailed   State = "failed"   // required startup-phase failure (pre-rollback)
)

type Timeouts

type Timeouts struct {
	Init   time.Duration
	Close  time.Duration
	Reload time.Duration
}

Timeouts bounds the component's lifecycle calls. Zero values use the registry-wide defaults (Init 30s / Close 15s / Reload 10s unless overridden at App level).

Directories

Path Synopsis
Package event is the chok v2 business event bus: typed pub/sub with per-subscriber bounded queues.
Package event is the chok v2 business event bus: typed pub/sub with per-subscriber bounded queues.

Jump to

Keyboard shortcuts

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