lifecycle

package
v0.142.2 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 9 Imported by: 1

Documentation

Overview

Package lifecycle provides framework-neutral startup and shutdown orchestration for hosted Go applications.

The package intentionally depends only on the Go standard library. It can be incubated inside go-admin and later copied to a standalone repository without carrying go-admin or third-party dependencies.

Hosts own listener binding. A typical integration runs pre-bind tasks, binds the HTTP listener, proves the listener is accepting requests, marks the runner serving, and then runs post-bind, ready, and background work.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterModule

func RegisterModule(registry *Registry, module StartStopModule) error

RegisterModule adapts a module into lifecycle tasks. Lifecycle-aware modules own their task registration and are not also adapted through Start/Stop.

Types

type ErrorPolicy

type ErrorPolicy string

ErrorPolicy controls how task failures affect phase execution.

const (
	// ErrorPolicyFatal stops ordinary phases and returns an error. Shutdown is
	// best-effort: remaining shutdown tasks still run and the failure is joined.
	ErrorPolicyFatal ErrorPolicy = "fatal"
	// ErrorPolicyDegraded records the failure and allows execution to continue.
	ErrorPolicyDegraded ErrorPolicy = "degraded"
	// ErrorPolicyRetryable retries the task before recording a degraded failure.
	ErrorPolicyRetryable ErrorPolicy = "retryable"
	// ErrorPolicyIgnored records the failure as ignored and continues.
	ErrorPolicyIgnored ErrorPolicy = "ignored"
)

type PanicError added in v0.115.0

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

PanicError reports a panic recovered while executing a lifecycle task. Error returns a bounded diagnostic suitable for snapshots. Recovered and StackTrace retain the original value and stack for internal diagnostics.

func (*PanicError) Error added in v0.115.0

func (e *PanicError) Error() string

Error implements error without exposing the recovered stack in serialized lifecycle snapshots.

func (*PanicError) Recovered added in v0.115.0

func (e *PanicError) Recovered() any

Recovered returns the original panic value.

func (*PanicError) StackTrace added in v0.115.0

func (e *PanicError) StackTrace() []byte

StackTrace returns a defensive copy of the recovered panic stack.

func (*PanicError) TaskName added in v0.115.0

func (e *PanicError) TaskName() string

TaskName returns the task that panicked.

func (*PanicError) Unwrap added in v0.115.0

func (e *PanicError) Unwrap() error

Unwrap preserves an error used as the panic value for errors.Is/errors.As.

type Phase

type Phase string

Phase identifies a lifecycle execution phase.

const (
	// PhasePreBind runs required startup work before listeners are opened.
	PhasePreBind Phase = "pre_bind"
	// PhaseBind is a host-owned boundary for listener startup.
	PhaseBind Phase = "bind"
	// PhasePostBind runs after the host has proven listeners accept traffic.
	PhasePostBind Phase = "post_bind"
	// PhaseReady runs readiness checks and hooks.
	PhaseReady Phase = "ready"
	// PhaseBackground supervises long-running workers until shutdown.
	PhaseBackground Phase = "background"
	// PhaseShutdown runs teardown hooks after background workers are stopped.
	PhaseShutdown Phase = "shutdown"
)

type Registerer

type Registerer interface {
	RegisterLifecycle(*Registry)
}

Registerer is implemented by lifecycle-aware modules.

type Registry

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

Registry collects lifecycle tasks before a Runner is built.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty lifecycle registry.

func (*Registry) MustRegister

func (r *Registry) MustRegister(task Task)

MustRegister adds a task and panics on error.

func (*Registry) Register

func (r *Registry) Register(task Task) error

Register adds a task to the registry.

func (*Registry) Tasks

func (r *Registry) Tasks() []Task

Tasks returns registered tasks in deterministic phase/priority order.

type Runner

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

Runner executes registered lifecycle tasks and captures status.

func MustNewRunner

func MustNewRunner(registry *Registry) *Runner

MustNewRunner builds a runner and panics on error.

func NewRunner

func NewRunner(registry *Registry) (*Runner, error)

NewRunner builds a runner from the current registry contents.

func (*Runner) BackgroundFailures added in v0.115.1

func (r *Runner) BackgroundFailures() <-chan *TaskFailure

BackgroundFailures publishes one terminal failure for each failed background task. The channel closes after all background tasks exit.

func (*Runner) Failures added in v0.115.1

func (r *Runner) Failures() []*TaskFailure

Failures returns a defensive copy of bounded raw failed-attempt history. Unlike Snapshot, entries retain typed errors and recovered panic stacks.

func (*Runner) MarkReady

func (r *Runner) MarkReady()

MarkReady records that the host has completed readiness work.

func (*Runner) MarkServing

func (r *Runner) MarkServing()

MarkServing records that the host has proven listener availability.

func (*Runner) RunPhase

