lifecycle

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 11 Imported by: ? modules, 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 provides NornicDB's canonical process supervisor.

The package is deliberately a leaf in the import graph — it depends only on the Go standard library and golang.org/x/sync/errgroup. It never imports observability, storage, Cypher, Bolt, server, or any other NornicDB business package. This separation lets every current and future NornicDB binary (cmd/nornicdb/, planned cmd/metrics-doc-gen/, future CLI utilities) reuse the same supervision discipline without pulling in the OpenTelemetry SDK or Prometheus registry.

Architecture

A Component is anything that can be started and shut down. Run takes the parent context plus a forward-ordered slice of components and:

  1. Wraps the parent in signal.NotifyContext(SIGINT, SIGTERM) so any OS signal cleanly cancels the supervisor (replaces the legacy channel-leak-prone signal.Notify(chan)+<-chan idiom).
  2. Drives every Component.Start on a single golang.org/x/sync/errgroup, so the FIRST non-nil Start error cancels the whole group.
  3. After every Start has returned, drains components in REVERSE registration order (the OBS-08 contract — last to start, first to stop).
  4. Drives every Shutdown on a FRESH context.WithTimeout( context.Background(), ShutdownTimeout). This is the OBS-09 keystone: deriving from the cancelled errgroup ctx would return immediately and break the 30s flush budget.
  5. Returns errors.Join(runErr, shutdownErr) so callers see both the trigger and any cleanup failures.

Wiring contract

Callers register components in startup order. Reverse-order shutdown is the OBS-08 mechanism — components like the telemetry/metrics listener (started first) drain LAST so kubelet keeps scraping during graceful shutdown, while the application HTTP edge (started last) drains FIRST.

See ADR-0001 §2.8.1 (amendments A10a + A10c) for the architectural contract this package implements.

Index

Constants

View Source
const ShutdownTimeout = 30 * time.Second

ShutdownTimeout bounds the total drain budget across every component. Per ADR-0001 §2.8.1 / A10a this MUST be 30s — the OpenTelemetry batch span processor needs ~5s to flush, and the remaining headroom covers in-flight HTTP/Bolt requests.

Variables

This section is empty.

Functions

func AfterFuncJoined

func AfterFuncJoined(ctx context.Context, fn func()) (stop func())

AfterFuncJoined arranges fn to run once ctx is done, like context.AfterFunc, and returns a stop that settles it: stop either prevents fn from running or, when fn has already started, waits for it to return. After stop returns, fn is not running and never will be; repeated and concurrent stops join the same settlement. It is the one stop-callback-and-join mechanism for a callback whose resources its caller releases after stop.

func DrainReverse

func DrainReverse(ctx context.Context, components []Component) error

DrainReverse calls Shutdown on each component in REVERSE slice order (last → first), accumulating per-component errors with errors.Join.

One Shutdown returning a non-nil error does NOT abort the loop — every remaining component is still given a chance to flush. This is the OBS-08 mechanism: drain order is contractual, and a faulty component cannot strand the others.

The supplied ctx should be a FRESH context.WithTimeout( context.Background(), ShutdownTimeout) per OBS-09; DrainReverse itself does not enforce that — Run is the canonical caller and constructs the fresh ctx before invoking DrainReverse.

func Run

func Run(parent context.Context, components ...Component) error

Run supervises components until SIGINT/SIGTERM, parent ctx cancellation, or the first non-nil error from any Component.Start.

