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
- Variables
- func Get[T any](k Kernel, kind string, instance ...string) (T, bool)
- func SectionKeyOf(d Descriptor) string
- type AppStarted
- type AppStopped
- type Component
- type ComponentClosed
- type ComponentDegraded
- type ComponentInitialized
- type ComponentStatus
- type Config
- type Dep
- type Descriptor
- type Drainer
- type HealthEntry
- type HealthReport
- type HealthStatus
- type Healther
- type Kernel
- type Key
- type Logger
- type Middleware
- type Migrator
- type Mounter
- type PostReloadFunc
- type Readier
- type Registry
- func (r *Registry) Bus() *event.Bus
- func (r *Registry) Components() []ComponentStatus
- func (r *Registry) Config() *conf.Snapshot
- func (r *Registry) Failed() <-chan error
- func (r *Registry) Health(ctx context.Context) HealthReport
- func (r *Registry) Logger() Logger
- func (r *Registry) Lookup(kind string, instance ...string) (Component, bool)
- func (r *Registry) Ready(ctx context.Context) error
- func (r *Registry) Reload(ctx context.Context) error
- func (r *Registry) Start(ctx context.Context) error
- func (r *Registry) Stop(ctx context.Context) error
- type ReloadApplied
- type Reloader
- type Router
- type RouterProvider
- type RoutesFunc
- type SchemaOwner
- type Server
- type State
- type Timeouts
Constants ¶
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.
const DefaultInstance = "default"
DefaultInstance is the normalized name of the unnamed instance.
Variables ¶
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.
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.
var ErrNotStarted = errors.New("kernel: registry not started")
ErrNotStarted is returned by Reload when the registry has not completed startup (or has already stopped).
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 ¶
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 ¶
AppStarted fires once when startup completes (all components initialized, routes mounted, every Server ready).
type AppStopped ¶
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 ¶
ComponentClosed fires per component as Close completes during shutdown or startup rollback.
type ComponentDegraded ¶
ComponentDegraded fires when an Optional component's Init fails and startup continues without it.
type ComponentInitialized ¶
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 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 ¶
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 ¶
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 ¶
Key is the registry identity of a component: Descriptor.Kind plus the normalized instance name ("default" when Instance is "").
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 ¶
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 ¶
Migrator runs schema migration. Executed serially within each topological level, after that level's Init completes.
type Mounter ¶
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 ¶
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 ¶
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 ¶
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) Components ¶
func (r *Registry) Components() []ComponentStatus
Components lists every assembled component's observable status, disabled entries included, in assembly order.
func (*Registry) Failed ¶
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) Lookup ¶
Lookup implements Kernel: only enabled, initialized, not-yet-closed components are visible (SPEC §3.1 definition 2).
func (*Registry) Ready ¶
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 ¶
Reload executes config swap → component dispatch → post-reload callback, failing fast between stages. Overlapping calls receive ErrReloadInProgress immediately.
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 ¶
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 ¶
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 ¶
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) )