Documentation
¶
Overview ¶
Package shutdown coordinates a process's graceful shutdown — registered hooks run in LIFO order on signal (SIGINT/SIGTERM) or explicit Stop(), each with its own timeout, errors are aggregated rather than swallowed.
Designed for plain `func main()` programs that don't use fx. fx-based services already get this for free via lifecycle hooks.
c := shutdown.New(shutdown.WithGraceWindow(30 * time.Second))
c.Register("http-server", server.Stop)
c.Register("db", db.Close)
if err := c.Run(ctx); err != nil {
log.Fatal(err)
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Coordinator ¶
type Coordinator struct {
// contains filtered or unexported fields
}
Coordinator manages a stack of shutdown hooks.
func New ¶
func New(opts ...Option) *Coordinator
New constructs a Coordinator with the supplied options.
func (*Coordinator) Register ¶
func (c *Coordinator) Register(name string, fn Hook)
Register adds a hook. Hooks run in LIFO order, so register cheap-to-stop things last (servers before databases, for example).
func (*Coordinator) Run ¶
func (c *Coordinator) Run(ctx context.Context) error
Run blocks until ctx is cancelled, a configured signal arrives, or Stop is called, then runs all registered hooks in LIFO order. Returns the joined error of any hooks that failed or timed out.
func (*Coordinator) Stop ¶
func (c *Coordinator) Stop()
Stop triggers shutdown explicitly. Safe to call multiple times — only the first call has effect.
type Hook ¶
Hook is invoked during shutdown. Implementations should respect ctx and return promptly when it's cancelled — the coordinator imposes per-hook timeouts.
type Option ¶
type Option func(*Coordinator)
func WithGraceWindow ¶
WithGraceWindow sets the overall grace budget. Hooks running past this are abandoned and Run returns with their timeout error. Default: 30s.
func WithHookTimeout ¶
WithHookTimeout sets the per-hook timeout. Default: 10s.
func WithLogger ¶
WithLogger wires a logging function called with shutdown lifecycle events. Defaults to a no-op.
func WithSignals ¶
WithSignals overrides the signal set that triggers shutdown. Default: SIGINT + SIGTERM.