lifecycle

package module
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

README

lifecycle

Go Report Card Go Reference License Release

lifecycle is a Go library for managing application shutdown signals and interactive terminal I/O robustly. It centralizes the "Dual Signal" logic and "Interruptible I/O" patterns originally extracted from Trellis and designed for any tool needing robust signal handling.

Vision

To be the standard Control Plane for Infrastructure-Aware Applications (Services, Agents, CLIs).

  • Foundation (v1.0-v1.4): Solves "Death Management" (Signals, Blocking I/O, Zombies).
  • Control Plane (v1.5+): Solves "Life Management" (Events, Reactions, Hot Reloading).

Project Status & Versioning

[!IMPORTANT] v1.5+ (Current): Provides the Application Control Plane, generalizing "Signals" into "Events" (Hot Reload, Health Checks, Input Commands). Contains breaking changes from v1.4 - see MIGRATION.md.

v1.0-v1.4 (LTS): Focuses strictly on Death Management (Graceful Shutdown, Signals, Leak Prevention).

Installation

go get github.com/aretw0/lifecycle

Features (Foundation v1)

  • SignalContext: Differentiates between SIGINT (User Interrupt) and SIGTERM (System Shutdown).
    • Configurable Thresholds: Support for "Industry Standard" (Cancel on 1st), "Escalation" (Cancel on Nth), and "Unsafe" (No auto-kill) modes.
    • SIGTERM: Always triggers immediate graceful shutdown (context cancellation).
  • TermIO:
    • InterruptibleReader: Wraps io.Reader to allow Read() calls to be abandoned when a context is cancelled (avoids goroutine leaks).
    • Platform Aware: Automatically uses CONIN$ on Windows.
      • Why? On Windows, standard os.Stdin closes immediately upon receiving a signal (like Ctrl+C), causing a fatal EOF before the application can gracefully handle the signal. lifecycle switches to CONIN$, which keeps the handle open, allowing the SignalContext to process the event.
    • UpgradeTerminal: Helper to upgrade an arbitrary existing io.Reader (if it identifies as a terminal) to the safe platform-specific reader.
  • Observability & Introspection:
    • Unified Dashboard: SystemDiagram synthesizes Signal and Worker states into a single Mermaid visualization.
    • Rich Metrics: Built-in providers for tracking shutdown health, data loss, and shutdown latency.
    • Stall Detection: Automatically detects and warns if a shutdown hook is stalled (runs > 5s).
  • Reliability Primitives (v1.4):
    • Critical Sections: lifecycle.Do(ctx, fn) shields atomic operations from cancellation and returns any error from the protected function.
    • Introspection: SignalContext.Reason() to differentiate between "Manual Stop", "Interrupt", or "Timeout".
  • Worker & Supervisor (v1.3):
    • Unified Interface: Standard Start, Stop, Wait contract for Processes, Goroutines, and Containers.
    • Supervision Tree: Supervisor manages hierarchical worker clusters with restart policies (OneForOne, OneForAll).
    • Dynamic Topology: Add or remove workers at runtime.
    • Functional Workers: Turn any Go function into a managed Worker.
    • Process Hygiene: Automatic cleanup of child processes if the parent dies (Job Objects/PDeathSig).
    • Handover Protocol: Standardized environment variables (LIFECYCLE_RESUME_ID, LIFECYCLE_PREV_EXIT) to pass context across restarts.
    • Container Abstraction: Generic interface to manage containerized workloads without direct SDK dependencies.
  • DX Helpers (v1.4 & v1.5+):
    • Run: One-line main entry point with options (WithLogger, WithMetrics).
    • NewInteractiveRouter: Pre-configured router for CLIs (Signals + Input + Commands).
    • Sleep: Context-aware sleep (returns immediately on cancel).
    • OnShutdown: Type-safe hook registration without casting.

Control Plane Features

The Control Plane provides event-driven orchestration for modern Go applications:

  • Event Router: Generalizes Signals into Events (Webhook, FileWatch, HealthCheck).
  • Event Conditioning & Pub/Sub (v1.7+): Handle bursts gracefully with DebounceHandler and route events to idiomatic Go channels via events.Notify(ch).
  • Managed Concurrency: lifecycle.Go(ctx, fn) for non-leaking goroutines.
  • Reactions: Reload, Suspend, Scale alongside Shutdown.
Managed Concurrency

lifecycle now provides primitives to manage goroutines safely, ensuring they respect shutdown signals and provide visibility.

lifecycle.Run(func(ctx context.Context) error {
    // Fire-and-forget but tracked and panic-safe
    lifecycle.Go(ctx, func(ctx context.Context) error {
        // ...
        return nil
    })
    return nil
})

Quick Start (The Golden Path)

