lifecycle

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: 14 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

lifecycle-go

Go representation of pleme-io's service-lifecycle model. The Go counterpart to the Rust service-lifecycle crate: the same model, so every Go service and tool supervises itself the same way — one signal-aware context, one ordered graceful shutdown, one health surface, one run-loop.

No ad-hoc signal.Notify boilerplate, no hand-rolled shutdown ordering, no per-service /healthz handler. Wire one App once; every binary behaves identically under SIGINT/SIGTERM, a failing dependency, and a Kubernetes probe.

The single external dependency is golang.org/x/sync/errgroup (Go-team owned, de-facto stdlib) for the ctx-aware goroutine group. Everything else is stdlib (context, os/signal, log/slog, errors, net/http).

App — the composed owner (BOREALIS §2.5)

lifecycle.App is the one owner that runs the work, flips readiness, drains, and tears down in order. Construct it the canonical way and call Run once:

app, err := lifecycle.New(cfg.Lifecycle, lifecycle.WithLogger(log))
// or: lifecycle.FromConfig(cfg.Lifecycle)   // consumes the shikumi sub-struct
if err != nil { return err }

app.Go("reconcile", reconcileLoop).                       // errgroup (ctx-aware)
    Actor("http",  srv.serve, func(error){ srv.Close() }). // oklog/run shape
    Supervise("poller", poll, lifecycle.DefaultBackoff()). // suture-style restart
    Probe("db", lifecycle.ProbeFunc(db.PingContext)).      // readiness dependency
    OnShutdown("db", func(context.Context) error { return db.Close() })

return app.Run(ctx)   // encodes the k8s shutdown choreography

