lifecycle

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

lifecycle

Process lifecycle for Dioad daemons: ordered start with rollback, staged stop with budgets, failure fan-in, readiness and drain.

app := lifecycle.New(
	lifecycle.WithDrainDelay(5*time.Second),
	lifecycle.WithStopStages(
		lifecycle.Stage{Names: []string{"api"}, Budget: 10 * time.Second},
		lifecycle.Stage{Names: []string{"worker"}},
	),
)
if err := app.Add("store", store); err != nil {
	return err
}
if err := app.Add("worker", worker); err != nil {
	return err
}
if err := app.Add("api", apiServer); err != nil {
	return err
}

// Report readiness wherever the platform looks for it, for example
// dioad/net's http.Server.AddHealthSource.
app.Readiness().AddCheck("store", store.Ping, lifecycle.WithCacheTTL(5*time.Second))

return app.Run(ctx) // returns when ctx is done or a service fails
Start In registration order. A failure stops the services that had started, in the same way Stop would, and is returned joined with any stop errors.
Stop In stages: the services of a stage stop concurrently, each stage optionally within a budget, all within one stop timeout. Without stages, in reverse registration order. Errors are joined.
Failure A service that implements Failed() <-chan error has its failure reported on App.Failed as a *ServiceError. Run stops at once on a failure, without draining.
Readiness Not ready until started, not ready once draining, and in between ready unless a named check fails. A check can be cached for a TTL, and can be Degraded: reported, but still ready. It is a health source for dioad/net's HTTP server, without importing it.
Drain When Run's context is done, readiness reports not ready and Run waits for the drain delay before it stops the services, so the load balancer stops first.

A Service is Start(ctx) error and Shutdown(ctx) error: the same method set as dioad/net's http.Server, so one is a Service with no adapter. Failed, Live and Ready are optional, found by interface assertion.

See the package documentation for the details, and the examples for runnable versions.

Documentation

Overview

Package lifecycle runs the services of a Dioad daemon: it starts them in order, rolling back on a failure; fans their failures into one channel; reports readiness; drains; and stops them in stages within a deadline.

A daemon registers each service with an App, then calls Run:

app := lifecycle.New(lifecycle.WithDrainDelay(5 * time.Second))
if err := app.Add("store", store); err != nil {
	return err
}
if err := app.Add("api", apiServer); err != nil {
	return err
}
return app.Run(ctx)

Services

A Service has Start and Shutdown. A service that can also fail after it has started implements Failer, and one that can report that it has stopped working implements Liveness. A service that implements Ready adds a check of that name to the App's Readiness. All three are discovered by interface assertion, so a service implements only what it has.

The method set matches the one dioad/net's http.Server has (Start, Shutdown, Failed and Live), so a *http.Server is a Service with no adapter. It is Shutdown, not Stop, for that reason. A service's name is given when it is registered, not by the service.

Starting

Start starts services in registration order. If one fails, the services that had already started are stopped, in the same way Stop would stop them, and Start returns the start error joined with any stop errors. A service whose Start fails is not stopped, so Start must clean up after itself.

Stopping

Stop stops services in stages. A stage is a set of services stopped concurrently, optionally within a budget; the stages run one after another, all within one overall deadline (WithStopTimeout). With no stages configured every service is its own stage, stopped in reverse registration order. A service that no stage names is stopped after the stages, in reverse registration order. Errors are combined with errors.Join.

A service's Shutdown must return when its context is done. The App cannot stop a Shutdown that ignores it.

Failure and drain

A failure of a service that implements Failer is reported on App.Failed, wrapped in a ServiceError. Run, on a failure, stops the services at once; when its context is done instead, it first drains: Readiness reports not ready, and Run waits for the drain delay (WithDrainDelay) so that a load balancer stops sending requests before the listeners close.

Readiness

Readiness is a health source: it has the Ready method that dioad/net's http.Server.AddHealthSource looks for, so it is reported by /health/ready without this package importing dioad/net. It is not ready until Start has returned (the start gate) and not ready once draining. In between it runs its named checks. A check can be cached for a time to live, and can report itself degraded, in which case the process stays ready and the check is reported.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrAlreadyStarted is returned by Start, and by Add, once the App has
	// been started.
	ErrAlreadyStarted = errors.New("lifecycle: app already started")
	// ErrStarting is the reason Readiness reports before the App has started.
	ErrStarting = errors.New("starting")
	// ErrDraining is the reason Readiness reports once the App is draining or
	// stopping.
	ErrDraining = errors.New("draining")
)

Functions

func Degraded

func Degraded(err error) error

Degraded marks err as a degradation: the check that returned it is reported by Readiness, but the process stays ready. It returns nil if err is nil.

Types

type App

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

