shutdown

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PriorityHTTPServer is used for HTTP server shutdown (stop accepting new connections).
	PriorityHTTPServer = 90

	// PriorityBackgroundWorkers is used for background worker shutdown.
	PriorityBackgroundWorkers = 80

	// PriorityDatabase is used for database connection shutdown.
	PriorityDatabase = 70

	// PriorityCache is used for cache connection shutdown.
	PriorityCache = 60

	// PriorityMetrics is used for metrics/logging flush.
	PriorityMetrics = 50
)

Standard priorities for shutdown hooks (higher = earlier execution).

Variables

This section is empty.

Functions

func DefaultShutdownSignals

func DefaultShutdownSignals() []os.Signal

DefaultShutdownSignals returns the default signals used for graceful shutdown.

func DrainMiddleware

func DrainMiddleware(drainer *Drainer) func(http.Handler) http.Handler

DrainMiddleware is a middleware that tracks requests for graceful shutdown.

func ForceExit

func ForceExit(code int)

ForceExit terminates the process immediately with the given exit code. This should only be used when graceful shutdown fails completely.

func IsPanic

func IsPanic(err error) bool

IsPanic returns true if the error is a PanicError.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout returns true if the error is a TimeoutError.

func ShutdownReadyMiddleware

func ShutdownReadyMiddleware(manager *Manager) func(http.Handler) http.Handler

ShutdownReadyMiddleware returns a middleware that checks if the manager is shutting down and returns 503 for the /health/ready endpoint.

func WithTimeout

func WithTimeout(ctx context.Context, timeout time.Duration, name string, fn func(ctx context.Context) error) error

WithTimeout executes a function with a timeout. Returns TimeoutError if the function doesn't complete within the timeout.

func WithTimeoutAndPanicRecovery

func WithTimeoutAndPanicRecovery(ctx context.Context, timeout time.Duration, name string, fn func(ctx context.Context) error) (err error)

WithTimeoutAndPanicRecovery executes a function with timeout and panic recovery.

Types

type Config

type Config struct {
	// OverallTimeout is the maximum time allowed for all shutdown hooks to complete.
	// Default: 30 seconds.
	OverallTimeout time.Duration

	// PerHookTimeout is the maximum time allowed for a single hook to complete.
	// Default: 10 seconds.
	PerHookTimeout time.Duration

	// DrainTimeout is the time to wait for in-flight requests to complete.
	// Default: 10 seconds.
	DrainTimeout time.Duration

	// SlowHookThreshold is the duration after which a hook is considered slow
	// and a warning is logged.
	// Default: 5 seconds.
	SlowHookThreshold time.Duration
}

Config holds configuration for the shutdown manager.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default shutdown configuration.

func (*Config) Validate

func (c *Config) Validate()

Validate validates the configuration and sets defaults for zero values.

type Drainer

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

Drainer tracks and waits for in-flight operations to complete.

func NewDrainer

func NewDrainer() *Drainer

NewDrainer creates a new Drainer.

func (*Drainer) Add

func (d *Drainer) Add() bool

Add increments the count of in-flight operations. Returns false if draining has started.

func (*Drainer) Count

func (d *Drainer) Count() int64

Count returns the current number of in-flight operations.

func (*Drainer) Done

func (d *Drainer) Done()

Done decrements the count of in-flight operations.

func (*Drainer) IsDraining

func (d *Drainer) IsDraining() bool

IsDraining returns true if draining has started.

func (*Drainer) StartDrain

func (d *Drainer) StartDrain()

StartDrain signals that draining has started. New operations will be rejected after this call.

func (*Drainer) Wait

func (d *Drainer) Wait(ctx context.Context) error

Wait blocks until all in-flight operations complete or the context is canceled.

func (*Drainer) WaitWithTimeout

func (d *Drainer) WaitWithTimeout(timeout time.Duration) error

WaitWithTimeout blocks until all operations complete or timeout expires.

type HTTPDrainer

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

HTTPDrainer wraps an HTTP handler to track in-flight requests.

func NewHTTPDrainer

func NewHTTPDrainer(handler http.Handler) *HTTPDrainer

NewHTTPDrainer creates a new HTTP drainer wrapping the given handler.

func (*HTTPDrainer) ActiveRequests

func (d *HTTPDrainer) ActiveRequests() int64

ActiveRequests returns the number of in-flight requests.

func (*HTTPDrainer) IsDraining

func (d *HTTPDrainer) IsDraining() bool

IsDraining returns true if draining has started.

func (*HTTPDrainer) ServeHTTP

