xshutdown

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 21, 2026 License: MIT Imports: 7 Imported by: 1

README

xshutdown

CI

Graceful-shutdown coordination for Go, built around context. A Manager owns a cancelable context; canceling it cascades to every derived child through the context tree. On top of that signal it tracks in-flight work and runs cleanup callbacks on shutdown, draining everything within a configurable timeout.

No global state — create a Manager with New and pass it where needed.

xshutdown/      Manager: context node + drain + signal helpers

Install

go get github.com/gopherex/xshutdown

Minimum Go: 1.25.0. No third-party dependencies.

Quick start

Wait on SIGINT/SIGTERM, drain in-flight work, then close resources — bounded by a timeout:

import (
    "context"
    "log"
    "time"

    "github.com/gopherex/xshutdown"
)

func main() {
    stop := xshutdown.New(context.Background(),
        xshutdown.WithPreStopDelay(5*time.Second), // let the LB deregister first
        xshutdown.WithTimeout(10*time.Second),     // then drain within 10s
        xshutdown.WithForceExit(1),                // hard-exit if drain hangs
        xshutdown.WithErrorHandler(func(err error) { log.Println("shutdown:", err) }),
    )

    db := openDB()
    stop.RegisterFnErr(func(context.Context) error { return db.Close() })

    // tracked worker: winds down on stop.Context() cancel, drained by Stop
    stop.Go(func(ctx context.Context) { serve(ctx) })

    // Run installs SIGINT/SIGTERM, blocks, then Stops.
    if err := stop.Run(); err != nil {
        log.Fatal(err) // e.g. xshutdown.ErrShutdownTimeout
    }
}

The import block above no longer needs os/signal or syscall — Run wires signals internally.

Derive a child context tied to the Manager:

ctx, cancel := stop.Derive()
defer cancel()
// ctx cancels on its own cancel OR when stop.Stop() runs

API

New returns a concrete *Manager. Accept an interface in components for looser coupling and mockability:

  • Registrar — register side: Context, Derive, Register, RegisterFnErr, Go. Pass to components that register their own cleanup or tracked work.
  • Controller — drive side: Done, Stop, Wait, WaitSignal, Run. Held by main to trigger/await shutdown.
  • Shutdowner — composition of both, the full contract.
s := xshutdown.New(parent, opts...)

s.Context()                  // cancelable root; derive children from it
s.Done()                     // <-chan struct{}, = s.Context().Done()
s.Derive()                   // (child context, cancel) of s.Context()

s.Register(cancels...)       // context.CancelFunc run on Stop (foreign cancels)
s.RegisterFnErr(fns...)      // func(ctx) error cleanup; errors joined into Stop()
s.Go(fn)                     // func(ctx) tracked task, drained by Stop

s.Stop()                     // shutdown; returns error
s.Wait(ch)                   // block on chan struct{}, then Stop
s.WaitSignal(ch)             // block on chan os.Signal, then Stop
s.Run()                      // install signals (SIGINT/SIGTERM), block, then Stop

Registration unit is context.CancelFunc (underlying func()), so any func(){} is accepted — no separate plain-func registrar.

Options
WithTimeout(d)          // bound the Go-task drain; d <= 0 waits forever (default)
WithPreStopDelay(d)     // wait d before canceling, so an LB/mesh can deregister
WithForceExit(code)     // os.Exit(code) if the drain times out (hard backstop)
WithErrorHandler(fn)    // fn(err) per cleanup error + ErrShutdownTimeout, as it happens
WithSignals(sigs...)    // signals Run listens for; defaults to SIGINT, SIGTERM

Shutdown sequence

Stop is idempotent (sync.Once); the first call's result is returned to all callers. It:

  1. waits WithPreStopDelay (if set), still serving — lets an LB deregister
  2. cancels the context — derived children and Go tasks see ctx.Done()
  3. runs Register'd cancels, in registration order
  4. drains Go tasks, waiting at most WithTimeout (a shared deadline context). On timeout with WithForceExit, calls os.Exit(code) and stops here
  5. runs RegisterFnErr cleanups, passing that deadline context
  6. returns errors.Join of cleanup errors plus ErrShutdownTimeout if draining timed out

Each error in steps 4–5 is also handed to WithErrorHandler as it occurs.

Notes

  • Cleanups run on the goroutine that calls Stop (or the one blocked in Wait/WaitSignal).
  • A Manager is single-use per lifecycle.

Documentation

Overview

Package xshutdown coordinates graceful shutdown of an application.

A Manager owns a cancelable context. Children derive from it via Context or Derive, so canceling the Manager cascades through the context tree the same way context cancellation always does. On top of that signal, a Manager can track in-flight work (Go) and run cleanup callbacks (Register, RegisterFnErr) on shutdown, draining everything within a configurable timeout.