Forward order = startup order. Reverse order = drain order (the OBS-08 contract — encoded by the caller's slice order).

Run retains every actual Start completion and shutdown failure so callers observe sibling outcomes as well as the cancellation trigger. A clean exit returns nil.

Critical correctness properties enforced here:

  1. signal.NotifyContext (Go 1.16+) replaces the channel-leak-prone signal.Notify(chan, ...) + <-chan pattern. The deferred stop() releases the signal handler.
  2. errgroup.WithContext cancels gctx on the FIRST non-nil Start error. Components observe gctx and exit cleanly.
  3. The shutdown ctx is derived from context.Background(), NOT gctx. gctx is already cancelled by the time we reach the drain loop; deriving from it would return immediately and break the OBS-09 fresh-context guarantee.
  4. Components are drained in REVERSE slice order (OBS-08). DrainReverse continues past per-component Shutdown errors so a single faulty component cannot strand others.

Types

type Component

type Component interface {
	Name() string
	Start(ctx context.Context) error
	Shutdown(ctx context.Context) error
}

Component is anything the supervisor can start concurrently and shut down on demand.

Start blocks until the component exits naturally or ctx is cancelled. Returning a non-nil error from Start cancels the entire errgroup and triggers the reverse-order drain.

Shutdown is invoked once Start has returned for ALL components, in reverse registration order. The ctx passed to Shutdown has a fresh ~30s deadline whose lifetime is INDEPENDENT of the cancelled supervisor context (ADR-0001 §2.8.1 A10a / OBS-09). Implementations must honor the deadline but should NOT assume it is the same ctx that cancelled Start.

Name is used to tag wrapped errors and enable structured logging. It must be stable for the lifetime of the component.

type FakeComponent

type FakeComponent struct {

	// OnStart, when non-nil, replaces the default Start behavior
	// (which blocks on <-ctx.Done() and returns nil).
	OnStart func(ctx context.Context) error

	// OnShutdown, when non-nil, replaces the default Shutdown behavior
	// (which returns nil immediately).
	OnShutdown func(ctx context.Context) error
	// contains filtered or unexported fields
}

FakeComponent is a deterministic test fixture implementing Component. It records start/shutdown call counts and monotonic timestamps so tests can assert ordering invariants (e.g. reverse-drain order).

FakeComponent lives in production source rather than _test.go so that downstream packages — pkg/observability adapters in Plan 01-03, integration tests in Plan 01-04 — can reuse it without duplicating the fixture. This mirrors the colocated `MemoryEngine` pattern in pkg/storage/memory.go.

All counters/timestamps are atomic; the struct is safe for concurrent use across the supervisor's errgroup goroutines.

func NewFakeComponent

func NewFakeComponent(name string) *FakeComponent

NewFakeComponent returns a fresh FakeComponent with the given name. Override OnStart / OnShutdown on the returned pointer to inject test behavior.

func (*FakeComponent) Name

func (f *FakeComponent) Name() string

Name implements Component.

func (*FakeComponent) Shutdown

func (f *FakeComponent) Shutdown(ctx context.Context) error

Shutdown records the invocation timestamp + count, then either calls the caller-supplied OnShutdown override or returns nil.

Order matters: shutdownAt + shutdownSeq are stamped BEFORE shutdownCount is incremented (same reasoning as Start above).

func (*FakeComponent) ShutdownAtNanos

func (f *FakeComponent) ShutdownAtNanos() int64

ShutdownAtNanos returns the UnixNano timestamp of the first Shutdown invocation, or 0 if Shutdown has not yet been called.

func (*FakeComponent) ShutdownBefore

func (f *FakeComponent) ShutdownBefore(other *FakeComponent) bool

ShutdownBefore reports whether this component's Shutdown was entered strictly before other's. Uses a monotonic process-wide sequence counter to remain deterministic when consecutive Shutdowns land within the same wall-clock nanosecond (e.g. the supervisor's tight reverse-drain loop). Returns false if either component has not recorded a Shutdown.

func (*FakeComponent) ShutdownCount

func (f *FakeComponent) ShutdownCount() int32

ShutdownCount returns how many times Shutdown has been entered.

func (*FakeComponent) Start

func (f *FakeComponent) Start(ctx context.Context) error

Start records the invocation timestamp + count, then either calls the caller-supplied OnStart override or blocks on ctx.

Order matters: startedAt + startSeq are stamped BEFORE startCount is incremented, so any reader polling Eventually(StartCount()==1) and then reading StartedAtNanos()/startSeq is guaranteed to observe the stamped values. Inverting the order causes a 40%-repro race under -count=10.

func (*FakeComponent) StartCount

func (f *FakeComponent) StartCount() int32

StartCount returns how many times Start has been entered.

func (*FakeComponent) StartedAtNanos

func (f *FakeComponent) StartedAtNanos() int64

StartedAtNanos returns the UnixNano timestamp of the first Start invocation, or 0 if Start has not yet been called.

func (*FakeComponent) StartedBefore

func (f *FakeComponent) StartedBefore(other *FakeComponent) bool

StartedBefore reports whether this component's Start was entered strictly before other's. Uses a monotonic process-wide sequence counter to remain deterministic when consecutive Starts land within the same wall-clock nanosecond. Returns false if either component has not recorded a Start.

type OnceCompletion

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

OnceCompletion publishes one native operation's completion. It caches one result; the enclosing lifetime still owns attribution and sibling aggregation. The publication fence never spans the operation or a caller's wait.

func (*OnceCompletion) Do

func (c *OnceCompletion) Do(operation func() error) error

Do executes the winning operation in its caller's retained frame and joins that same completion for every later caller.

func (*OnceCompletion) DoContext

func (c *OnceCompletion) DoContext(ctx context.Context, operation func() error) error

DoContext dispatches the winning operation under its completion future. ctx bounds only this caller's wait; operation must supply its own live disposal context. Later calls observe the same eventual result, without repeating work.

func (*OnceCompletion) Done

func (c *OnceCompletion) Done() <-chan struct{}

Done closes when the operation has actually completed, including one not yet dispatched when Done is called.

func (*OnceCompletion) Err

func (c *OnceCompletion) Err() error

Err is the operation's result once Done has closed, and nil before.

func (*OnceCompletion) Go

func (c *OnceCompletion) Go(operation func() error) <-chan struct{}

Go dispatches the winning operation without waiting and returns the channel that closes on its actual completion. Later calls repeat no work.

func (*OnceCompletion) Run

func (c *OnceCompletion) Run(operation func())

Run joins a void native callback through the same completion owner. The callback runs outside the publication fence; its normal outcomes remain with its enclosing owner. A previously panicking callback cannot appear successful to a later joiner.

type Outcomes

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

Outcomes retains the completion outcomes of an owner's work, graceful and forced, with attribution. The zero value is ready to use. WorkLifetime embeds it; owners that only aggregate sibling results use it directly.

func (*Outcomes) Err

func (o *Outcomes) Err() error

Err returns the outcomes recorded so far. Composition calls the errors' own Is/Unwrap methods, which may be extension code, so it runs outside mu.

func (*Outcomes) Record

func (o *Outcomes) Record(operation string, err error)

Record keeps err, prefixed with operation when given. Attribution is formatted before taking the publication lock: an extension's Error method may itself call back into its host.

type OwnedTimer

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

OwnedTimer retains an accepted callback until Stop prevents it from starting or until its actual return. A failed Stop never reports completion.

func AfterFuncOwned

func AfterFuncOwned(ctx context.Context, arm func(time.Duration, func()) *time.Timer, delay time.Duration, retain func() (func(), bool), fn func()) *OwnedTimer

AfterFuncOwned acquires the caller's existing lifetime before arming. It stops when that lifetime ends; it has no registry or cancellation source. arm creates the native timer (time.AfterFunc, or an owner's injected clock).

func (*OwnedTimer) Stop

func (t *OwnedTimer) Stop() bool

type WorkLifetime

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

WorkLifetime is the admission and actual-completion owner shared by HTTP services. A caller deadline never discharges accepted work. The zero value is ready to use; close admission, signal cancellation, then join Quiescent.

func NewWorkLifetime

func NewWorkLifetime(parent context.Context) *WorkLifetime

NewWorkLifetime creates the same admission/completion owner with one parent- bound cancellation source. The zero value keeps its process-root behavior.

func (*WorkLifetime) Acquire

func (w *WorkLifetime) Acquire(ctx context.Context) (context.Context, func(), bool)

Acquire enrolls before launch and returns its actual-completion release.

func (*WorkLifetime) Active

func (w *WorkLifetime) Active() int

Active reports how many admitted units have not yet returned. It is an observation for diagnostics and tests; admission and completion decisions use Acquire, Enter and Quiescent.

func (*WorkLifetime) BeginStop

func (w *WorkLifetime) BeginStop(dispose func() error) <-chan struct{}

BeginStop starts Shutdown's one stop protocol without waiting for it: a supervisor signals every sibling before joining any of them. The returned channel closes after dispose; WaitStopped reports the outcomes.

func (*WorkLifetime) Cancel

func (w *WorkLifetime) Cancel()

Cancel signals accepted work; it does not declare it completed.

func (*WorkLifetime) Close

func (w *WorkLifetime) Close() error

Close seals admission, signals stop and joins actual completion. An active worker must return its ticket before its caller joins this same lifetime.

func (*WorkLifetime) CloseAdmission

func (w *WorkLifetime) CloseAdmission() bool

CloseAdmission seals roots. An active parent can still enroll its real child. It reports whether this call closed admission, so one caller owns the stop.

func (*WorkLifetime) CloseContext

func (w *WorkLifetime) CloseContext(ctx context.Context) error

CloseContext bounds only the caller's wait. Accepted work retains its ticket and reports its outcome until actual completion, also after this returns.

func (*WorkLifetime) Closing

func (w *WorkLifetime) Closing() bool

Closing reports whether admission has been closed.

func (*WorkLifetime) Context

func (w *WorkLifetime) Context() context.Context

Context is canceled by Cancel after admission is closed.

func (*WorkLifetime) Enter

func (w *WorkLifetime) Enter() bool

Enter admits one unit of root work that has no context and no children, without allocating: a storage helper or a reserved notification. The same admission and quiescence as Acquire; the caller calls Leave exactly once.

func (*WorkLifetime) Err

func (w *WorkLifetime) Err() error

Err returns the outcomes collected so far; WaitClosed returns the final set.

func (*WorkLifetime) Handler

func (w *WorkLifetime) Handler(next http.Handler) http.Handler

Handler owns the real request through outer buffered response publication.

func (*WorkLifetime) JoinStopped

func (w *WorkLifetime) JoinStopped() error

JoinStopped waits without a caller deadline for the owner's actual retirement and returns its retained outcomes. It does not initiate shutdown: call BeginStop first, or join a stop another owner has already initiated. Unlike WaitStopped, no canceled work context can shorten this completion join. A supervisor can BeginStop all siblings before JoinStopped on each of them.

func (*WorkLifetime) Leave

func (w *WorkLifetime) Leave()

Leave returns a unit admitted by Enter. A Leave without its Enter is a broken accounting invariant and panics rather than releasing others' work.

func (*WorkLifetime) OnRequestComplete

func (w *WorkLifetime) OnRequestComplete(ctx context.Context, complete func()) error

OnRequestComplete transfers a resource share to the outer response publisher of a request this lifetime admitted; an already-finished request runs complete immediately. The callback always runs outside host state locks.

func (*WorkLifetime) OnStop

func (w *WorkLifetime) OnStop(signal func() error) bool

OnStop enrolls a stop signal, such as closing a listener or a transport so that blocked work can return. It runs once when the lifetime is cancelled, outside any owner lock; its outcome is recorded, and quiescence (so also Shutdown's dispose) waits for it. It reports false once admission is closed.

func (*WorkLifetime) Quiescent

func (w *WorkLifetime) Quiescent() <-chan struct{}

Quiescent closes only after admission is closed and actual users return.

func (*WorkLifetime) RecordError

func (w *WorkLifetime) RecordError(operation string, err error)

RecordError retains an accepted lifetime's completion outcome.

func (*WorkLifetime) RetainHandler

func (w *WorkLifetime) RetainHandler(next http.Handler, r *http.Request) http.Handler

RetainHandler enrolls TimeoutHandler's child before its goroutine can run, preserving the worker's own cancellation/deadline when it eventually starts. A request this lifetime has not admitted is enrolled as its own request.

func (*WorkLifetime) Shutdown

func (w *WorkLifetime) Shutdown(ctx context.Context, dispose func() error) error

Shutdown is the one stop protocol. The first caller seals admission and signals cancellation; the owner waits for every accepted unit of work to actually return, then runs dispose exactly once. Every caller, first, repeated or concurrent, joins that same completion and receives the same outcomes. ctx bounds only this caller's wait, never the work or the dispose. dispose is reachable only here, after quiescence; later callers' dispose arguments are not run.

func (*WorkLifetime) Stopped

func (w *WorkLifetime) Stopped() <-chan struct{}

Stopped closes when Shutdown has disposed after quiescence.

func (*WorkLifetime) WaitClosed

func (w *WorkLifetime) WaitClosed(ctx context.Context) error

WaitClosed joins a lifetime whose admission has already been closed.

func (*WorkLifetime) WaitStopped

func (w *WorkLifetime) WaitStopped(ctx context.Context) error

WaitStopped joins the stop without starting it. ctx bounds only the wait.

Jump to

Keyboard shortcuts

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