Run choreography, in order:

  1. derive a signal-aware run context;
  2. mount the health planes (+ the deferred /metrics seam) and start any periodic probe loops;
  3. run the work group — the first fatal error or a delivered signal begins teardown;
  4. flip readiness DOWN first → drain (sleep DrainInterval and, concurrently, run every OnDrain remote-session Drainable inside that one window) → cancel the group → wait → run the LIFO Shutdown stack under ShutdownGrace (kept below the pod's terminationGracePeriodSeconds). This ordering eliminates rolling-deploy 502s.
Draining remote sessions (OnDrain / Drainable)

The readiness-down sleep only tells external load balancers to stop sending new traffic — it does nothing about sessions the process is already holding on a remote peer (SRA SSH/web sessions, a SOCKS tunnel, an event-forwarding channel, a long-poll subscription). A local LIFO OnShutdown close stack cannot reach those: the sessions live on the peer, not in this process. OnDrain registers a Drainable that runs during the drain window to release them:

app.OnDrain("sra-sessions", lifecycle.DrainFunc(func(ctx context.Context) error {
    sra.StopAcceptingSessions()           // refuse new remote sessions
    return sra.WaitForActiveSessions(ctx) // let live ones finish within ctx
}))

All registered drainers run concurrently (different peers, independent waits) under the single DrainInterval budget — a Drainable that ignores its ctx deadline is abandoned (and reported as an error) when the window closes, never blocking past the budget. Panics are isolated. Registering after Run starts is ignored. With no drainers registered the drain is exactly the historical sleep. Use OnShutdown for local resources, OnDrain for remote sessions.

Three goroutine shapes
Verb Shape Use when
app.Go(name, fn) x/sync/errgroup (ctx-aware) the work watches a context
app.Actor(name, execute, interrupt) oklog/run pair (in-package) the work blocks and can't watch ctx (Accept loops)
app.Supervise(name, fn, backoff) suture-style restart (in-package) the work should restart with backoff on crash

Supervise honours ErrDoNotRestart (stop cleanly) and ErrTerminate (stop and propagate). Every spawned unit and shutdown hook recovers panics into errors.

The four leaf primitives

App composes four primitives that are also usable directly:

  • SignalContext — a context.Context that cancels when the process is signalled (SIGINT/SIGTERM by default). The root of every run.
  • Shutdown — named hooks run in LIFO order under a single deadline, with errors aggregated (errors.Join). The observable analog of a defer stack.
  • Registry / Probe — liveness/readiness/startup aggregation, tri-state (up/down/unknown), optional per-probe WithCache/WithPeriodic, transition listeners, plus a stdlib http.Handler exposing /livez,/healthz,/readyz, /startupz. lifecycle-go is the single fleet owner of the health planes.
  • RunLoop — a ticking work loop that stops on context cancellation, with optional exponential backoff on error.

Usage

package main

import (
	"context"
	"log/slog"
	"net/http"
	"time"

	"github.com/pleme-io/lifecycle-go"
)

func main() {
	// 1. Root context cancels on SIGINT/SIGTERM.
	ctx, stop := lifecycle.SignalContext(context.Background())
	defer stop()

	// 2. Ordered, bounded teardown (LIFO — reverse of acquisition order).
	srv := &http.Server{Addr: ":8080"}
	sd := lifecycle.NewShutdown(slog.Default())
	sd.Add("http-server", srv.Shutdown)
	sd.Add("db", func(context.Context) error { return db.Close() })

	// 3. Health surface for Kubernetes probes.
	reg := lifecycle.NewRegistry()
	reg.RegisterLiveness("self", lifecycle.ProbeFunc(func(context.Context) error { return nil }))
	reg.RegisterReadiness("db", lifecycle.ProbeFunc(db.PingContext))
	srv.Handler = reg.Handler() // serves /healthz and /readyz

	go srv.ListenAndServe()

	// 4. Background work loop, with backoff on error.
	go lifecycle.RunLoop(ctx, 30*time.Second, reconcile,
		lifecycle.WithLoopLogger(slog.Default()),
		lifecycle.WithBackoff(5*time.Minute),
	)

	<-ctx.Done() // a signal arrived
	_ = sd.Run(context.Background(), 30*time.Second)
}

Health endpoints

Path Plane Question Failure action (k8s)
/healthz, /livez liveness "is the process wedged?" restart the pod
/readyz readiness "can it serve traffic now?" pull from rotation
/startupz startup "has it finished booting?" gate liveness during boot

Each returns 200 when its plane is OK and 503 otherwise, with a small JSON body — {"status":"ok"|"fail","checks":{<name>:"ok"|<error>}} — for humans and log scrapers. Keep liveness probes dependency-free so a flaky downstream never triggers restarts.

Shutdown ordering

Hooks run last-in-first-out: the resource registered last (typically acquired last) is released first. The HTTP server stops accepting before the DB pool closes, the pool closes before the metrics flusher, and so on. Errors are aggregated with errors.Join, never short-circuited — one failing close does not skip the rest. Once the per-shutdown deadline passes, remaining hooks are skipped and reported.

Run-loop options

  • WithImmediateTick() — fire once on entry before the first interval.
  • WithStopOnError() — a tick error terminates the loop (becomes the return).
  • WithBackoff(max) — double the inter-tick delay on consecutive errors up to max, resetting on the first success.
  • WithLoopLogger(log) — log tick errors and backoff decisions.

Build & test

go build ./...
go test ./...

Documentation

Overview

Package lifecycle is the Go representation of pleme-io's service-lifecycle model. It mirrors the Rust `service-lifecycle` crate so Go services and tools supervise themselves the same way everywhere: one signal-aware context, one ordered graceful-shutdown sequence, one health surface, one run-loop.

The mandate, like the Rust crate: no ad-hoc signal.Notify boilerplate, no hand-rolled shutdown ordering, no per-service /healthz handlers. Wire the four primitives and every binary behaves identically under SIGINT/SIGTERM, under a failing dependency, and under a Kubernetes probe.

The composed owner is App: one type (signal ctx + goroutine group + three-plane health + ordered shutdown + shikumi config) with one App.Run that encodes the Kubernetes shutdown choreography (flip readiness down → drain → LIFO teardown, inside a budget). It composes four leaf primitives that are also usable directly:

  • SignalContext — a context.Context that cancels when the process is signalled (SIGINT/SIGTERM by default). The root of every run.
  • Shutdown — named hooks run in LIFO order under a single deadline, with errors aggregated. The teardown analog of a defer stack.
  • Registry / Probe — liveness/readiness/startup aggregation (tri-state, cached/periodic, transition listeners) plus a stdlib net/http handler exposing /livez, /healthz, /readyz, /startupz. lifecycle-go is the single fleet owner of the health planes (BOREALIS §3.5).
  • RunLoop — a ticking work loop that stops on context cancellation, with optional exponential backoff on error.

The only external dependency is golang.org/x/sync/errgroup (Go-team owned) for the ctx-aware goroutine group; everything else is stdlib (context, os/signal, log/slog, errors, net/http). The oklog/run actor group and the suture-style restart backoff are re-expressed in-package (BOREALIS Law 6).

Typical wiring with the composed owner:

app, _ := lifecycle.New(cfg.Lifecycle, lifecycle.WithLogger(log))
app.Go("reconcile", reconcileLoop).
    Actor("http", srv.serve, func(error) { srv.Close() }).
    Supervise("poller", poll, lifecycle.DefaultBackoff()).
    Probe("db", lifecycle.ProbeFunc(db.PingContext)).
    OnShutdown("db", func(context.Context) error { return db.Close() })
return app.Run(ctx)

Or wire the leaf primitives directly:

ctx, stop := lifecycle.SignalContext(context.Background())
defer stop()
var sd lifecycle.Shutdown
sd.Add("db", func(context.Context) error { return db.Close() })
<-ctx.Done()
_ = sd.Run(context.Background(), 30*time.Second)

Index

Constants

This section is empty.

Variables

View Source
var DefaultSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM}