There is no global state: create a Manager with New and pass it where needed, either concretely or behind the Shutdowner interface.

Index

Constants

This section is empty.

Variables

View Source
var ErrShutdownTimeout = errors.New("xshutdown: timeout waiting for tasks")

ErrShutdownTimeout is returned by Stop when tracked Go tasks do not finish within the configured timeout.

Functions

This section is empty.

Types

type Controller

type Controller interface {
	Done() <-chan struct{}
	Stop() error
	Wait(ch chan struct{}) error
	WaitSignal(ch chan os.Signal) error
	Run() error
}

Controller is the drive side: accept it where shutdown is triggered or awaited (typically main).

type Manager

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

Manager coordinates shutdown for a context subtree.

func New

func New(parent context.Context, opts ...Option) *Manager

New returns a Manager whose context derives from parent. A nil parent is treated as context.Background.

func (*Manager) Context

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

Context returns the Manager's context. Derive children from it so they cancel when the Manager stops.

func (*Manager) Derive

func (m *Manager) Derive() (context.Context, context.CancelFunc)

Derive returns a child context and its cancel. The child cancels on its own cancel or when the Manager stops (via the context tree).

func (*Manager) Done

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

Done reports shutdown, equivalent to m.Context().Done().

func (*Manager) Go

func (m *Manager) Go(fn func(ctx context.Context))

Go runs fn in a tracked goroutine. fn should observe ctx and return when it is canceled; Stop waits for all such goroutines (bounded by WithTimeout). Calls after shutdown begins still run but are not tracked.

func (*Manager) Register

func (m *Manager) Register(cancels ...context.CancelFunc)

Register adds cancel functions run on Stop, in registration order. Use it for contexts that do not derive from this Manager's context.

func (*Manager) RegisterFnErr

func (m *Manager) RegisterFnErr(fns ...func(ctx context.Context) error)

RegisterFnErr adds cleanup callbacks run on Stop after Go tasks drain. Each receives the shutdown context (carrying the WithTimeout deadline); returned errors are joined into Stop's result.

func (*Manager) Run

func (m *Manager) Run() error

Run installs a handler for the configured signals (SIGINT and SIGTERM by default), blocks until one arrives, then calls Stop and returns its result.

func (*Manager) Stop

func (m *Manager) Stop() error

Stop shuts down: optionally wait WithPreStopDelay, cancel the context, run registered cancels, drain Go tasks within the timeout, then run RegisterFnErr cleanups. It is idempotent; the first call's result is returned to all callers. The error joins any cleanup errors with ErrShutdownTimeout if draining timed out.

func (*Manager) Wait

func (m *Manager) Wait(ch chan struct{}) error

Wait blocks until ch receives or is closed, then calls Stop.

func (*Manager) WaitSignal

func (m *Manager) WaitSignal(ch chan os.Signal) error

WaitSignal blocks until an OS signal arrives on ch, then calls Stop.

type Option

type Option func(*Manager)

Option configures a Manager.

func WithErrorHandler

func WithErrorHandler(fn func(error)) Option

WithErrorHandler sets a callback invoked for every shutdown error as it happens: each cleanup failure and ErrShutdownTimeout. Errors are still joined into Stop's result regardless.

func WithForceExit

func WithForceExit(code int) Option

WithForceExit makes Stop call os.Exit(code) if Go tasks do not drain within the timeout, instead of running cleanups against an expired deadline. It is a hard backstop against a hung drain; pair with WithTimeout.

func WithPreStopDelay

func WithPreStopDelay(d time.Duration) Option

WithPreStopDelay makes Stop wait d before canceling the context, leaving in-flight work running. Use it so a load balancer or service mesh can deregister the instance before connections drain (e.g. Kubernetes SIGTERM).

func WithSignals

func WithSignals(sigs ...os.Signal) Option

WithSignals sets the OS signals Run listens for. Defaults to SIGINT and SIGTERM when unset.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout bounds shutdown: Stop waits at most d for Go tasks to finish and passes a context with that deadline to RegisterFnErr callbacks. A value <= 0 (the default) waits indefinitely.

type Registrar

type Registrar interface {
	Context() context.Context
	Derive() (context.Context, context.CancelFunc)
	Register(cancels ...context.CancelFunc)
	RegisterFnErr(fns ...func(ctx context.Context) error)
	Go(fn func(ctx context.Context))
}

Registrar is the register side: accept it in components that derive contexts and register their own cleanup or tracked work.

type Shutdowner

type Shutdowner interface {
	Registrar
	Controller
}

Shutdowner is the full contract implemented by Manager, composing Registrar and Controller.

Jump to

Keyboard shortcuts

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