For 99% of CLI applications, you just need lifecycle.Run. It handles signals, context cancellation, and cleanup automatically.

package main

import (
    "context"
    "fmt"
    "time"
    "github.com/aretw0/lifecycle"
)

func main() {
    // 1. Wrap your logic in a Job
    // 2. lifecycle.Run manages the boring "Death Management" stuff
    lifecycle.Run(lifecycle.Job(func(ctx context.Context) error {
        fmt.Println("App started. Press Ctrl+C to exit.")
        
        // 3. Use lifecycle.Go to spawn safe, tracked background tasks
        task := lifecycle.Go(ctx, func(ctx context.Context) error {
            // This goroutine is automatically tracked and waited for on shutdown
            return doWork(ctx)
        }, lifecycle.WithErrorHandler(func(err error) {
            fmt.Printf("Task failed: %v\n", err)
        }))

        // Optional: Wait for a specific task manually
        // err := task.Wait()

        // 4. Wait for interrupt
        <-ctx.Done()
        fmt.Println("Shutting down...")
        return nil
    }))
}

Basic Patterns (CLI & Automation)

1. Robust Input (Windows Safe)

Reading from Stdin on Windows is tricky. lifecycle solves the "Ctrl+C kills the prompt" problem by automatically using CONIN$.

// Smart Open (handles Windows CONIN$)
reader, _ := lifecycle.OpenTerminal()
defer reader.Close()

// Wrap to respect context cancellation (prevents blocked Read calls)
r := lifecycle.NewInterruptibleReader(reader, ctx.Done())

buf := make([]byte, 1024)
n, err := r.Read(buf)
if lifecycle.IsInterrupted(err) {
    return // Clean exit
}
2. Graceful Hooks

Register cleanup functions that run after the context is cancelled but before the process exits.

lifecycle.OnShutdown(ctx, func() {
    db.Close()
    fmt.Println("Cleanup done locally")
})

Advanced Patterns (Control Plane v1.5+)

For complex long-running services/agents that need dynamic behavior (Hot Reload, Supervisors).

1. Managed Concurrency & Global Fallback

lifecycle.Go(ctx, fn) is designed to work within lifecycle.Run. However, if you use it in a standalone script, it safely falls back to a Global Task Tracker.

func main() {
    ctx := context.Background()
    
    // Works safely even without lifecycle.Run
    lifecycle.Go(ctx, func(ctx context.Context) error {
        // ...
        return nil
    })
    
    // Explicitly wait for global tasks (required without Run)
    lifecycle.WaitForGlobal()
}
2. Supervisor & Workers

Manage long-running processes, containers, or goroutines with restarts and hygiene.

// Create a Supervisor with a "OneForOne" restart strategy
sup := lifecycle.NewSupervisor("agent", lifecycle.SupervisorStrategyOneForOne,
    lifecycle.NewProcessWorker("pinger", "ping", "1.1.1.1"),
    lifecycle.NewWorkerFromFunc("metrics", metricsLoop),
)

sup.Start(ctx)
<-ctx.Done()
sup.Stop(context.Background())
3. System Introspection

Generate live architecture diagrams of your running application.

// Generate Mermaid Dashboard
diagram := lifecycle.SystemDiagram(ctx.State(), supervisor.State())
fmt.Println(diagram)

Metrics Palette

The library uses a consistent color palette for all generated diagrams:

  • 🟡 Pending: Defined but not yet active.
  • 🔵 Running: Active and healthy.
  • 🟢 Stopped: Successfully terminated.
  • 🔴 Failed: Crashed or terminated with error.

I/O Safety

The library implements Context-Aware I/O to balance data preservation and responsiveness:

  • Read() (Pipeline Safe): Uses a Shielded Return strategy. If data arrives simultaneously with a cancellation signal, it returns the data (nil error). This guarantees no data loss in pipelines or logs.
  • ReadInteractive() (Interactive Safe): Uses a Strict Discard strategy. If the user hits Ctrl+C while typing, any partial input is discarded to prevent accidental execution of commands.

Documentation

Development & Contribution

Local Development (Multi-Module)

If you are developing lifecycle and procio simultaneously (e.g. adding features to procio that lifecycle needs), you can use the provided Makefile helpers to toggle a local go.work file:

# Enable local development (uses ../procio by default)
make work-on

# Enable local development with custom path
make work-on WORK_PATH=../../my-fork/procio

# Disable local development (return to published module)
make work-off

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:

  1. 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()

  2. 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()

  3. 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

Examples

Constants

View Source
const (
	WorkerStatusCreated = worker.StatusCreated
	WorkerStatusPending = worker.StatusPending
	WorkerStatusRunning = worker.StatusRunning
	WorkerStatusStopped = worker.StatusStopped
	WorkerStatusFailed  = worker.StatusFailed
)
View Source
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