App starts, watches and stops a set of services. See the package documentation.

Example

Services start in the order they are added. When one fails to start, the services that had already started are stopped, newest first, and Start returns the failure.

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/dioad/lifecycle"
)

// printer is a Service that prints what it is asked to do.
type printer struct {
	name     string
	startErr error
}

func (p printer) Start(context.Context) error {
	if p.startErr != nil {
		fmt.Println("start", p.name, "failed")

		return p.startErr
	}
	fmt.Println("start", p.name)

	return nil
}

func (p printer) Shutdown(context.Context) error {
	fmt.Println("stop", p.name)

	return nil
}

func main() {
	app := lifecycle.New()
	for _, service := range []printer{
		{name: "store"},
		{name: "queue"},
		{name: "api", startErr: errors.New("address in use")},
		{name: "metrics"},
	} {
		if err := app.Add(service.name, service); err != nil {
			fmt.Println(err)

			return
		}
	}

	fmt.Println("result:", app.Start(context.Background()))
}
Output:
start store
start queue
start api failed
stop queue
stop store
result: start api: address in use

func New

func New(opts ...Option) *App

New returns an App with no services.

func (*App) Add

func (a *App) Add(name string, service Service) error

Add registers a service under name. Services start in the order they are added. It returns an error for an empty or repeated name, a nil service, or once the App has been started.

func (*App) Drain

func (a *App) Drain(ctx context.Context)

Drain makes Readiness report not ready, then waits for the drain delay or for ctx to be done, so that traffic stops before the services do.

func (*App) Failed

func (a *App) Failed() <-chan error

Failed returns a channel that receives the failure of any service that implements Failer, as a *ServiceError, once Start has returned. It is nil before then, and never closes.

func (*App) Live

func (a *App) Live(ctx context.Context) error

Live returns nil while every started service that implements Liveness reports live, and otherwise the errors of those that do not, each naming its service.

func (*App) Readiness

func (a *App) Readiness() *Readiness

Readiness returns the App's readiness, for adding checks and for reporting as a health source.

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run starts the services and blocks until ctx is done or a service fails, then stops them. When ctx is done it drains first and returns nil if the stop was clean. When a service fails it stops at once, without draining, and returns the *ServiceError joined with any stop errors. The drain and the stop share one stop timeout, and neither is cut short by ctx being done.

func (*App) Start

func (a *App) Start(ctx context.Context) error

Start starts the services in the order they were added, then opens Readiness. If a service fails to start, the ones already started are stopped and Start returns the failure joined with any stop errors; the App cannot then be started again. An App can be started once.

func (*App) Stop

func (a *App) Stop(ctx context.Context) error

Stop stops the started services in stages, within the stop timeout and ctx's deadline, whichever is sooner, and returns the errors joined. It does not drain; see Drain. It does nothing for an App that was never started, that failed to start, or that has already stopped.

Example

Stop stops the services in stages. The api stops first, so that nothing is sending the worker work; the store, which no stage names, stops last.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/dioad/lifecycle"
)

// printer is a Service that prints what it is asked to do.
type printer struct {
	name     string
	startErr error
}

func (p printer) Start(context.Context) error {
	if p.startErr != nil {
		fmt.Println("start", p.name, "failed")

		return p.startErr
	}
	fmt.Println("start", p.name)

	return nil
}

func (p printer) Shutdown(context.Context) error {
	fmt.Println("stop", p.name)

	return nil
}

func main() {
	app := lifecycle.New(lifecycle.WithStopStages(
		lifecycle.Stage{Names: []string{"api"}, Budget: time.Second},
		lifecycle.Stage{Names: []string{"worker"}},
	))
	for _, name := range []string{"store", "worker", "api"} {
		if err := app.Add(name, printer{name: name}); err != nil {
			fmt.Println(err)

			return
		}
	}
	if err := app.Start(context.Background()); err != nil {
		fmt.Println(err)

		return
	}

	fmt.Println("result:", app.Stop(context.Background()))
}
Output:
start store
start worker
start api
stop api
stop worker
stop store
result: <nil>

type CheckFunc

type CheckFunc func(ctx context.Context) error

CheckFunc reports whether one thing a process depends on is working. It returns nil when it is, and an error saying why not when it is not. Wrap the error in Degraded to report a problem that does not stop the process taking traffic.

type CheckOption

type CheckOption func(*check)

CheckOption configures a check added with AddCheck.

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) CheckOption

WithCacheTTL caches the check's result for ttl, so that a health probe that arrives every second does not query a database every second. A result is not cached when the probe's context is done, since that says nothing about the thing checked. Without it every Ready runs the check.

type Failer

type Failer interface {
	Failed() <-chan error
}

Failer is implemented by a Service that can stop working after Start has returned. Failed returns a channel that receives, at most once, the error that ended the service. It need not close it.

