Documentation
¶
Overview ¶
Package lifecycle provides a robust control plane for modern Go applications. It unifies Death Management (Signals, Shutdown) with Life Management (Supervision, Events).
Core Concepts ¶
The library is built around three pillars:
Signal Context (The Foundation): Manages the application's lifecycle, handling OS signals (SIGINT/SIGTERM) and propagating cancellation via context.Context.
ctx := lifecycle.NewSignalContext(context.Background()) <-ctx.Done()
Supervisor (The Bridge): Manages a tree of Workers (Processes, Containers, Goroutines), ensuring they adhere to the parent's lifecycle. It supports restart strategies (OneForOne, OneForAll), persistent identity (Handover), and state introspection via Workers().
sup := lifecycle.NewSupervisor("root", lifecycle.SupervisorStrategyOneForOne) sup.Add(spec) states := sup.Workers()
Control Plane (The Orchestrator): Decouples "Events" (Triggers) from "Handlers" (Reactions) via a Router. This allows the application to react to external stimuli (Input, Webhooks) dynamically.
router := lifecycle.NewRouter() router.Handle("signal/interrupt", handler)
Root Package Aliases ¶
For convenience, this package exposes the most commonly used types and constructors from the internal `pkg/` structure, grouped by functionality:
- Runtime: lifecycle.Run (supports WithLogger, WithMetrics), lifecycle.Go (returns Task, supports WithErrorHandler), lifecycle.Do
- Signals: lifecycle.NewSignalContext, lifecycle.WithForceExit
- Supervision: lifecycle.NewSupervisor, lifecycle.NewProcessWorker
- Control: lifecycle.NewRouter, lifecycle.Handle
- Interactive: lifecycle.NewInteractiveRouter, lifecycle.WithShutdown
Interactive Applications ¶
For CLI tools, use the Interactive Router preset to wire up signals and input automatically:
router := lifecycle.NewInteractiveRouter( lifecycle.WithSuspendOnInterrupt(suspendHandler), lifecycle.WithShutdown(quitFunc), ) lifecycle.Run(router)
Configuration ¶
Configuration is done via Functional Options (SignalOption) and Struct Specs (SupervisorSpec). We adopt the "Stdlib Pattern": providing a `DefaultRouter` for convenience ("Managed Global State") while allowing explicit `NewRouter` for strict isolation.
Index ¶
- Constants
- Variables
- func BlockWithTimeout(done <-chan struct{}, timeout time.Duration) error
- func Dispatch(ctx context.Context, e Event)
- func Do(ctx context.Context, fn func(ctx context.Context) error) error
- func DoDetached(parent context.Context, fn func(ctx context.Context) error) error
- func GetForceExitThreshold(ctx context.Context) int
- func GetObserver() observe.Observer
- func Handle(pattern string, handler Handler)
- func HandleFunc(pattern string, handler func(context.Context, Event) error)
- func IsInterrupted(err error) bool
- func IsUnsafe(ctx context.Context) bool
- func LifecycleDiagramConfig() *introspection.DiagramConfig
- func NewInteractiveRouter(opts ...InteractiveOption) *events.Router
- func NewInterruptibleReader(base io.Reader, cancel <-chan struct{}) *termio.InterruptibleReader
- func NewLogMetricsProvider() metrics.Provider
- func NewNoOpLogger() *slog.Logger
- func NewProcessCmd(ctx context.Context, name string, args ...string) *proc.Cmd
- func NewWorkerFromFunc(name string, fn func(context.Context) error) worker.Worker
- func OnShutdown(ctx context.Context, fn func())
- func OpenTerminal() (io.ReadCloser, error)
- func Receive[V any](ctx context.Context, ch <-chan V) iter.Seq[V]
- func ResetSignalCount(ctx context.Context)
- func Run(r Runnable, opts ...any) error
- func SetLogger(l *slog.Logger)
- func SetMetricsLabelPolicy(p *metrics.LabelPolicy)
- func SetMetricsProvider(p metrics.Provider)
- func SetObserver(o observe.Observer)
- func SetStrictMode(strict bool)
- func Shutdown(ctx context.Context)
- func ShutdownAndWait(ctx context.Context)
- func Signal(ctx context.Context) os.Signal
- func SignalStateDiagram(s SignalState) string
- func Sleep(ctx context.Context, d time.Duration) error
- func Start(ctx context.Context) error
- func StartProcess(cmd *exec.Cmd) error
- func StopAndWait(ctx context.Context, w Worker) error
- func SystemDiagram(sig SignalState, work WorkerState) string
- func UpgradeTerminal(r io.Reader) (io.Reader, error)
- func Wait(ctx context.Context)
- func WithCancelOnInterrupt(enabled bool) signal.Option
- func WithForceExit(threshold int) signal.Option
- func WithHookTimeout(d time.Duration) signal.Option
- func WithInputCommands(commands ...string) events.InputOption
- func WithInputHandlers(handlers map[string]events.Handler) events.InputOption
- func WithLogger(l *slog.Logger) any
- func WithMetrics(p metrics.Provider) any
- func WithResetTimeout(d time.Duration) signal.Option
- func WithRouterHandlers(handlers map[string]events.Handler) events.RouterOption
- func WithShutdownTimeout(d time.Duration) any
- func WorkerStateDiagram(s WorkerState) string
- func WorkerTreeDiagram(s WorkerState) string
- type BaseWorker
- type ChannelSource
- type ClearLineEvent
- type Container
- type ContainerStatus
- type Escalator
- type Event
- type FileWatchSource
- type GoOption
- type Group
- type Handler
- func NewReloadHandler(onReload func(context.Context) error) Handler
- func NewShutdownFunc(fn func()) Handler
- func NewShutdownHandler(cancel context.CancelFunc) Handler
- func NewTerminateHandler(suspend Handler, shutdown Handler, opts ...TerminateOption) Handler
- func WithFixedEvent(h Handler, ev Event) Handler
- func WithStateCheck(h Handler, checker StateChecker) Handler
- type HandlerFunc
- type HealthCheckSource
- type HealthOption
- type InputEvent
- type InputOption
- type InputSource
- type InteractiveOption
- func WithCommand(name string, handler events.Handler) InteractiveOption
- func WithDefaultHandler(handler events.Handler) InteractiveOption
- func WithDefaultMappings() InteractiveOption
- func WithInput(enable bool) InteractiveOption
- func WithInputBackoff(d time.Duration) InteractiveOption
- func WithInputBufferSize(size int) InteractiveOption
- func WithInputEventBuffer(size int) InteractiveOption
- func WithInputOptions(opts ...events.InputOption) InteractiveOption
- func WithInterruptHandler(handler events.Handler) InteractiveOption
- func WithShutdown(fn func()) InteractiveOption
- func WithSignal(enable bool) InteractiveOption
- func WithSuspendOnInterrupt(h events.Handler) InteractiveOption
- func WithUnknownHandler(handler events.Handler) InteractiveOption
- type InterruptEvent
- type LineEvent
- type NoOpObserver
- type Observer
- type ProcessWorker
- type ResumeEvent
- type Router
- type RouterOption
- type Runnable
- type ShutdownEvent
- type SignalContext
- type SignalOption
- type SignalState
- type Source
- type StateChecker
- type Supervisor
- type SupervisorBackoff
- type SupervisorFactory
- type SupervisorRestartPolicy
- type SupervisorSpec
- type SupervisorStrategy
- type SuspendEvent
- type SuspendHandler
- type SuspendManager
- type Suspendable
- type SuspendableHandler
- type Task
- type TerminateEvent
- type TerminateOption
- type TickEvent
- type UnknownCommandEvent
- type WebhookOption
- type WebhookSource
- type Worker
- type WorkerState
- type WorkerStatus
Examples ¶
Constants ¶
const ( WorkerStatusCreated = worker.StatusCreated WorkerStatusPending = worker.StatusPending WorkerStatusRunning = worker.StatusRunning WorkerStatusStopped = worker.StatusStopped WorkerStatusFailed = worker.StatusFailed )
const ( // WorkerEnvResumeID is the unique session identifier for a worker. WorkerEnvResumeID = worker.EnvResumeID // WorkerEnvPrevExit is the exit code of the previous execution of this worker. WorkerEnvPrevExit = worker.EnvPrevExit )
Handover Constants
const ( // SupervisorStrategyOneForOne: If a child process terminates, only that process is restarted. SupervisorStrategyOneForOne = supervisor.StrategyOneForOne // SupervisorStrategyOneForAll: If a child process terminates, all other child processes are terminated. SupervisorStrategyOneForAll = supervisor.StrategyOneForAll )
const ( RestartAlways = supervisor.RestartAlways RestartOnFailure = supervisor.RestartOnFailure RestartNever = supervisor.RestartNever )
Variables ¶
var DefaultRouter = events.DefaultRouter
DefaultRouter is the default instance for package-level helpers. Alias for pkg/events.Defaultevents.
var ( // ErrNotHandled is a sentinel error that handlers can return to indicate they did not process the event. ErrNotHandled = events.ErrNotHandled )
var Version string
Functions ¶
func BlockWithTimeout ¶ added in v1.1.0
BlockWithTimeout blocks until the done channel is closed or the timeout expires. Alias for pkg/runtime.BlockWithTimeout.
Example ¶
ExampleBlockWithTimeout demonstrates how to enforce a deadline on shutdown cleanup.
package main
import (
"fmt"
"time"
"github.com/aretw0/lifecycle"
)
func main() {
done := make(chan struct{})
// Simulate a cleanup task
go func() {
defer close(done)
// Simulate fast cleanup
time.Sleep(10 * time.Millisecond)
}()
// Wait for cleanup, but give up after 1 second
err := lifecycle.BlockWithTimeout(done, 1*time.Second)
if err != nil {
fmt.Println("Cleanup timed out!")
} else {
fmt.Println("Cleanup finished successfully")
}
}
Output: Cleanup finished successfully
func Dispatch ¶ added in v1.5.0
Dispatch finds the handler for an event on the DefaultRouter and executes it. Alias for pkg/events.Dispatch.
func Do ¶ added in v1.4.0
Do executes a function in a "Safe Executor" (Panic Recovery + Observability). Alias for pkg/runtime.Do.
func DoDetached ¶ added in v1.5.0
DoDetached executes a function in a "Critical Section" (Detached Context). Alias for pkg/runtime.DoDetached.
func GetForceExitThreshold ¶ added in v1.5.0
GetForceExitThreshold returns the number of signals required to trigger os.Exit(1).
func GetObserver ¶ added in v1.5.0
GetObserver returns the current global observer, if any. Alias for pkg/observe.GetObserver.
func Handle ¶ added in v1.5.0
Handle registers a handler on the Defaultevents. Alias for pkg/events.Handle.
func HandleFunc ¶ added in v1.5.0
HandleFunc registers a handler function on the Defaultevents. Alias for pkg/events.HandleFunc.
func IsInterrupted ¶
IsInterrupted checks if an error indicates an interruption (Context Canceled, EOF, etc.). Alias for pkg/termio.IsInterrupted.
func IsUnsafe ¶ added in v1.5.0
IsUnsafe returns true if the context is configured to never force exit.
func LifecycleDiagramConfig ¶ added in v1.5.0
func LifecycleDiagramConfig() *introspection.DiagramConfig
LifecycleDiagramConfig returns an introspection DiagramConfig customized for lifecycle's domain terminology and rendering.
This maps lifecycle concepts (Signal Context, Supervision Tree) to the generic introspection rendering pipeline by delegating to core component stylers and labelers.
func NewInteractiveRouter ¶ added in v1.5.0
func NewInteractiveRouter(opts ...InteractiveOption) *events.Router
NewInteractiveRouter creates a router pre-configured for interactive CLI applications.
It wires up:
- OS Signals (Interrupt/Term) -> Escalator (Interrupt first, then Quit)
- Input (Stdin) -> Router (reads lines as commands)
- Core Routes: "suspend", "resume" (if a SuspendHandler is provided)
The router uses a "Double-Tap" strategy for interrupts (Ctrl+C):
- First Signal: Triggers the configured InterruptHandler (or SuspendHandler). For REPLs, this might clear the line. For services, this triggers suspension.
- Second Signal: Forces the application to Quit.
The quit handler is wrapped in events.Once() to ensure idempotency.
func NewInterruptibleReader ¶
func NewInterruptibleReader(base io.Reader, cancel <-chan struct{}) *termio.InterruptibleReader
NewInterruptibleReader returns a reader that checks the cancel channel before/after blocking reads. Alias for pkg/termio.NewInterruptibleReader.
func NewLogMetricsProvider ¶ added in v1.1.0
NewLogMetricsProvider returns a metrics provider that logs to the current logger. Useful for development and local verification. Alias for pkg/metrics.LogProvider.
func NewNoOpLogger ¶ added in v1.5.0
NewNoOpLogger returns a logger that discards all output. Alias for pkg/log.NewNoOpLogger.
func NewProcessCmd ¶ added in v1.7.2
NewProcessCmd creates a proc.Cmd pre-configured with context-linked cancellation and platform process hygiene (PDeathSig / Job Objects). Use cmd.Start() / cmd.Wait() / cmd.Run() directly. Alias for procio/proc.NewCmd.
func NewWorkerFromFunc ¶ added in v1.3.1
NewWorkerFromFunc creates a Worker from a function. Alias for pkg/worker.FromFunc.
func OnShutdown ¶ added in v1.4.0
OnShutdown safely registers a shutdown hook on the context if it supports it. It abstracts the discovery of signal.Context even when wrapped.
func OpenTerminal ¶
func OpenTerminal() (io.ReadCloser, error)
OpenTerminal checks for text input capability and returns a Reader. On Windows, it tries to open CONIN$. Alias for pkg/termio.Open.
Example ¶
ExampleOpenTerminal demonstrates how to open the terminal safely.
package main
import (
"fmt"
"github.com/aretw0/lifecycle"
)
func main() {
// OpenTerminal handles OS-specific logic (like CONIN$ on Windows)
reader, err := lifecycle.OpenTerminal()
if err != nil {
fmt.Printf("Error opening terminal: %v\n", err)
return
}
defer reader.Close()
fmt.Println("Terminal opened successfully")
// Wrap with InterruptibleReader to respect context cancellation
// r := lifecycle.NewInterruptibleReader(reader, ctx.Done())
}
Output: Terminal opened successfully
func Receive ¶ added in v1.5.0
Receive creates a push iterator that yields values from the channel until the context is cancelled or the channel is closed. Alias for pkg/runtime.Receive.
func ResetSignalCount ¶ added in v1.5.0
ResetSignalCount resets the signal counter and clears the last received signal. This is useful for "Smart Handlers" (like REPLs) that successfully handle a signal and want to prevent the "Force Exit" threshold from being reached on subsequent signals.
func Run ¶ added in v1.4.0
Run executes the application logic with a managed SignalContext. Alias for pkg/runtime.Run.
func SetLogger ¶ added in v1.1.0
SetLogger overrides the global logger used by the library. Alias for pkg/log.SetLogger.
func SetMetricsLabelPolicy ¶ added in v1.5.0
func SetMetricsLabelPolicy(p *metrics.LabelPolicy)
SetMetricsLabelPolicy configures label sanitization for metrics. Alias for pkg/metrics.SetLabelPolicy.
func SetMetricsProvider ¶ added in v1.1.0
SetMetricsProvider overrides the global metrics provider. This allowing bridging library metrics to Prometheus, OTEL, etc. Alias for pkg/metrics.SetProvider.
func SetObserver ¶ added in v1.5.0
SetObserver configures the global observer. Alias for pkg/observe.SetObserver.
func SetStrictMode ¶ added in v1.1.0
func SetStrictMode(strict bool)
SetStrictMode sets whether to block on unsupported platforms for process hygiene. Alias for pkg/proc.StrictMode.
func Shutdown ¶ added in v1.5.0
Shutdown initiates a graceful shutdown of the application asynchronously. It cancels the context and triggers all registered OnShutdown hooks.
When to use:
- Inside an HTTP handler or RPC method where blocking is undesirable.
- When you want to trigger shutdown but don't need to wait for it (fire-and-forget).
- In tests where you want to assert intermediate states during shutdown.
Difference from Stop():
- Shutdown() triggers application teardown (hooks run, context cancels).
- Stop() only stops signal monitoring (hooks do NOT run, context remains valid).
func ShutdownAndWait ¶ added in v1.5.0
ShutdownAndWait initiates a graceful shutdown and blocks until all hooks have completed. It is a shorthand for Shutdown(ctx) followed by Wait(ctx).
When to use:
- In your main() function to ensure strict cleanup before exit.
- When the next line of code assumes all resources are released.
func Signal ¶ added in v1.5.0
Signal returns the signal that caused the context to be cancelled/interrupted, or nil. It safely unwraps the context to find the SignalContext.
func SignalStateDiagram ¶ added in v1.3.0
func SignalStateDiagram(s SignalState) string
SignalStateDiagram returns a Mermaid state diagram string representing the signal context configuration. Alias for pkg/signal.MermaidState.
func Sleep ¶ added in v1.4.0
Sleep pauses the current goroutine for at least the duration d. Alias for pkg/runtime.Sleep.
func Start ¶ added in v1.5.0
Start begins the listening loop for the DefaultRouter. Alias for pkg/events.Start.
func StartProcess ¶ added in v1.1.0
StartProcess starts the specified command with process hygiene (auto-kill on parent exit). Alias for pkg/proc.Start.
func StopAndWait ¶ added in v1.6.5
StopAndWait requests a worker to stop and blocks until it fully terminates. This utility resolves race conditions where Stop() returns but the worker's I/O or background routines are still active. Alias for pkg/worker.StopAndWait.
func SystemDiagram ¶ added in v1.3.0
func SystemDiagram(sig SignalState, work WorkerState) string
SystemDiagram returns a unified Mermaid diagram representing the entire application lifecycle. It combines the SignalContext (Control Plane) and the Worker hierarchy (Data Plane) using the generic introspection.ComponentDiagram API with lifecycle-specific configuration.
func UpgradeTerminal ¶ added in v0.1.1
UpgradeTerminal checks if the provided reader is a terminal and returns a safe reader (e.g. CONIN$ on Windows). If not a terminal, returns the original reader.
func WithCancelOnInterrupt ¶ added in v1.5.0
WithCancelOnInterrupt controls whether SIGINT automatically cancels the context. Alias for pkg/signal.WithCancelOnInterrupt.
func WithForceExit ¶ added in v1.1.0
WithForceExit configures the threshold of signals required to trigger an immediate os.Exit(1). Threshold values: 1 (Default): SIGINT cancels context immediately. n >= 2: SIGINT is captured, os.Exit(1) at n-th signal (Escalation Mode). 0 (Unsafe): Automatic os.Exit(1) is disabled for SIGINT.
func WithHookTimeout ¶ added in v1.2.0
WithHookTimeout configures the duration after which a running hook produces a warning log. Alias for pkg/signal.WithHookTimeout.
func WithInputCommands ¶ added in v1.5.0
func WithInputCommands(commands ...string) events.InputOption
WithInputCommands is a low-level helper to allowlist simple commands for InputSource. Alias for pkg/events.WithInputCommands.
func WithInputHandlers ¶ added in v1.5.0
func WithInputHandlers(handlers map[string]events.Handler) events.InputOption
WithInputHandlers configures an InputSource from a handler map. Alias for pkg/events.WithInputHandlers.
func WithLogger ¶ added in v1.5.0
WithLogger returns a RunOption to configure the global logger. Alias for pkg/runtime.WithLogger.
func WithMetrics ¶ added in v1.5.0
WithMetrics returns a RunOption to configure the global metrics provider. Alias for pkg/runtime.WithMetrics.
func WithResetTimeout ¶ added in v1.5.0
WithResetTimeout configures the duration after which the signal count resets. Alias for pkg/signal.WithResetTimeout.
func WithRouterHandlers ¶ added in v1.5.0
func WithRouterHandlers(handlers map[string]events.Handler) events.RouterOption
WithRouterHandlers configures a Router from a handler map. Alias for pkg/events.WithRouterHandlers.
func WithShutdownTimeout ¶ added in v1.5.0
WithShutdownTimeout returns a RunOption to configure the diagnostic timeout during shutdown. Alias for pkg/runtime.WithShutdownTimeout.
func WorkerStateDiagram ¶ added in v1.3.0
func WorkerStateDiagram(s WorkerState) string
WorkerStateDiagram returns a Mermaid state diagram string representing the worker state transitions. Alias for pkg/worker.MermaidState.
func WorkerTreeDiagram ¶ added in v1.3.0
func WorkerTreeDiagram(s WorkerState) string
WorkerTreeDiagram returns a Mermaid diagram string representing the worker structure (Tree). Alias for pkg/worker.MermaidTree.
Types ¶
type BaseWorker ¶ added in v1.5.0
type BaseWorker = worker.BaseWorker
BaseWorker provides default implementations for Worker interface boilerplate. Embed this in your worker types to avoid repeating Stop/Wait/String methods.
Example:
type MyWorker struct {
*lifecycle.BaseWorker
// custom fields...
}
func (w *MyWorker) State() lifecycle.WorkerState {
return w.ExportState(func(s *lifecycle.WorkerState) {
s.Metadata = map[string]string{"custom": "data"}
})
}
func NewMyWorker() *MyWorker {
return &MyWorker{
BaseWorker: lifecycle.NewBaseWorker("MyWorker"),
}
}
func (w *MyWorker) Start(ctx context.Context) error {
return w.StartFunc(ctx, w.Run)
}
Alias for pkg/worker.BaseWorker.
func NewBaseWorker ¶ added in v1.5.0
func NewBaseWorker(name string) *BaseWorker
NewBaseWorker creates a BaseWorker with the given name. The name is immutable (construct a new worker to change it). Alias for pkg/worker.NewBaseWorker.
type ChannelSource ¶ added in v1.5.0
type ChannelSource = events.ChannelSource
ChannelSource adapts a generic Go channel to the Source interface. Alias for pkg/events.ChannelSource.
func NewChannelSource ¶ added in v1.5.0
func NewChannelSource(ch <-chan Event) *ChannelSource
NewChannelSource creates a new source that reads from the given channel. Alias for pkg/events.NewChannelSource.
type ClearLineEvent ¶ added in v1.5.0
type ClearLineEvent = events.ClearLineEvent
ClearLineEvent is triggered when an interactive input is interrupted. Alias for pkg/events.ClearLineEvent.
type Container ¶ added in v1.3.0
Container represents a generic container interface. Alias for container.Container.
func NewMockContainer ¶ added in v1.3.0
NewMockContainer creates a new MockContainer for testing. Alias for pkg/container.NewMockContainer.
type ContainerStatus ¶ added in v1.3.0
ContainerStatus represents the lifecycle state of a container. Alias for container.Status.
type Escalator ¶ added in v1.5.0
Escalator is a generic "Double-Tap" handler that escalates from Primary to Fallback. Alias for pkg/events.Escalator.
func NewEscalator ¶ added in v1.5.0
NewEscalator creates a new generic Double-Tap handler. Alias for pkg/events.NewEscalator.
type Event ¶ added in v1.5.0
Event is a stimulus that triggers a reaction. Alias for pkg/events.Event.
type FileWatchSource ¶ added in v1.5.0
type FileWatchSource = events.FileWatchSource
FileWatchSource watches for file changes using platform-specific notifications. Alias for pkg/events.FileWatchSource.
func NewFileWatchSource ¶ added in v1.5.0
func NewFileWatchSource(path string) *FileWatchSource
NewFileWatchSource creates a new source that watches the given file for changes. Uses fsnotify for efficient, event-driven file watching (Linux, Windows, macOS, BSD).
Example:
events.AddSource(lifecycle.NewFileWatchSource("config.yaml"))
events.Handle("file/*", lifecycle.NewReloadHandler(reloadConfig))
Alias for pkg/events.NewFileWatchSource.
type GoOption ¶ added in v1.5.0
GoOption configuration for Go. Alias for pkg/runtime.GoOption.
func WithErrorHandler ¶ added in v1.5.0
WithErrorHandler creates an option to handle errors in background goroutines. Alias for pkg/runtime.WithErrorHandler.
func WithStackCapture ¶ added in v1.6.0
WithStackCapture creates an option to control stack capture for background task panics. Alias for pkg/runtime.WithStackCapture.
Stable as of v1.6.0. Behavior:
- WithStackCapture(true): Always capture stack bytes (useful in production for critical tasks)
- WithStackCapture(false): Never capture stack bytes (performance testing)
- Unset (default): Auto-detect based on debug logging (no overhead in production)
See docs/LIMITATIONS.md (Performance section) for stack capture overhead details.
type Group ¶ added in v1.5.0
type Group struct {
// contains filtered or unexported fields
}
Group is a wrapper around errgroup.Group that adds lifecycle safety features: - Panic Recovery: Captures panics in goroutines and returns them as errors. - Observability: Tracks started/finished goroutines via pkg/metrics. - Context Propagation: Inherits context from the parent.
func NewGroup ¶ added in v1.5.0
NewGroup creates a new Group derived from the given context. It acts like errgroup.WithContext.
func (*Group) Go ¶ added in v1.5.0
Go calls the given function in a new goroutine. It blocks until the new goroutine can be added without the number of active goroutines in the group exceeding the configured limit.
If the function triggers a panic, it is recovered, logged, and returned as an error, which will cancel the Group's context.
type Handler ¶ added in v1.5.0
Handler responds to an event. Alias for pkg/events.Handler.
func NewReloadHandler ¶ added in v1.5.0
NewReloadHandler returns a handler that reloads configuration. Alias for pkg/events.NewReload.
func NewShutdownFunc ¶ added in v1.5.0
func NewShutdownFunc(fn func()) Handler
NewShutdownFunc returns a handler that executes the given function once. Useful for wrapping generic close/cleanup operations as shutdown triggers. Alias for pkg/events.NewShutdownFunc.
func NewShutdownHandler ¶ added in v1.5.0
func NewShutdownHandler(cancel context.CancelFunc) Handler
NewShutdownHandler returns a handler that cancels context. It is automatically wrapped in events.Once to ensure idempotency. Alias for pkg/events.NewShutdown.
func NewTerminateHandler ¶ added in v1.5.0
func NewTerminateHandler(suspend Handler, shutdown Handler, opts ...TerminateOption) Handler
NewTerminateHandler creates a new handler that chains suspension and shutdown. Alias for pkg/events.NewTerminate.
func WithFixedEvent ¶ added in v1.5.0
WithFixedEvent wraps a handler and always passes the specified event. Alias for pkg/events.WithFixedEvent.
func WithStateCheck ¶ added in v1.5.0
func WithStateCheck(h Handler, checker StateChecker) Handler
WithStateCheck wraps a handler and only executes it if the StateChecker allows. Alias for pkg/events.WithStateCheck.
type HandlerFunc ¶ added in v1.5.0
type HandlerFunc = events.HandlerFunc
HandlerFunc matches the signature of a Handler. Alias for pkg/events.HandlerFunc.
type HealthCheckSource ¶ added in v1.5.0
type HealthCheckSource = events.HealthCheckSource
HealthCheckSource runs a periodic health check. Alias for pkg/events.HealthCheckSource.
func NewHealthCheckSource ¶ added in v1.5.0
func NewHealthCheckSource(name string, check events.CheckFunc, opts ...HealthOption) *HealthCheckSource
NewHealthCheckSource creates a new health monitor. Alias for pkg/events.NewHealthCheckSource.
type HealthOption ¶ added in v1.5.0
type HealthOption = events.HealthOption
HealthOption configures a HealthCheckSource. Alias for pkg/events.HealthOption.
func WithHealthInterval ¶ added in v1.5.0
func WithHealthInterval(d time.Duration) HealthOption
WithHealthInterval sets the check interval. Alias for pkg/events.WithHealthInterval.
func WithHealthStrategy ¶ added in v1.5.0
func WithHealthStrategy(strategy events.TriggerStrategy) HealthOption
WithHealthStrategy sets the triggering strategy (Edge vs Level). Alias for pkg/events.WithHealthStrategy.
type InputEvent ¶ added in v1.5.0
type InputEvent = events.InputEvent
InputEvent represents a generic text command. Alias for pkg/events.InputEvent.
type InputOption ¶ added in v1.5.0
type InputOption = events.InputOption
InputOption configures the InputSource. Alias for pkg/events.InputOption.
func WithInputMapping ¶ added in v1.5.0
func WithInputMapping(key string, event events.Event) InputOption
WithInputMapping adds a custom command mapping. Alias for pkg/events.WithInputMapping.
func WithInputMappings ¶ added in v1.5.0
func WithInputMappings(mappings map[string]events.Event) InputOption
WithInputMappings adds multiple command mappings at once. Alias for pkg/events.WithInputMappings.
func WithInputReader ¶ added in v1.5.0
func WithInputReader(r io.Reader) InputOption
WithInputReader configures the reader for InputSource. Alias for pkg/events.WithInputReader.
func WithRawInput ¶ added in v1.5.0
func WithRawInput(handler func(line string)) InputOption
WithRawInput configures the InputSource for "Data-Only" mode. Alias for pkg/events.WithRawInput.
type InputSource ¶ added in v1.5.0
type InputSource = events.InputSource
InputSource reads from Stdin and emits events. Alias for pkg/events.InputSource.
func NewInputSource ¶ added in v1.5.0
func NewInputSource(opts ...InputOption) *InputSource
NewInputSource creates a new source that listens for standard CLI commands. Alias for pkg/events.NewInputSource.
type InteractiveOption ¶ added in v1.5.0
type InteractiveOption func(*interactiveConfig)
InteractiveOption configures the interactive events.
func WithCommand ¶ added in v1.5.0
func WithCommand(name string, handler events.Handler) InteractiveOption
WithCommand adds a custom command handler. Example: WithCommand("stats", statsHandler) will route "command/stats" to statsHandler.
func WithDefaultHandler ¶ added in v1.5.0
func WithDefaultHandler(handler events.Handler) InteractiveOption
WithDefaultHandler registers a handler for input that does not match any command. This enables "Passthrough" mode, where raw lines are routed to this handler via the "input/line" topic.
func WithDefaultMappings ¶ added in v1.5.0
func WithDefaultMappings() InteractiveOption
WithDefaultMappings enables the standard lifecycle command mappings (quit, suspend, etc.). By default, the InteractiveRouter starts with NO input mappings.
func WithInput ¶ added in v1.5.0
func WithInput(enable bool) InteractiveOption
WithInput enables or disables the standard input source (stdin). Default is true.
func WithInputBackoff ¶ added in v1.5.0
func WithInputBackoff(d time.Duration) InteractiveOption
WithInputBackoff configures the duration to wait before retrying interruptions or errors. Default: 100ms.
func WithInputBufferSize ¶ added in v1.5.0
func WithInputBufferSize(size int) InteractiveOption
WithInputBufferSize sets the size of the internal read buffer for InteractiveRouter. Default: 1024 bytes.
func WithInputEventBuffer ¶ added in v1.5.0
func WithInputEventBuffer(size int) InteractiveOption
WithInputEventBuffer sets the size of the event channel buffer for InteractiveRouter. Default: 10.
func WithInputOptions ¶ added in v1.5.0
func WithInputOptions(opts ...events.InputOption) InteractiveOption
WithInputOptions passes generic InputOptions to the underlying InputSource. Use this to configure the reader, backoff, or other low-level settings.
func WithInterruptHandler ¶ added in v1.5.0
func WithInterruptHandler(handler events.Handler) InteractiveOption
WithInterruptHandler configures the primary handler for the first interrupt signal (Ctrl+C). Use this for generic handlers that should run on "InterruptEvent" (e.g. clearing a line).
func WithShutdown ¶ added in v1.5.0
func WithShutdown(fn func()) InteractiveOption
WithShutdown registers a function to be called when a "quit" or "shutdown" event occurs. This simplifies wiring up the main loop exit mechanism (e.g. closing a quit channel).
func WithSignal ¶ added in v1.5.0
func WithSignal(enable bool) InteractiveOption
WithSignal enables or disables the OS signal source (Interrupt, Term). Default is true.
func WithSuspendOnInterrupt ¶ added in v1.5.0
func WithSuspendOnInterrupt(h events.Handler) InteractiveOption
WithSuspendOnInterrupt configures the handler to SUSPEND the application on the first interrupt signal. This preserves the "State Check" logic: if the handler is already suspended, the event is ignored. It explicitly sets the target event to SuspendEvent.
func WithUnknownHandler ¶ added in v1.5.0
func WithUnknownHandler(handler events.Handler) InteractiveOption
WithUnknownHandler registers a handler for unknown commands. Use this to customize the visual feedback when a user types an invalid command.
type InterruptEvent ¶ added in v1.5.0
type InterruptEvent = events.InterruptEvent
InterruptEvent is a CLI-friendly alias for SuspendEvent. Alias for pkg/events.InterruptEvent.
type LineEvent ¶ added in v1.5.0
LineEvent represents raw text input that didn't match a command. Alias for pkg/events.LineEvent.
type NoOpObserver ¶ added in v1.5.0
type NoOpObserver = observe.NoOpObserver
NoOpObserver disables observer routing when configured. Alias for pkg/observe.NoOpObserver.
type Observer ¶ added in v1.5.0
Observer allows external packages to plug in observability (logs and process events). Alias for pkg/observe.Observer.
type ProcessWorker ¶ added in v1.6.5
type ProcessWorker = worker.ProcessWorker
ProcessWorker represents a worker that executes an OS process. Alias for pkg/worker.ProcessWorker.
func NewProcessWorker ¶ added in v1.3.0
func NewProcessWorker(name string, nameCmd string, args ...string) *ProcessWorker
NewProcessWorker creates a new Process worker for the given command. Alias for pkg/worker.NewProcessWorker.
type ResumeEvent ¶ added in v1.5.0
type ResumeEvent = events.ResumeEvent
ResumeEvent is the event that triggers a resumption. Alias for pkg/events.ResumeEvent.
type Router ¶ added in v1.5.0
Router maps events to reactions. Alias for pkg/events.events.
func NewRouter ¶ added in v1.5.0
func NewRouter(opts ...RouterOption) *Router
NewRouter creates a new Control events. Alias for pkg/events.Newevents.
type RouterOption ¶ added in v1.5.0
type RouterOption = events.RouterOption
RouterOption is an option for configuring a events. Alias for pkg/events.RouterOption.
type Runnable ¶ added in v1.5.0
Runnable defines a long-running process. Alias for pkg/runtime.Runnable.
type ShutdownEvent ¶ added in v1.5.0
type ShutdownEvent = events.ShutdownEvent
ShutdownEvent is triggered when the application should shut down gracefully. Alias for pkg/events.ShutdownEvent.
type SignalContext ¶ added in v1.6.0
SignalContext represents the signal context. It is the stable contract for signal handling in v1.5+. It wraps a standard context.Context and adds signal-specific metadata (Reason, ForceExit). Consumers like Trellis should rely on this type definition.
func Context ¶ added in v1.3.0
func Context() *SignalContext
Context returns a signal-aware context using default settings. This is the manual setup path for gradual migrations.
Stable as of v1.6.0. Usage for gradual adoption: Replace context.Background() with lifecycle.Context() in existing applications without restructuring the entire codebase. Set up signal handling via the returned context instead of wiring through Run(). Example: See examples/context/main.go in the repository.
func NewSignalContext ¶
func NewSignalContext(parent context.Context, opts ...SignalOption) *SignalContext
NewSignalContext creates a context that cancels on SIGTERM/SIGINT. On the first signal, context is cancelled. On the second, it force exits. Behavior can be customized via functional options. Alias for pkg/signal.NewContext.
Example ¶
ExampleNewSignalContext demonstrates how to use the Dual Signal context. Note: This example is illustrative; in a real run, it waits for SIGINT/SIGTERM.
package main
import (
"context"
"fmt"
"time"
"github.com/aretw0/lifecycle"
)
func main() {
// Create a context that listens for signals.
ctx := lifecycle.NewSignalContext(context.Background())
// For checking output deterministically in this example, we cancel manually
// after a short delay, allowing "work" to happen first.
go func() {
time.Sleep(50 * time.Millisecond)
ctx.Cancel()
}()
// Simulate work
select {
case <-ctx.Done():
fmt.Println("Context cancelled too early")
case <-time.After(10 * time.Millisecond):
fmt.Println("Doing work...")
}
}
Output: Doing work...
type SignalOption ¶ added in v1.5.0
Option is a functional option for signal configuration. Alias for pkg/signal.Option.
type SignalState ¶ added in v1.3.0
SignalState returns a snapshot of the current configuration. Alias for signal.State.
func GetSignalState ¶ added in v1.5.0
func GetSignalState(ctx context.Context) (SignalState, bool)
GetSignalState returns a snapshot of the context's signal configuration.
type Source ¶ added in v1.5.0
Source is a producer of events. Alias for pkg/events.Source.
func NewOSSignalSource ¶ added in v1.5.0
NewOSSignalSource creates a source that listens for OS signals. Alias for pkg/events.NewOSSignalSource.
func NewTickerSource ¶ added in v1.5.0
NewTickerSource creates a source that emits periodic events. Alias for pkg/events.NewTickerSource.
type StateChecker ¶ added in v1.5.0
type StateChecker = events.StateChecker
StateChecker is an optional interface for handlers that can report if they are in an "Active" (e.g. Suspended) state.
type Supervisor ¶ added in v1.3.0
type Supervisor = supervisor.Supervisor
Supervisor defines the interface for a supervisor. Alias for pkg/supervisor.Supervisor.
func NewSupervisor ¶ added in v1.3.0
func NewSupervisor(name string, strategy SupervisorStrategy, specs ...SupervisorSpec) Supervisor
NewSupervisor creates a new Supervisor for the given workers. Alias for pkg/supervisor.New.
type SupervisorBackoff ¶ added in v1.3.1
type SupervisorBackoff = supervisor.Backoff
SupervisorBackoff defines the retry policy for failed children. Alias for pkg/supervisor.Backoff.
type SupervisorFactory ¶ added in v1.3.0
type SupervisorFactory = supervisor.Factory
SupervisorFactory is a function that creates a new worker instance. Alias for pkg/supervisor.Factory.
type SupervisorRestartPolicy ¶ added in v1.5.0
type SupervisorRestartPolicy = supervisor.RestartPolicy
SupervisorRestartPolicy defines when a child worker should be restarted. Alias for pkg/supervisor.RestartPolicy.
type SupervisorSpec ¶ added in v1.3.0
type SupervisorSpec = supervisor.Spec
SupervisorSpec defines the configuration for a supervised child worker. Alias for pkg/supervisor.Spec.
type SupervisorStrategy ¶ added in v1.3.0
type SupervisorStrategy = supervisor.Strategy
SupervisorStrategy defines how the supervisor handles child failures. Alias for pkg/supervisor.Strategy.
type SuspendEvent ¶ added in v1.5.0
type SuspendEvent = events.SuspendEvent
SuspendEvent is the event that triggers a suspension. Alias for pkg/events.SuspendEvent.
type SuspendHandler ¶ added in v1.5.0
type SuspendHandler = events.SuspendHandler
SuspendHandler manages Suspend and Resume events. Alias for pkg/events.SuspendHandler.
func NewSuspendHandler ¶ added in v1.5.0
func NewSuspendHandler() *SuspendHandler
NewSuspendHandler creates a new handler for suspend/resume events. Alias for pkg/events.NewSuspendHandler.
type SuspendManager ¶ added in v1.5.0
SuspendManager provides channel-based suspend/resume with context cancellation. Use this for workers that need to support cancellable suspension. For maximum performance (>10k suspends/sec), use sync.Cond directly.
Example:
type MyWorker struct {
lifecycle.BaseWorker
suspendMgr *lifecycle.SuspendManager
}
func (w *MyWorker) Run(ctx context.Context) error {
for {
if err := w.suspendMgr.Wait(ctx); err != nil {
return err
}
// Do work...
}
}
See examples/suspend/channels/ for complete example. Alias for pkg/worker/suspend.Manager.
func NewSuspendManager ¶ added in v1.5.0
func NewSuspendManager() *SuspendManager
NewSuspendManager creates a suspend manager (initially running). Alias for pkg/worker/suspend.NewManager.
type Suspendable ¶ added in v1.5.0
type Suspendable = worker.Suspendable
Suspendable defines a worker that can pause its execution in-place without exiting. Alias for pkg/worker.Suspendable.
type SuspendableHandler ¶ added in v1.5.0
type SuspendableHandler = events.SuspendableHandler
SuspendableHandler is an optional interface for handlers that support the full Suspend/Resume lifecycle (Suspend, Intercept, Resume).
type Task ¶ added in v1.5.0
Task represents a handle to a background goroutine. It allows waiting for completion and checking errors. Alias for pkg/runtime.Task.
type TerminateEvent ¶ added in v1.5.0
type TerminateEvent = events.TerminateEvent
TerminateEvent is a high-level event that chains Suspend and Shutdown. Alias for pkg/events.TerminateEvent.
type TerminateOption ¶ added in v1.5.0
type TerminateOption = events.TerminateOption
TerminateOption configures the TerminateHandler. Alias for pkg/events.TerminateOption.
func WithContinueOnFailure ¶ added in v1.5.0
func WithContinueOnFailure(continueOnFailure bool) TerminateOption
WithContinueOnFailure configures whether to proceed with shutdown even if suspension fails. Alias for pkg/events.WithContinueOnFailure.
type TickEvent ¶ added in v1.5.0
TickEvent represents a periodic time tick. Alias for pkg/events.TickEvent.
type UnknownCommandEvent ¶ added in v1.5.0
type UnknownCommandEvent = events.UnknownCommandEvent
UnknownCommandEvent is emitted when a command is not found in the mappings. Alias for pkg/events.UnknownCommandEvent.
type WebhookOption ¶ added in v1.6.5
type WebhookOption = events.WebhookOption
WebhookOption configures a WebhookSource. Alias for pkg/events.WebhookOption.
func WithMaxPayloadBytes ¶ added in v1.6.5
func WithMaxPayloadBytes(n int64) WebhookOption
WithMaxPayloadBytes configures the maximum request body size for webhooks. Alias for pkg/events.WithMaxPayloadBytes.
type WebhookSource ¶ added in v1.6.5
type WebhookSource = events.WebhookSource
WebhookSource listens for HTTP requests and converts them into lifecycle events. Alias for pkg/events.WebhookSource.
func NewWebhookSource ¶ added in v1.5.0
func NewWebhookSource(addr string, opts ...WebhookOption) *WebhookSource
NewWebhookSource creates a source that listens for Webhooks. Alias for pkg/events.NewWebhookSource.
type Worker ¶ added in v1.3.0
Worker defines the interface for a managed unit of work. Alias for pkg/worker.Worker.
func NewContainerWorker ¶ added in v1.3.0
NewContainerWorker creates a new Worker from a Container interface. Alias for pkg/worker.NewContainerWorker.
type WorkerState ¶ added in v1.3.0
WorkerState represents the snapshot of a worker's state.
type WorkerStatus ¶ added in v1.3.0
WorkerStatus represents the lifecycle state of a worker.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
baseworker
command
|
|
|
basic
command
|
|
|
chained_cancels
command
|
|
|
container
command
|
|
|
context
command
|
|
|
control
command
|
|
|
demo
command
|
|
|
hooks
command
|
|
|
input/json
command
|
|
|
interactive_dx
command
|
|
|
introspection
command
|
|
|
observability
command
|
|
|
passthrough
command
|
|
|
reliability
command
|
|
|
reload
command
|
|
|
repl
command
|
|
|
supervisor
command
|
|
|
supervisor/dynamic
command
|
|
|
suspend/channels
command
|
|
|
suspend/cond
command
|
|
|
test_sighup
command
|
|
|
worker
command
|
|
|
zombie
command
|
|
|
pkg
|
|
|
core/container
Package container defines a generic interface for managing containerized workloads.
|
Package container defines a generic interface for managing containerized workloads. |
|
core/log
Package log provides a lightweight, structured logging interface for the lifecycle library.
|
Package log provides a lightweight, structured logging interface for the lifecycle library. |
|
core/metrics
Package metrics provides a decoupled interface for collecting library metrics.
|
Package metrics provides a decoupled interface for collecting library metrics. |
|
core/observe
Package observe provides a lightweight observer facade for logs and key process events.
|
Package observe provides a lightweight observer facade for logs and key process events. |
|
core/runtime
Package runtime provides utilities for deterministic process management and boilerplate reduction.
|
Package runtime provides utilities for deterministic process management and boilerplate reduction. |
|
core/signal
Package signal provides a stateful signal context with introspection and LIFO hooks.
|
Package signal provides a stateful signal context with introspection and LIFO hooks. |
|
core/supervisor
Package supervisor implements the Supervisor Pattern for managing process and worker lifecycles.
|
Package supervisor implements the Supervisor Pattern for managing process and worker lifecycles. |
|
core/worker
Package worker defines interfaces and implementations for managed units of work.
|
Package worker defines interfaces and implementations for managed units of work. |
|
events
Package events implements the Lifecycle Control Plane.
|
Package events implements the Lifecycle Control Plane. |