View Source
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
)
View Source
const (
	RestartAlways    = supervisor.RestartAlways
	RestartOnFailure = supervisor.RestartOnFailure
	RestartNever     = supervisor.RestartNever
)

Variables

View Source
var DefaultRouter = events.DefaultRouter

DefaultRouter is the default instance for package-level helpers. Alias for pkg/events.Defaultevents.

View Source
var (
	// ErrNotHandled is a sentinel error that handlers can return to indicate they did not process the event.
	ErrNotHandled = events.ErrNotHandled
)
View Source
var Version string

Functions

func BlockWithTimeout added in v1.1.0

func BlockWithTimeout(done <-chan struct{}, timeout time.Duration) error

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

func Dispatch(ctx context.Context, e Event)

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

func Do(ctx context.Context, fn func(ctx context.Context) error) error

Do executes a function in a "Safe Executor" (Panic Recovery + Observability). Alias for pkg/runtime.Do.

func DoDetached added in v1.5.0

func DoDetached(parent context.Context, fn func(ctx context.Context) error) error

DoDetached executes a function in a "Critical Section" (Detached Context). Alias for pkg/runtime.DoDetached.

func GetForceExitThreshold added in v1.5.0

func GetForceExitThreshold(ctx context.Context) int

GetForceExitThreshold returns the number of signals required to trigger os.Exit(1).

func GetObserver added in v1.5.0

func GetObserver() observe.Observer

GetObserver returns the current global observer, if any. Alias for pkg/observe.GetObserver.

func Handle added in v1.5.0

func Handle(pattern string, handler Handler)

Handle registers a handler on the Defaultevents. Alias for pkg/events.Handle.

func HandleFunc added in v1.5.0

func HandleFunc(pattern string, handler func(context.Context, Event) error)

HandleFunc registers a handler function on the Defaultevents. Alias for pkg/events.HandleFunc.

func IsInterrupted

func IsInterrupted(err error) bool

IsInterrupted checks if an error indicates an interruption (Context Canceled, EOF, etc.). Alias for pkg/termio.IsInterrupted.

func IsUnsafe added in v1.5.0

func IsUnsafe(ctx context.Context) bool

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

  1. First Signal: Triggers the configured InterruptHandler (or SuspendHandler). For REPLs, this might clear the line. For services, this triggers suspension.
  2. 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

func NewLogMetricsProvider() metrics.Provider

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

func NewNoOpLogger() *slog.Logger

NewNoOpLogger returns a logger that discards all output. Alias for pkg/log.NewNoOpLogger.

func NewProcessCmd added in v1.7.2

func NewProcessCmd(ctx context.Context, name string, args ...string) *proc.Cmd

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

func NewWorkerFromFunc(name string, fn func(context.Context) error) worker.Worker

NewWorkerFromFunc creates a Worker from a function. Alias for pkg/worker.FromFunc.

func OnShutdown added in v1.4.0

func OnShutdown(ctx context.Context, fn func())

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

func Receive[V any](ctx context.Context, ch <-chan V) iter.Seq[V]

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

func ResetSignalCount(ctx context.Context)

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

func Run(r Runnable, opts ...any) error

Run executes the application logic with a managed SignalContext. Alias for pkg/runtime.Run.

func SetLogger added in v1.1.0

func SetLogger(l *slog.Logger)

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

func SetMetricsProvider(p metrics.Provider)

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

func SetObserver(o observe.Observer)

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

func Shutdown(ctx context.Context)

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

func ShutdownAndWait(ctx context.Context)

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

func Signal(ctx context.Context) os.Signal

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

func Sleep(ctx context.Context, d time.Duration) error

Sleep pauses the current goroutine for at least the duration d. Alias for pkg/runtime.Sleep.

func Start added in v1.5.0

func Start(ctx context.Context) error

Start begins the listening loop for the DefaultRouter. Alias for pkg/events.Start.

func StartProcess added in v1.1.0

func StartProcess(cmd *exec.Cmd) error

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

func StopAndWait(ctx context.Context, w Worker) error

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

func UpgradeTerminal(r io.Reader) (io.Reader, error)

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 Wait added in v1.5.0

func Wait(ctx context.Context)

Wait blocks until all shutdown hooks have finished.

func WithCancelOnInterrupt added in v1.5.0

func WithCancelOnInterrupt(enabled bool) signal.Option

WithCancelOnInterrupt controls whether SIGINT automatically cancels the context. Alias for pkg/signal.WithCancelOnInterrupt.

func WithForceExit added in v1.1.0

func WithForceExit(threshold int) signal.Option

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

func WithHookTimeout(d time.Duration) signal.Option

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