func (d *HTTPDrainer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP requests, tracking them for draining.

func (*HTTPDrainer) StartDrain

func (d *HTTPDrainer) StartDrain()

StartDrain starts draining connections.

func (*HTTPDrainer) Wait

func (d *HTTPDrainer) Wait(ctx context.Context) error

Wait waits for all in-flight requests to complete.

type Hook

type Hook struct {
	// Name identifies the hook for logging purposes.
	Name string

	// Priority determines execution order. Higher priorities execute first.
	// Use the Priority* constants for standard components.
	Priority int

	// Fn is the shutdown function to execute.
	Fn HookFunc
}

Hook represents a shutdown hook with metadata.

type HookFunc

type HookFunc func(ctx context.Context) error

HookFunc is a function that performs shutdown logic. It receives a context that will be canceled when the hook timeout expires.

type HookResult

type HookResult struct {
	Name     string
	Priority int
	Error    error
	Duration interface{} // time.Duration, but stored as interface for flexibility
}

HookResult contains the result of executing a shutdown hook.

type Manager

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

Manager coordinates graceful shutdown of all registered components.

func NewManager

func NewManager(cfg Config, logger *slog.Logger) *Manager

NewManager creates a new shutdown manager with the given configuration.

func NewManagerWithDefaults

func NewManagerWithDefaults() *Manager

NewManagerWithDefaults creates a shutdown manager with default configuration.

func (*Manager) Config

func (m *Manager) Config() Config

Config returns the manager's configuration.

func (*Manager) Done

func (m *Manager) Done() <-chan struct{}

Done returns a channel that is closed when shutdown is complete.

func (*Manager) Errors

func (m *Manager) Errors() []error

Errors returns all errors that occurred during shutdown.

func (*Manager) HookCount

func (m *Manager) HookCount() int

HookCount returns the number of registered hooks.

func (*Manager) IsShutdown

func (m *Manager) IsShutdown() bool

IsShutdown returns true if shutdown is complete.

func (*Manager) IsShuttingDown

func (m *Manager) IsShuttingDown() bool

IsShuttingDown returns true if shutdown is in progress.

func (*Manager) ListenForSignals

func (m *Manager) ListenForSignals() <-chan struct{}

ListenForSignals starts listening for OS shutdown signals and triggers shutdown when a signal is received. Returns a channel that is closed when shutdown is complete.

func (*Manager) Register

func (m *Manager) Register(name string, priority int, fn HookFunc)

Register adds a shutdown hook with the given name, priority, and function. Higher priority hooks are executed first.

func (*Manager) RegisterHook

func (m *Manager) RegisterHook(hook Hook)

RegisterHook adds a Hook struct to the registry.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown initiates graceful shutdown. It is safe to call multiple times. The first call triggers the shutdown, subsequent calls are no-ops.

func (*Manager) ShutdownWithContext

func (m *Manager) ShutdownWithContext(ctx context.Context)

ShutdownWithContext initiates graceful shutdown with an external context.

func (*Manager) State

func (m *Manager) State() State

State returns the current state of the manager.

func (*Manager) Wait

func (m *Manager) Wait()

Wait blocks until shutdown is complete.

type PanicError

type PanicError struct {
	Operation string
	Value     interface{}
}

PanicError is returned when a shutdown hook panics.

func (*PanicError) Error

func (e *PanicError) Error() string

type Registry

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

Registry manages shutdown hooks.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new hook registry.

func (*Registry) Clear

func (r *Registry) Clear()

Clear removes all registered hooks.

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of registered hooks.

func (*Registry) Hooks

func (r *Registry) Hooks() []Hook

Hooks returns all registered hooks.

func (*Registry) Register

func (r *Registry) Register(name string, priority int, fn HookFunc)

Register adds a shutdown hook to the registry.

func (*Registry) RegisterHook

func (r *Registry) RegisterHook(hook Hook)

RegisterHook adds a Hook struct to the registry.

type SignalHandler

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

SignalHandler manages OS signal handling for graceful shutdown.

func NewSignalHandler

func NewSignalHandler(signals ...os.Signal) *SignalHandler

NewSignalHandler creates a new signal handler that listens for the specified signals. If no signals are provided, it defaults to SIGTERM, SIGINT, and SIGQUIT.

func (*SignalHandler) Listen

func (h *SignalHandler) Listen() <-chan os.Signal

Listen starts listening for shutdown signals. It returns a channel that will receive the signal when one is caught. The signal channel will only deliver one signal before being closed.

func (*SignalHandler) Signals

func (h *SignalHandler) Signals() []os.Signal

Signals returns the list of signals being monitored.

func (*SignalHandler) Stop

func (h *SignalHandler) Stop()

Stop stops listening for signals and cleans up.

type State

type State int

State represents the current state of the shutdown manager.

const (
	// StateRunning indicates the manager is running normally.
	StateRunning State = iota

	// StateShuttingDown indicates shutdown is in progress.
	StateShuttingDown

	// StateShutdown indicates shutdown is complete.
	StateShutdown
)

func (State) String

func (s State) String() string

type TimeoutError

type TimeoutError struct {
	Operation string
	Timeout   time.Duration
}

TimeoutError is returned when a shutdown operation times out.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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