DefaultSignals are the signals SignalContext watches when none are passed: SIGINT (Ctrl-C / local interrupt) and SIGTERM (the orchestrator's polite "please stop", e.g. Kubernetes pod termination, systemd stop).

View Source
var ErrDoNotRestart = errors.New("lifecycle: do not restart")

ErrDoNotRestart, returned by a ServiceFunc, stops its supervision loop without treating the stop as a failure (the supervisor exits nil). Use it for a service that has done its job and should not be restarted.

View Source
var ErrTerminate = errors.New("lifecycle: terminate")

ErrTerminate, returned by a ServiceFunc, stops its supervision loop AND surfaces as the supervisor's error — a fatal condition the whole app should observe (it propagates out of App.Run). Use it for an unrecoverable failure that should bring the process down rather than restart-loop.

Functions

func RunLoop

func RunLoop(ctx context.Context, every time.Duration, tick TickFunc, opts ...LoopOption) error

RunLoop ticks tick every interval until ctx is cancelled, then returns ctx.Err() (or nil if a tick error or stop-on-error terminated it first). It is the Go analog of the Rust crate's supervised run-loop: a single cancellable cadence with optional backoff-on-error, so periodic work — reconcile passes, metric scrapes, token refreshes — shares one shape.

Behaviour:

  • With no options, ticks at a fixed interval; tick errors are non-fatal (logged, retried next interval).
  • WithImmediateTick fires once on entry before the first wait.
  • WithStopOnError turns the first tick error into the return value.
  • WithBackoff widens the inter-tick delay exponentially while ticks keep failing, resetting on the first success.

An interval of zero or less is treated as a minimal positive interval to avoid a busy spin. RunLoop always returns; it never blocks past ctx cancellation (an in-flight tick is awaited, but the next wait observes the cancellation).

func SignalContext

func SignalContext(parent context.Context, sigs ...os.Signal) (context.Context, context.CancelFunc)

SignalContext returns a child of parent that is cancelled the first time one of sigs is delivered to the process. When sigs is empty it watches DefaultSignals (SIGINT, SIGTERM).

It is a thin, intention-revealing wrapper over signal.NotifyContext: the returned context's cancellation means "the process was asked to stop", which is the root signal every other lifecycle primitive keys off. The returned context.CancelFunc must be called (typically deferred) to release the signal handler and restore default disposition — after calling it, a subsequent signal reverts to Go's default (terminate the process), which is the standard double-Ctrl-C "I really mean it" escape hatch.

Types

type ActorFunc

type ActorFunc = func() error

ActorFunc is the long-running body of an App.Actor. It blocks until its work is done or it is interrupted, then returns. Unlike App.Go's ctx-aware function, an actor is NOT required to honour a context — it is the canonical shape for blocking primitives that cannot watch a context (e.g. net.Listener.Accept, a database/sql driver loop), which are stopped by their paired InterruptFunc instead.

type App

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

App is the one composed owner of a service's lifecycle: a signal-aware run context, a goroutine group (both ctx-aware and oklog/run-actor shapes), a supervision layer with backoff, the three-plane health Registry, and an ordered Shutdown stack — all driven by a single App.Run that encodes the Kubernetes shutdown choreography (BOREALIS §2.5).

Before App, lifecycle-go's four leaf primitives (SignalContext, Shutdown, Registry, RunLoop) were correct but disconnected islands; App is the owner that runs the loops, flips readiness, drains, and tears down in order. It is the single fleet home of the health planes (server-go only mounts them).

Construct with New or FromConfig; register work with App.Go, App.Actor, App.Supervise; register teardown with App.OnShutdown; register dependencies with App.Probe. Then call App.Run exactly once.

The happy path is zero-config: New(Config{}) gives sane defaults (SIGINT/SIGTERM, 5s drain, 30s shutdown grace).

func FromConfig

func FromConfig(cfg Config, opts ...Option) (*App, error)

FromConfig constructs an App from an already-loaded Config sub-struct, plus functional [Option]s. It is the canonical config-consuming constructor (BOREALIS §3.5 `pkg.FromConfig(cfg pkg.Config) (*T, error)`) and MUST NOT itself call shikumi.Load — the loader runs once at main, and the lifecycle-go/cfg leaf is the shikumi adapter that produces the Config this takes. FromConfig and New share one body so there is one construction path.

func New

func New(cfg Config, opts ...Option) (*App, error)

New constructs an App from a Config 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.

func (*App) Actor

func (a *App) Actor(name string, execute ActorFunc, interrupt InterruptFunc) *App

Actor runs an execute/interrupt pair (the oklog/run shape) in the app's group. Use it for blocking work that cannot watch a context — execute blocks, interrupt stops it. The first actor (or App.Go unit) to return tears down the rest via their interrupts. Returns the App for chaining.

func (*App) Go

func (a *App) Go(name string, fn func(ctx context.Context) error) *App

Go runs fn as a ctx-aware unit in the app's structured-concurrency group (x/sync/errgroup): the first unit to return a non-nil error cancels the run context for every sibling, and that error propagates out of App.Run. fn MUST honour its context to participate in cancellation. Returns the App for chaining. Registering after Run has started is ignored.

func (*App) Health

func (a *App) Health() *Registry

Health returns the app's three-plane health Registry — the single fleet owner of the liveness/readiness/startup planes. Mount its handler yourself, or let App.Run mount it when Config.Health.Addr is set.

func (*App) OnDrain

func (a *App) OnDrain(name string, d Drainable) *App

OnDrain registers a named Drainable run CONCURRENTLY during the shutdown drain window (after readiness is flipped down, before the LIFO Shutdown teardown). It is the remote-session analog of App.OnShutdown: use OnShutdown to close local resources (DB pool, file handles, the listener), use OnDrain to release sessions held on a remote peer (SRA SSH/web sessions, tunnels, subscriptions). Returns the App for chaining. Registering after App.Run has started is ignored.

All registered drainers run in parallel under the single Config.DrainInterval budget — remote drains are independent (different peers) and waiting for them serially would multiply the budget. The drain window is sized below the pod's terminationGracePeriodSeconds by the operator, exactly like ShutdownGrace.

func (*App) OnShutdown

func (a *App) OnShutdown(name string, fn HookFunc) *App

OnShutdown registers a named teardown hook run in LIFO order during the shutdown choreography (the last registered is the first torn down), under the Config.ShutdownGrace budget. Returns the App for chaining.

func (*App) Probe

func (a *App) Probe(name string, p Probe, opts ...ProbeOption) *App

Probe registers a readiness dependency under name, with optional ProbeOption decorators (WithCache, WithPeriodic). It is the canonical health registration verb (BOREALIS §3.5 `app.Probe(...)`) and a thin pass-through to the app's Registry. For liveness/startup planes use the registry directly via App.Health.

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run executes the full lifecycle and blocks until the app stops, returning the first fatal error (or nil on a clean signalled shutdown). It MUST be called at most once. The choreography, in order (BOREALIS §2.5):

  1. Derive a signal-aware run context (SignalContext over Config.Signals).
  2. Mount the health planes (and the deferred /metrics seam) if an address is configured; start any WithPeriodic probe loops.
  3. Run the work group: App.Go units under an errgroup, App.Actor pairs and supervised services as actors in the same group. First fatal error or a delivered signal begins teardown.
  4. K8s shutdown choreography: flip readiness DOWN first (stop new traffic) → sleep DrainInterval (let load balancers observe the failed readiness and in-flight requests drain) → cancel the group → wait for every unit to return → run the LIFO Shutdown stack under the ShutdownGrace budget.

The whole shutdown stays inside ShutdownGrace, which must be set below the pod's terminationGracePeriodSeconds so Kubernetes does not SIGKILL mid-drain.

func (*App) Status

func (a *App) Status() Status

Status captures a typed point-in-time view of the app for rendering. It is the data behind the uniform render verb `borealis.Render(theme, app.Status())` (BOREALIS §3.5) — App deliberately exposes NO bespoke StatusString; the borealis render adapter lives in the leaf sub-package lifecycle-go/render so the core never imports borealis (Law 8).

func (*App) Supervise

func (a *App) Supervise(name string, fn ServiceFunc, backoff Backoff) *App

Supervise runs fn under restart supervision with the given Backoff (a zero Backoff uses DefaultBackoff): fn is restarted with decay+threshold+jittered backoff whenever it returns, until it returns ErrDoNotRestart (stop, no error) or ErrTerminate (stop, propagate). The supervisor stops cleanly when the run context is cancelled. Returns the App for chaining.

type Backoff

type Backoff struct {
	// Base is the initial delay after the first failure (default 1s).
	Base time.Duration
	// Max is the ceiling the exponentially-growing delay is clamped to
	// (default 60s). Zero means no ceiling.
	Max time.Duration
	// Threshold is how long a service must stay up for its run to count as
	// "good", resetting the consecutive-failure count to zero (default 30s).
	Threshold time.Duration
	// Jitter, when true (the default via [DefaultBackoff]), randomises each delay
	// in [0, computed) — full jitter, the AWS-standard storm-control.
	Jitter bool
}

Backoff configures the restart policy of App.Supervise, modelled on thejerf/suture's decay+threshold+jittered backoff (re-expressed in-package per BOREALIS Law 6, well under 300 LOC). The defaults are suture's: a restart that keeps the service up past Threshold resets the failure count, so a service that runs healthily for a while and then dies once is restarted immediately, while a tight crash-loop backs off exponentially up to Max with full jitter.

func DefaultBackoff

func DefaultBackoff() Backoff

DefaultBackoff is the suture-derived default restart policy: 1s base, 60s ceiling, 30s good-run threshold, full jitter.

type Config

type Config struct {
	// Signals are the OS signals that trigger graceful shutdown. Empty means
	// [DefaultSignals] (SIGINT, SIGTERM). Parsed from names via SignalNames when
	// loaded from yaml (see the lifecycle-go/cfg leaf).
	Signals []os.Signal `yaml:"-" json:"-"`

	// SignalNames is the yaml-facing spelling of Signals ("SIGINT","SIGTERM").
	// The cfg leaf converts these to Signals after load. Kept separate so the
	// core stays free of yaml-name parsing.
	SignalNames []string `yaml:"signals" json:"signals,omitempty"`

	// DrainInterval is how long Run sleeps after flipping readiness DOWN, before
	// tearing down work — the window for load balancers to observe the failed
	// readiness probe and stop routing. Default 5s. This is the single most
	// effective cure for rolling-deploy 502s.
	DrainInterval time.Duration `yaml:"drain_interval" json:"drain_interval"`

	// ShutdownGrace is the total budget for the LIFO teardown stack. It MUST be
	// set below the pod's terminationGracePeriodSeconds so Kubernetes does not
	// SIGKILL mid-teardown. Default 30s.
	ShutdownGrace time.Duration `yaml:"shutdown_grace" json:"shutdown_grace"`

	// Health configures the health-plane HTTP surface.
	Health HealthConfig `yaml:"health" json:"health"`

	// Supervisor is the default restart policy applied to [App.Supervise] units
	// that pass a zero [Backoff]. Per-unit backoff overrides it.
	Supervisor Backoff `yaml:"supervisor" json:"supervisor"`
}

Config is the typed, yaml-tagged runtime policy of an App — 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: App fills every field with a sane default.

type DrainFunc

type DrainFunc func(ctx context.Context) error

DrainFunc adapts a plain function into a Drainable — the common authoring shape, so a caller need not declare a bespoke type for a one-off drainer:

app.OnDrain("sra-sessions", lifecycle.DrainFunc(func(ctx context.Context) error {
    return sra.DrainSessions(ctx)
}))

func (DrainFunc) Drain

func (f DrainFunc) Drain(ctx context.Context) error

Drain calls the wrapped function.

type Drainable

type Drainable interface {
	// Drain stops accepting new remote sessions and waits for active ones to
	// finish (or evicts them), within ctx's deadline. It returns the error from
	// abandoning any session it could not release in time.
	Drain(ctx context.Context) error
}

Drainable is a resource that holds REMOTE sessions which must be released gracefully during the shutdown drain window — distinct from a local HookFunc teardown (App.OnShutdown).

The distinction is load-bearing (BOREALIS §2.5 shutdown choreography). The existing drain step only *sleeps* for Config.DrainInterval so external load balancers observe the failed readiness probe and stop routing new traffic; it does nothing about sessions a process is ALREADY holding on a remote endpoint. For a gateway/proxy (SRA SSH + web, a SOCKS tunnel, a long-poll subscription, an event-forwarding channel) those remote sessions live on a peer, not in this process, so a local LIFO close stack cannot reach them — the peer must be told "stop accepting new sessions, let the live ones finish or be evicted." Draining a remote session set is therefore its own verb that runs DURING the drain window, alongside the readiness-down sleep, not in the LIFO teardown after it.

Implement Drainable on the type that owns the remote session set:

type sraGateway struct{ /* … */ }
func (g *sraGateway) Drain(ctx context.Context) error {
    g.stopAcceptingSessions()          // refuse new remote sessions
    return g.waitForActiveSessions(ctx) // let live ones finish within ctx
}

Drain MUST honour ctx: the whole drain runs inside Config.DrainInterval (see App.Run), so a Drainable that ignores its deadline is forcibly abandoned when the window closes (and reported as an error), never blocking past the budget. Drain SHOULD be idempotent — a second call after the window finds no sessions and returns nil.

type HealthConfig

type HealthConfig struct {
	// Addr is the listen address for the health server (e.g. ":8081"). Empty
	// means do not serve health over HTTP (the caller mounts Registry.Handler
	// elsewhere, e.g. on server-go's mux).
	Addr string `yaml:"addr" json:"addr,omitempty"`
	// CacheTTL is the default cache window applied to probes registered without
	// an explicit [WithCache] (zero disables default caching). Advisory: probes
	// opt in per-registration; this records the fleet default for the cfg leaf.
	CacheTTL time.Duration `yaml:"cache_ttl" json:"cache_ttl,omitempty"`
	// PeriodInterval is the default background interval for probes registered
	// without an explicit [WithPeriodic] (zero disables). Advisory, as CacheTTL.
	PeriodInterval time.Duration `yaml:"period_interval" json:"period_interval,omitempty"`
}

HealthConfig configures where and how the three health planes are served.

type HookFunc

type HookFunc = func(context.Context) error

HookFunc is one unit of teardown: it releases a resource and returns any error. It receives the per-shutdown context so a slow hook can observe the overall deadline (see Shutdown.Run) and abort early.

type InterruptFunc

type InterruptFunc = func(error)

InterruptFunc stops the ActorFunc it is paired with, given the error that triggered the group's teardown (the first actor's return, or the run context's cancellation cause). It must cause the paired ActorFunc to return promptly — typically by closing a listener, cancelling an internal context, or signalling a channel. It may be called from a different goroutine than the actor and must be safe to call once.

type LoopOption

type LoopOption func(*loopConfig)

LoopOption configures RunLoop using the functional-options pattern, so the common case (RunLoop(ctx, every, tick)) stays terse while rarer knobs — backoff, immediate first tick, stop-on-error — opt in without a config struct.

func WithBackoff

func WithBackoff(max time.Duration) LoopOption

WithBackoff enables exponential backoff on consecutive tick errors: the delay before the next tick doubles from the base interval up to max (clamped), and resets to the base interval on the first success. A max of zero or less means "no ceiling". Has no effect when combined with WithStopOnError (the loop exits on the first error before any backoff can apply).

func WithImmediateTick

func WithImmediateTick() LoopOption

WithImmediateTick runs the first tick immediately on entry rather than waiting a full interval. Useful when the loop should establish state at startup (warm a cache, take a first reading) before settling into its cadence.

func WithLoopLogger

func WithLoopLogger(log *slog.Logger) LoopOption

WithLoopLogger logs each tick error and backoff decision to log. A nil logger (the default) disables logging.

func WithStopOnError

func WithStopOnError() LoopOption

WithStopOnError makes a tick error terminate the loop, surfacing it as RunLoop's return value. By default tick errors are non-fatal (logged, and retried on the next interval).

type Option

type Option func(*App)

Option configures an App at construction, the functional-options half of the canonical `New(cfg, opts…)` shape (BOREALIS §3.5).

func WithLogger

func WithLogger(log *slog.Logger) Option

WithLogger sets the slog logger used for lifecycle events (shutdown hooks, supervision restarts, choreography steps). The default is a no-op logger.

func WithMetricsHandler

func WithMetricsHandler(h http.Handler) Option

WithMetricsHandler registers the /metrics handler to mount on the health mux.

DEFERRED: metrics-go is in-flight. This is the registration hook so that a future `metricsgo` adapter can call `app.WithMetricsHandler(reg.Handler())` without lifecycle-go importing metrics-go. Until then it is an inert seam — passing nil (the default) mounts nothing. See mountMetrics's TODO.

func WithRegistry

func WithRegistry(r *Registry) Option

WithRegistry supplies a pre-populated health Registry instead of the empty one App creates. Use it when probes are registered before the App exists.

type Probe

type Probe interface {
	Check(ctx context.Context) error
}

Probe is one health check: Check returns nil when the dependency is healthy and an error describing the failure otherwise. The context carries the request deadline so a probe can bound its own I/O.

A probe should be cheap and side-effect-free — it is hit on every Kubernetes liveness/readiness poll. Anything expensive belongs behind a cache.

type ProbeFunc

type ProbeFunc func(ctx context.Context) error

ProbeFunc adapts an ordinary func into a Probe, the http.HandlerFunc pattern. It makes a bare ping method — db.PingContext, conn.Ping — usable directly as a probe.

func (ProbeFunc) Check

func (f ProbeFunc) Check(ctx context.Context) error

Check calls the wrapped function, satisfying Probe.

type ProbeOption

type ProbeOption func(Probe) Probe

ProbeOption configures how a probe is evaluated when registered, using the functional-options pattern so the bare case (register a raw Probe) stays terse while caching and periodic evaluation opt in without a config struct.

Options wrap the underlying probe in a decorator (composition over framework, Law 2): WithCache yields a probe that memoises its last result for a TTL, WithPeriodic yields one that is driven by a background loop. They compose — `WithPeriodic` over `WithCache` is a cached, periodically-refreshed probe.

func WithCache

func WithCache(ttl time.Duration) ProbeOption

WithCache memoises a probe's result for ttl, so a burst of liveness/readiness polls (Kubernetes hits each plane every few seconds) collapses to at most one real evaluation per ttl window. A ttl of zero or less disables caching.

This is the alexliesenfeld/health "cached check" pattern: it bounds the cost of an expensive dependency check under aggressive probing.

func WithPeriodic

func WithPeriodic(interval time.Duration) ProbeOption

WithPeriodic drives the probe from a background goroutine every interval rather than on the hot path of a health poll, so the HTTP handler reads the last result without blocking on the dependency. The background loop is owned by the App the probe is registered on and stops when the app's run context is cancelled. An interval of zero or less disables periodic evaluation (the probe runs synchronously on poll).

This is the heptiolabs/healthcheck "async check" pattern. Until the first background tick completes, the probe reports its cold-start state (Unknown).

type ProbeState

type ProbeState struct {
	// Name is the registered probe name.
	Name string `json:"name"`
	// Plane is the health plane the probe participates in ("liveness",
	// "readiness", or "startup").
	Plane string `json:"plane"`
	// State is the tri-state outcome of the last evaluation.
	State State `json:"state"`
	// Err is the last failure, or nil when up/unknown.
	Err error `json:"-"`
	// Message is Err.Error() (or empty), carried for JSON/render where the error
	// value itself cannot travel.
	Message string `json:"message,omitempty"`
	// Since is the time of the last evaluation (zero when never evaluated).
	Since time.Time `json:"since,omitempty"`
}

ProbeState is the observed status of a single registered probe: its tri-state State, the error from its last failing evaluation (nil when up or unknown), and the wall-clock time of that evaluation (zero when never evaluated). It is the per-check element of Status.

type Registry

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

Registry aggregates named [Probe]s across the liveness and readiness planes and exposes them as a stdlib net/http handler. It mirrors the Rust crate's health surface: liveness answers "should I be restarted?", readiness answers "should I receive traffic?".

The zero value is not usable; construct with NewRegistry. A Registry is safe for concurrent registration and checking.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty health registry.

func (*Registry) Handler

func (r *Registry) Handler() http.Handler

Handler returns an http.Handler serving the conventional health endpoints, with both the legacy and the Kubernetes-idiomatic spellings of each plane:

The body is a small JSON document ({"status":"ok"|"fail","checks":{name:"ok"|err}}), suitable for both Kubernetes probes (which key off the status code) and humans (who read the body). Any other path returns 404.

func (*Registry) Liveness

func (r *Registry) Liveness(ctx context.Context) Report

Liveness evaluates every liveness probe and returns the aggregate report. A report with no probes is OK (an absent liveness probe means "assume live").

func (*Registry) Names

func (r *Registry) Names() []string

Names lists the registered probe names across both planes, sorted, for diagnostics. Duplicate names (the same dependency in both planes) appear once.

func (*Registry) OnTransition

func (r *Registry) OnTransition(l StatusListener)

OnTransition registers a StatusListener invoked whenever a probe's tri-state changes between consecutive evaluations of the same plane. It is additive and safe to call before or after probes are registered.

func (*Registry) Readiness

func (r *Registry) Readiness(ctx context.Context) Report

Readiness evaluates every readiness probe and returns the aggregate report. A report with no probes is OK (an absent readiness probe means "assume ready").

func (*Registry) Register

func (r *Registry) Register(name string, p Probe, opts ...ProbeOption)

Register adds a readiness probe under name. It is shorthand for Registry.RegisterReadiness; readiness is the common case (a dependency the service needs to serve traffic).

func (*Registry) RegisterLiveness

func (r *Registry) RegisterLiveness(name string, p Probe, opts ...ProbeOption)

RegisterLiveness adds a liveness probe under name. Liveness failures indicate the process itself is unhealthy and should be restarted, so liveness probes should not depend on external services (a flaky DB must not trigger restarts). Optional [ProbeOption]s (WithCache, WithPeriodic) decorate the probe.

func (*Registry) RegisterReadiness

func (r *Registry) RegisterReadiness(name string, p Probe, opts ...ProbeOption)

RegisterReadiness adds a readiness probe under name. Readiness failures indicate the process cannot currently serve traffic and should be pulled from rotation, but not restarted. Optional [ProbeOption]s decorate the probe.

func (*Registry) RegisterStartup

func (r *Registry) RegisterStartup(name string, p Probe, opts ...ProbeOption)

RegisterStartup adds a startup probe under name. Startup failures indicate the process has not finished booting; Kubernetes gates the liveness/readiness polls behind a passing startup probe so a slow boot does not trip a restart. Optional [ProbeOption]s decorate the probe.

func (*Registry) Snapshot

func (r *Registry) Snapshot(ctx context.Context) []ProbeState

Snapshot evaluates all three planes and returns the per-probe tri-state view, in registration order across liveness then readiness then startup. It is the data behind App.Status; unlike the boolean Report, it preserves the up/down/unknown distinction and the evaluation timestamp.

func (*Registry) Startup

func (r *Registry) Startup(ctx context.Context) Report

Startup evaluates every startup probe and returns the aggregate report. A report with no probes is OK (an absent startup probe means "assume booted").

type Report

type Report struct {
	// OK is true when every probe in the plane passed.
	OK bool
	// Results holds the per-probe outcomes in registration order.
	Results []Result
}

Report is the aggregate outcome of evaluating one health plane. OK is true only when every probe passed; Results holds each probe's individual outcome, in registration order.

func (Report) Err

func (r Report) Err() error

Err aggregates the failing probes' errors with errors.Join, or returns nil when the report is OK.

type Result

type Result struct {
	// Name is the registered probe name.
	Name string
	// Err is the probe's failure, or nil if it passed.
	Err error
}

Result is the per-probe outcome of a health evaluation. Err is nil when the probe passed.

type ServiceFunc

type ServiceFunc = func(ctx context.Context) error

ServiceFunc is a restartable unit run under App.Supervise. It runs until it returns (cleanly or with an error) or until ctx is cancelled. A clean or errored return is restarted with backoff; returning ErrDoNotRestart or ErrTerminate stops supervision (see App.Supervise). Honour ctx to stop promptly on shutdown.

type Shutdown

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

Shutdown collects named teardown hooks and runs them, on request, in last-in-first-out order under a single deadline — the imperative analog of a defer stack, but observable and bounded. It mirrors the Rust crate's graceful shutdown: resources are released in the reverse of the order they were acquired (the HTTP server stops accepting before the DB pool closes, the DB pool closes before the metrics flusher, and so on).

The zero value is ready to use. A Shutdown is safe for concurrent registration from multiple goroutines, but Shutdown.Run is intended to be called exactly once from the supervising goroutine.

func NewShutdown

func NewShutdown(log *slog.Logger) *Shutdown

NewShutdown returns a Shutdown that logs each hook's start, completion, and failure to log. A nil logger disables logging (equivalent to the zero value).

func (*Shutdown) Add

func (s *Shutdown) Add(name string, fn HookFunc) int

Add registers a named teardown hook. Hooks run in LIFO order, so the last resource registered (typically the last acquired) is the first released. Registering after Shutdown.Run has started is a no-op that returns the hook count unchanged. Returns the number of hooks now registered.

func (*Shutdown) Len

func (s *Shutdown) Len() int

Len reports how many hooks are currently registered.

func (*Shutdown) Run

func (s *Shutdown) Run(ctx context.Context, timeout time.Duration) error

Run executes every registered hook in LIFO order under a single deadline of timeout, derived from ctx. Each hook receives the deadline-bearing context so a cooperative hook can abort early; a hook that ignores its context is still awaited, but once the deadline passes the remaining hooks are skipped and reported as errors.

Errors are aggregated with errors.Join rather than short-circuiting: a failing DB close does not prevent the metrics flusher from running. The joined error is nil only when every hook succeeded within the deadline. A timeout of zero or less means "no deadline" (hooks run to completion).

Run is idempotent in the sense that a second call finds no hooks (they are cleared on first run) and returns nil.

type State

type State int

State is the tri-state health of one probe at a point in time. It mirrors the distributed-systems consensus (alexliesenfeld/health, heptiolabs/healthcheck): a probe is not merely pass/fail — until it has been evaluated at least once it is genuinely Unknown, which is materially different from Down for routing and alerting decisions.

const (
	// StateUnknown means the probe has not yet produced a result (no cached
	// evaluation, periodic loop not yet ticked). Treated as not-ready but not a
	// hard failure — it is the cold-start state.
	StateUnknown State = iota
	// StateUp means the last evaluation passed.
	StateUp
	// StateDown means the last evaluation failed.
	StateDown
)

func (State) String

func (s State) String() string

String renders the state as a lowercase token ("up"/"down"/"unknown"), stable for JSON bodies, logs, and golden tests.

type Status

type Status struct {
	// Running is true once Run has begun the work phase.
	Running bool `json:"running"`
	// Started is when Run entered its work phase (zero before Run).
	Started time.Time `json:"started,omitempty"`
	// Uptime is the time since Started (zero before Run).
	Uptime time.Duration `json:"uptime,omitempty"`
	// Probes is the tri-state per-probe snapshot across all three planes.
	Probes []ProbeState `json:"probes,omitempty"`
}

Status is the typed lifecycle view returned by App.Status. Rendered the uniform way via borealis (see App.Status).

type StatusListener

type StatusListener func(ps ProbeState, prev State)

StatusListener is notified when a probe's tri-state State changes between evaluations (e.g. a dependency goes Up→Down). It is the hook for alerting, metric flips, or logging on health transitions. Listeners are invoked synchronously from the evaluating goroutine and must not block.

type TickFunc

type TickFunc = func(ctx context.Context) error

TickFunc is the unit of work a RunLoop performs on each interval. Returning an error does not stop the loop by default; it is logged and (when backoff is configured) widens the next interval. Honour the context to abort a long tick when the loop is cancelled.

Jump to

Keyboard shortcuts

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