func WithLogger(l *slog.Logger) any

WithLogger returns a RunOption to configure the global logger. Alias for pkg/runtime.WithLogger.

func WithMetrics added in v1.5.0

func WithMetrics(p metrics.Provider) any

WithMetrics returns a RunOption to configure the global metrics provider. Alias for pkg/runtime.WithMetrics.

func WithResetTimeout added in v1.5.0

func WithResetTimeout(d time.Duration) signal.Option

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

func WithShutdownTimeout(d time.Duration) any

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

type Container = container.Container

Container represents a generic container interface. Alias for container.Container.

func NewMockContainer added in v1.3.0

func NewMockContainer(id string) Container

NewMockContainer creates a new MockContainer for testing. Alias for pkg/container.NewMockContainer.

type ContainerStatus added in v1.3.0

type ContainerStatus = container.Status

ContainerStatus represents the lifecycle state of a container. Alias for container.Status.

type Escalator added in v1.5.0

type Escalator = events.Escalator

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

func NewEscalator(primary Handler, fallback Handler) *Escalator

NewEscalator creates a new generic Double-Tap handler. Alias for pkg/events.NewEscalator.

type Event added in v1.5.0

type Event = events.Event

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

type GoOption = runtime.GoOption

GoOption configuration for Go. Alias for pkg/runtime.GoOption.

func WithErrorHandler added in v1.5.0

func WithErrorHandler(h func(error)) GoOption

WithErrorHandler creates an option to handle errors in background goroutines. Alias for pkg/runtime.WithErrorHandler.

func WithStackCapture added in v1.6.0

func WithStackCapture(enabled bool) GoOption

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

func NewGroup(ctx context.Context) (*Group, context.Context)

NewGroup creates a new Group derived from the given context. It acts like errgroup.WithContext.

func (*Group) Go added in v1.5.0

func (g *Group) Go(fn func(ctx context.Context) error)

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.

func (*Group) SetLimit added in v1.5.0

func (g *Group) SetLimit(n int)

SetLimit limits the number of active goroutines in this group to at most n. A negative value indicates no limit.

func (*Group) Wait added in v1.5.0

func (g *Group) Wait() error

Wait blocks until all function calls from the Go method have returned, then returns the first non-nil error (if any) from them.

type Handler added in v1.5.0

type Handler = events.Handler

Handler responds to an event. Alias for pkg/events.Handler.

func NewReloadHandler added in v1.5.0

func NewReloadHandler(onReload func(context.Context) error) Handler

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

func WithFixedEvent(h Handler, ev Event) Handler

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

type LineEvent = events.LineEvent

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

type Observer = observe.Observer

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

type Router = events.Router

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

type Runnable = runtime.Runnable

Runnable defines a long-running process. Alias for pkg/runtime.Runnable.

func Job added in v1.5.0

func Job(fn func(context.Context) error) Runnable

Job creates a Runnable from a function. Alias for pkg/runtime.Job.

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

type SignalContext = signal.Context

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

type SignalOption = signal.Option

Option is a functional option for signal configuration. Alias for pkg/signal.Option.

type SignalState added in v1.3.0

type SignalState = signal.State

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

type Source = events.Source

Source is a producer of events. Alias for pkg/events.Source.

func NewOSSignalSource added in v1.5.0

func NewOSSignalSource(signals ...os.Signal) Source

NewOSSignalSource creates a source that listens for OS signals. Alias for pkg/events.NewOSSignalSource.

func NewTickerSource added in v1.5.0

func NewTickerSource(interval time.Duration) Source

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

type SuspendManager = suspend.Manager

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

type Task = runtime.Task

Task represents a handle to a background goroutine. It allows waiting for completion and checking errors. Alias for pkg/runtime.Task.

func Go added in v1.5.0

func Go(ctx context.Context, fn func(context.Context) error, opts ...GoOption) Task

Go starts a tracked goroutine. Alias for pkg/runtime.Go.

The returned Task handle allows waiting for completion and checking errors. By default, errors are discarded unless an ErrorHandler is provided via WithErrorHandler.

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

type TickEvent = events.TickEvent

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

type Worker = worker.Worker

Worker defines the interface for a managed unit of work. Alias for pkg/worker.Worker.

func NewContainerWorker added in v1.3.0

func NewContainerWorker(name string, c Container) Worker

NewContainerWorker creates a new Worker from a Container interface. Alias for pkg/worker.NewContainerWorker.

type WorkerState added in v1.3.0

type WorkerState = worker.State

WorkerState represents the snapshot of a worker's state.

type WorkerStatus added in v1.3.0

type WorkerStatus = worker.Status

WorkerStatus represents the lifecycle state of a worker.

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
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.

Jump to

Keyboard shortcuts

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