lifecycle

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package lifecycle owns main: Run sets up logging, tracing and metrics from the identity, writes process.start, runs the app's function and takes every exit through one stop sequence (contract.md section 9.1). The causes are the function returning, SIGINT, SIGTERM or SIGHUP, Stop, a panic in the function or in a goroutine started with Go, and a Go goroutine returning an error. The sequence cancels ctx, waits for the Go goroutines, runs the OnStop steps in reverse order, waits for the function, writes process.stop or process.crash, flushes spans and metrics and exits with the code of the failure table.

func main() {
	lifecycle.Run(identity.New("api"), serve, lifecycle.Grace(20*time.Second))
}

func serve(ctx context.Context, log *slog.Logger) error {
	db, err := sql.Open("postgres", os.Getenv("DB_URL"))
	if err != nil {
		return err
	}
	lifecycle.OnStop(ctx, "db", db.Close)
	srv := httpserver.New(log, routes(db), httpserver.Addr(":8080"))
	lifecycle.OnStop(ctx, "http", func() error { return srv.Shutdown(context.Background()) })
	lifecycle.Go(ctx, "consumer", func(ctx context.Context) error { return consumer.Run(ctx, db) })
	return srv.ListenAndServe(ctx)
}

Teardown is OnStop steps, not defers. os.Exit and log.Fatal inside the function skip the sequence; so does a panic in a goroutine started with plain go (section 6).

Run makes its logger the default of log/slog, so a line written through slog.Info or a library that logs through slog.Default is the contract's line. A service test runs fn through the same sequence in-process with lifecycletest.Run.

Example

The server of contract.md section 9.1: the database closes after the consumer, because Run waits for the Go goroutines before the steps; the http step drains the requests and makes serve return.

package main

import (
	"context"
	"database/sql"
	"log/slog"
	"net/http"
	"os"
	"time"

	"github.com/AndreiD108/d108-go/httpserver"
	"github.com/AndreiD108/d108-go/identity"
	"github.com/AndreiD108/d108-go/lifecycle"
)

// The server of contract.md section 9.1: the database closes after the consumer, because Run
// waits for the Go goroutines before the steps; the http step drains the requests and makes
// serve return.
func main() {
	lifecycle.Run(identity.New("api"), serve, lifecycle.Grace(20*time.Second))
}

func serve(ctx context.Context, log *slog.Logger) error {
	db, err := sql.Open("postgres", os.Getenv("DB_URL"))
	if err != nil {
		return err
	}
	lifecycle.OnStop(ctx, "db", db.Close)

	srv := httpserver.New(log, routes(db), httpserver.Addr(":8080"))
	lifecycle.OnStop(ctx, "http", func() error { return srv.Shutdown(context.Background()) })

	lifecycle.Go(ctx, "consumer", func(ctx context.Context) error { return consume(ctx, db) })

	return srv.ListenAndServe(ctx)
}

func routes(*sql.DB) http.Handler { return http.NewServeMux() }

func consume(ctx context.Context, _ *sql.DB) error {
	<-ctx.Done()
	return ctx.Err()
}

Index

Examples

Constants

View Source
const (
	ReasonDone   = run.ReasonDone
	ReasonError  = run.ReasonError
	ReasonSignal = run.ReasonSignal
	ReasonApp    = run.ReasonApp
	ReasonForced = run.ReasonForced
)

The reason values of process.stop.

View Source
const DefaultGrace = run.DefaultGrace

DefaultGrace is the time the stop sequence gets before Run forces the exit.

View Source
const HeartbeatInterval = 60 * time.Second

HeartbeatInterval is the time between two process.heartbeat lines.

Variables

This section is empty.

Functions

func Go

func Go(ctx context.Context, name string, fn func(ctx context.Context) error)

Go starts fn in a goroutine the stop sequence waits for. A panic in fn is recovered and written as process.crash; an error ends the process with reason error and the error's exit code; nil ends the goroutine quietly. A cancelled or terminated error after the stop started is quiet too. Once the steps began, fn does not start and a WARN line says so.

func OnStop

func OnStop(ctx context.Context, name string, fn func() error)

OnStop registers a named stop step. Steps run in reverse order of registration when the process stops, every one of them, each failure an ERROR line with the step's name. A step registered once the steps began (the Go goroutines had ended) does not run and is reported with a WARN line. ctx must come from Run (or lifecycletest.Run); another ctx panics.

func Run

func Run(id identity.Identity, fn Func, opts ...Option)

Run owns main. It builds the logger, refuses to start on a bad LOG_LEVEL or LOG_OUTPUT (the error envelope on stderr, exit 2), turns tracing and metrics on when the environment asks, writes process.start, runs fn and ends the process through the stop sequence. It never returns. A second call in the same process panics.

func Stop

func Stop(ctx context.Context)

Stop starts the stop sequence with reason app and exit code 0. Later calls do nothing.

Types

type Func

type Func func(ctx context.Context, log *slog.Logger) error

Func is the app's function: it returns when the app is done or when ctx is cancelled.

type Option

type Option func(*run.Options)

Option configures Run.

func Grace

func Grace(d time.Duration) Option

Grace sets how long the stop sequence may take before Run forces the exit (default DefaultGrace). 0 or less never forces; a second signal still does.

func Heartbeat

func Heartbeat(on bool) Option

Heartbeat turns the process.heartbeat line on or off (default on). Commands turn it off.

func Logging

func Logging(opts ...logging.Option) Option

Logging passes options to logging.New: KeepDays, MaxFileBytes and the rest.

func RedactFlags added in v0.2.0

func RedactFlags(names ...string) Option

RedactFlags names value-taking long flags, without the dashes, whose values process.start logs as "redacted": a flag that carries a pepper or a similar value. The app still reads the real value; such a flag has no short form.

Directories

Path Synopsis
internal
run
Package run is the state of one lifecycle run and its stop sequence, shared by lifecycle (the process owner) and lifecycletest (the in-process harness).
Package run is the state of one lifecycle run and its stop sequence, shared by lifecycle (the process owner) and lifecycletest (the in-process harness).
Package lifecycletest runs a lifecycle.Func through the real stop sequence inside a test, so a service test sees its OnStop steps, Go goroutines and Stop calls behave as they do under lifecycle.Run: ctx cancelled, the Go goroutines drained, the steps in reverse order, fn waited for, process.stop or process.crash as the last line.
Package lifecycletest runs a lifecycle.Func through the real stop sequence inside a test, so a service test sees its OnStop steps, Go goroutines and Stop calls behave as they do under lifecycle.Run: ctx cancelled, the Go goroutines drained, the steps in reverse order, fn waited for, process.stop or process.crash as the last line.

Jump to

Keyboard shortcuts

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