Documentation
¶
Overview ¶
Package runtime provides utilities for deterministic process management and boilerplate reduction.
It focuses on:
- Preventing hangs during shutdown (timeouts).
- Standardizing application entry points (Run).
- Providing context-aware primitives (Sleep).
- Enabling Critical Sections via DoDetached (for durable operations).
Configuration ¶
The Run function accepts generic options to configure the runtime environment:
- WithLogger(l): Sets the global logger.
- WithMetrics(p): Sets the global metrics provider.
- signal.Option: Configures the SignalContext (e.g. WithForceExit).
This package is part of the Lifecycle Data Plane core.
Index ¶
- func BlockWithTimeout(done <-chan struct{}, timeout time.Duration) error
- func Do(ctx context.Context, fn func(ctx context.Context) error) (err error)
- func DoDetached(parent context.Context, fn func(ctx context.Context) error) error
- func GetFunctionName(i interface{}) string
- func Receive[V any](ctx context.Context, ch <-chan V) iter.Seq[V]
- func Run(r Runnable, opts ...any) error
- func Sleep(ctx context.Context, d time.Duration) error
- func WaitForGlobal()
- func WithLogger(l *slog.Logger) any
- func WithMetrics(p metrics.Provider) any
- func WithShutdownTimeout(d time.Duration) any
- func WithTaskTracking(ctx context.Context, wg *sync.WaitGroup) context.Context
- type ErrorHandler
- type GoOption
- type Runnable
- type RunnableFunc
- type Task
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BlockWithTimeout ¶
BlockWithTimeout blocks until the done channel is closed or the timeout expires. It returns nil if the operation completed (channel closed), or context.DeadlineExceeded if the timeout occurred.
Usage:
go func() {
DoCleanup()
close(done)
}()
if err := lifecycle.BlockWithTimeout(done, 5*time.Second); err != nil {
// Force exit or log error
}
func Do ¶
Do executes a function with Managed Reliability (Panic Recovery + Observability). Unlike the deprecated internal/reliability.Do, this function RESPECTS context cancellation. For a "Critical Section" that survives cancellation, use DoDetached.
func DoDetached ¶
DoDetached executes a function in a "Critical Section" that delays context cancellation. It wraps the provided function in a shielded context that ignores the parent's cancellation. (Uses context.WithoutCancel available in Go 1.21+)
func GetFunctionName ¶
func GetFunctionName(i interface{}) string
GetFunctionName returns the name of the function or method. It uses reflection to retrieve the runtime name.
func Receive ¶
Receive creates a push iterator that yields values from the channel until the context is cancelled or the channel is closed. It eliminates the need for manual select loops when consuming channels, preventing deadlocks and "orphaned receiver" bugs.
Usage:
for msg := range runtime.Receive(ctx, ch) {
process(msg)
}
func Run ¶
Run executes the application logic with a managed SignalContext. It accepts a Runnable (Job, Router, Supervisor) and manages its lifecycle. It accepts generic options (e.g. SignalOption, WithLogger, WithMetrics) to configure the runtime. This is the recommended entry point for main().
func Sleep ¶
Sleep pauses the current goroutine for at least the duration d. Unlike time.Sleep, it returns immediately if the context is cancelled. Returns nil if the duration passed, or ctx.Err() if cancelled.
func WaitForGlobal ¶
func WaitForGlobal()
WaitForGlobal waits for all goroutines started with Go() that used the fallback global tracker. This is useful if you are using Go() outside of Run().
func WithLogger ¶
WithLogger returns an option to configure the global logger.
func WithMetrics ¶
WithMetrics returns an option to configure the global metrics provider.
func WithShutdownTimeout ¶
WithShutdownTimeout returns an option to configure the diagnostic timeout during shutdown. If the application doesn't finish within this duration, it dumps goroutine stacks. Default is 2s.
Types ¶
type ErrorHandler ¶
type ErrorHandler func(error)
ErrorHandler is a function type used to capture and process errors from background tasks asynchronously. This is useful for logging, reporting, or triggering recovery logic without blocking the main flow.
type GoOption ¶
type GoOption func(*goConfig)
GoOption provides functional configuration for background tasks.
func WithErrorHandler ¶
func WithErrorHandler(h ErrorHandler) GoOption
WithErrorHandler registers a handler for task errors. This is useful for logging or metrics when you don't want to Wait() on the task.
func WithStackCapture ¶ added in v1.6.0
WithStackCapture forces stack capture behavior for background task panics. When enabled, stack traces are captured for observer hooks even if debug logging is off. When disabled, stack traces are skipped even if debug logging is on. If not set, behavior auto-detects based on debug logging level.
type RunnableFunc ¶
RunnableFunc is a function adapter that implements Runnable.
type Task ¶
type Task interface {
// Wait blocks until the task completes.
// Returns nil if the task finished successfully, or an error if the task
// returned an error or panicked.
Wait() error
}
Task represents a handle to a background goroutine managed by the lifecycle runtime. It allows for synchronization (Wait) and retrieval of results or synchronization errors.
A Task is created when using lifecycle.Go(). It provides a way to wait for a specific goroutine to finish even if the main application lifecycle is still running.
func Go ¶
Go starts a goroutine that is tracked by the lifecycle. If the context contains a TaskTracker (injected by Run), it adds to that WaitGroup. If not, it falls back to a global TaskTracker (accessible via WaitForGlobal), ensuring "Safe by Default". It also recovers from panics to prevent crashing the entire application.
The returned Task handle allows waiting for completion and checking errors. By default, errors are discarded unless an ErrorHandler is provided via WithErrorHandler.