type Liveness

type Liveness interface {
	Live(ctx context.Context) error
}

Liveness is implemented by a Service that can report that it has stopped working. Live returns nil while the service is working.

type Option

type Option func(*App)

Option configures an App.

func WithDrainDelay

func WithDrainDelay(d time.Duration) Option

WithDrainDelay sets how long Drain waits after reporting not ready, before the services are stopped. The default is no wait.

func WithStopStages

func WithStopStages(stages ...Stage) Option

WithStopStages sets the stages Stop stops services in. See the package documentation for what stops a service no stage names.

func WithStopTimeout

func WithStopTimeout(d time.Duration) Option

WithStopTimeout sets the deadline for draining and stopping together. The default is 30 seconds. Zero or less means no deadline other than the context given to Stop.

type Readiness

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

Readiness reports whether a process should be sent traffic. It is not ready until MarkStarted, not ready once BeginDrain, and in between ready unless a check fails.

It has the Ready method that dioad/net's http.Server.AddHealthSource looks for. The zero value is not usable; call NewReadiness.

Example

A process is not ready until it has started, stays ready while a check is degraded, is not ready when a check fails, and is not ready once it is draining, so that traffic stops before its listeners close.

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/dioad/lifecycle"
)

func main() {
	readiness := lifecycle.NewReadiness()
	var searchErr, dbErr error
	readiness.AddCheck("db", func(context.Context) error { return dbErr })
	readiness.AddCheck("search", func(context.Context) error { return lifecycle.Degraded(searchErr) })

	report := func(when string) {
		status, err := readiness.Ready(context.Background())
		fmt.Printf("%s: status=%v err=%v\n", when, status, err)
	}

	report("before start")
	readiness.MarkStarted()
	report("started")

	searchErr = errors.New("slow")
	report("search degraded")

	dbErr = errors.New("connection refused")
	report("db down")

	dbErr = nil
	readiness.BeginDrain()
	report("draining")
}
Output:
before start: status=<nil> err=starting
started: status=map[db:ok search:ok] err=<nil>
search degraded: status=map[db:ok search:degraded: slow] err=<nil>
db down: status=map[db:failed: connection refused search:degraded: slow] err=db: connection refused
draining: status=<nil> err=draining

func NewReadiness

func NewReadiness(opts ...ReadinessOption) *Readiness

NewReadiness returns a Readiness that is not ready until MarkStarted.

func (*Readiness) AddCheck

func (r *Readiness) AddCheck(name string, fn CheckFunc, opts ...CheckOption)

AddCheck adds a named check. Checks run in the order they were added.

func (*Readiness) BeginDrain

func (r *Readiness) BeginDrain()

BeginDrain makes Ready report not ready from now on, so that traffic stops before listeners close. App does this when it drains or stops.

func (*Readiness) MarkStarted

func (r *Readiness) MarkStarted()

MarkStarted opens the start gate: from now on Ready runs the checks. App does this when every service has started.

func (*Readiness) Ready

func (r *Readiness) Ready(ctx context.Context) (any, error)

Ready reports whether the process should be sent traffic. The first result is a status for each check, by name: "ok", "degraded: <reason>" or "failed: <reason>". The error is non-nil before MarkStarted (ErrStarting), after BeginDrain (ErrDraining), and when a check has failed; a degraded check does not make it non-nil.

type ReadinessOption

type ReadinessOption func(*Readiness)

ReadinessOption configures a Readiness.

func WithClock

func WithClock(now func() time.Time) ReadinessOption

WithClock sets the clock that check results are cached against. It is for tests.

type Service

type Service interface {
	// Start brings the service up and returns once it is serving. It must not
	// block for the life of the service.
	Start(ctx context.Context) error
	// Shutdown stops the service. It must return when ctx is done.
	Shutdown(ctx context.Context) error
}

Service is something an App starts and stops: an HTTP server, a worker, a publisher, a store.

type ServiceError

type ServiceError struct {
	// Service is the name the service was registered under.
	Service string
	// Err is the error the service reported.
	Err error
}

ServiceError is a failure of a service, as reported on App.Failed.

func (*ServiceError) Error

func (f *ServiceError) Error() string

Error implements error.

func (*ServiceError) Unwrap

func (f *ServiceError) Unwrap() error

Unwrap returns the error the service reported.

type Stage

type Stage struct {
	// Names are the names the services were registered under.
	Names []string
	// Budget, if positive, is how long the stage may take. A service that has
	// not returned by then has its Shutdown context cancelled, and the next
	// stage starts. It is inside the overall stop deadline.
	Budget time.Duration
}

Stage is a set of services that Stop stops concurrently.

Jump to

Keyboard shortcuts

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