func (r *Runner) RunPhase(ctx context.Context, phase Phase) error

RunPhase executes all tasks for a phase in deterministic order.

func (*Runner) RunPostBind

func (r *Runner) RunPostBind(ctx context.Context) error

RunPostBind runs all post-bind tasks.

func (*Runner) RunPreBind

func (r *Runner) RunPreBind(ctx context.Context) error

RunPreBind runs all pre-bind tasks.

func (*Runner) RunReady

func (r *Runner) RunReady(ctx context.Context) error

RunReady runs all ready tasks and marks the runner ready on success.

func (*Runner) Shutdown

func (r *Runner) Shutdown(ctx context.Context) error

Shutdown cancels background tasks, waits for them to finish, and runs every shutdown task. Fatal, degraded, and exhausted retryable shutdown failures are returned together; ignored failures remain available through diagnostics.

func (*Runner) Snapshot

func (r *Runner) Snapshot() Snapshot

Snapshot returns a serializable point-in-time runner state.

func (*Runner) StartBackground

func (r *Runner) StartBackground(ctx context.Context) error

StartBackground starts all background tasks and returns immediately.

type ShutdownIncompleteError added in v0.115.2

type ShutdownIncompleteError struct {
	Cause error
	Stage ShutdownStage
}

ShutdownIncompleteError reports that the caller's context expired before a shutdown stage completed. Callers must not close shared resources until a later Shutdown call completes without this error.

func (*ShutdownIncompleteError) Error added in v0.115.2

func (e *ShutdownIncompleteError) Error() string

Error implements error.

func (*ShutdownIncompleteError) Unwrap added in v0.115.2

func (e *ShutdownIncompleteError) Unwrap() error

Unwrap exposes the context error that interrupted shutdown.

type ShutdownStage added in v0.115.3

type ShutdownStage string

ShutdownStage identifies the unfinished part of a retryable shutdown.

const (
	// ShutdownStageBackground means background tasks have not all exited.
	ShutdownStageBackground ShutdownStage = "background"
	// ShutdownStageTasks means shutdown tasks have not all completed.
	ShutdownStageTasks ShutdownStage = "shutdown_tasks"
)

type Snapshot

type Snapshot struct {
	Serving   bool           `json:"serving"`
	Ready     bool           `json:"ready"`
	StartedAt time.Time      `json:"started_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	Tasks     []TaskSnapshot `json:"tasks"`
}

Snapshot is a point-in-time view of runner status.

type StartStopModule

type StartStopModule interface {
	Name() string
	Priority() int
	Start(context.Context) error
	Stop(context.Context) error
}

StartStopModule is the compatibility shape used by many host apps.

type State

type State string

State identifies the current state of a task or runner.

const (
	StatePending   State = "pending"
	StateRunning   State = "running"
	StateSucceeded State = "succeeded"
	StateFailed    State = "failed"
	StateDegraded  State = "degraded"
	StateIgnored   State = "ignored"
	StateCancelled State = "cancelled"
)

type Task

type Task struct {
	Name        string
	Phase       Phase
	Priority    int
	Policy      ErrorPolicy
	Run         TaskFunc
	Timeout     time.Duration
	MaxAttempts int
}

Task describes a registered lifecycle task.

type TaskFailure added in v0.115.1

type TaskFailure struct {
	TaskName   string      `json:"task_name"`
	Phase      Phase       `json:"phase"`
	Policy     ErrorPolicy `json:"policy"`
	State      State       `json:"state"`
	Attempt    int         `json:"attempt"`
	Terminal   bool        `json:"terminal"`
	OccurredAt time.Time   `json:"occurred_at"`
	Cause      error       `json:"-"`
}

TaskFailure preserves a raw failed lifecycle attempt outside the JSON-safe snapshot. Cause may carry a PanicError and its stack trace.

func (*TaskFailure) Error added in v0.115.1

func (f *TaskFailure) Error() string

Error implements error while retaining the underlying cause for errors.Is and errors.As.

func (*TaskFailure) Unwrap added in v0.115.1

func (f *TaskFailure) Unwrap() error

Unwrap returns the raw task failure.

type TaskFunc

type TaskFunc func(context.Context) error

TaskFunc is a unit of lifecycle work.

type TaskSnapshot

type TaskSnapshot struct {
	Name        string        `json:"name"`
	Phase       Phase         `json:"phase"`
	Priority    int           `json:"priority"`
	Policy      ErrorPolicy   `json:"policy"`
	State       State         `json:"state"`
	Attempts    int           `json:"attempts"`
	StartedAt   time.Time     `json:"started_at"`
	CompletedAt time.Time     `json:"completed_at"`
	Duration    time.Duration `json:"duration"`
	Error       string        `json:"error,omitempty"`
}

TaskSnapshot is a point-in-time view of task status.

Jump to

Keyboard shortcuts

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