runtime

package
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: 14 Imported by: 0

Documentation

Overview

Package runtime provides utilities for deterministic process management and boilerplate reduction.

It focuses on:

  1. Preventing hangs during shutdown (timeouts).
  2. Standardizing application entry points (Run).
  3. Providing context-aware primitives (Sleep).
  4. 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

Constants

This section is empty.

Variables

This section is empty.

Functions

func BlockWithTimeout

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

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

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

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

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

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

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

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

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

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

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

func WithLogger(l *slog.Logger) any

WithLogger returns an option to configure the global logger.

func WithMetrics

func WithMetrics(p metrics.Provider) any

WithMetrics returns an option to configure the global metrics provider.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) any

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.

func WithTaskTracking

func WithTaskTracking(ctx context.Context, wg *sync.WaitGroup) context.Context

WithTaskTracking returns a context that tracks goroutines using the provided WaitGroup. This is used by Run to inject a wait group into the context.

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

func WithStackCapture(enabled bool) GoOption

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 Runnable

type Runnable interface {
	Start(ctx context.Context) error
}

Runnable defines a long-running process that can be started with a context.

func Job

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

Job creates a Runnable from a function. It is an alias for RunnableFunc, providing a cleaner API for v1-style CLIs.

type RunnableFunc

type RunnableFunc func(context.Context) error

RunnableFunc is a function adapter that implements Runnable.

func (RunnableFunc) Start

func (f RunnableFunc) Start(ctx context.Context) error

Start calls the underlying function.

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

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

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.

Jump to

Keyboard shortcuts

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