lifecycle

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 10 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.

README

lifecycle

lifecycle is a restartable lifecycle engine for Go. You describe phases with dependencies and idempotent enter, exit and rollback actions; the library validates the graph, runs independent phases concurrently, persists every action boundary, and resumes an interrupted run without repeating completed work. It is for services that start and stop dependent resources in order, for workflows that must survive crashes, and for tools that need DAG validation. A separate handoff package moves state between owners through integrity-checked artifacts.

Features

  • DAG validation: duplicates, unknown or self dependencies and cycles are rejected up front; stable topological levels and a deterministic digest.
  • Automatic Engine: entry in dependency order, exit in reverse order, rollback of entered phases after an entry failure, bounded parallelism and no level barriers.
  • Caller-driven Coordinator that tells you when a phase may run and durably records the outcome.
  • Durable state: a snapshot is saved before and after every action through a fenced, exclusive Store/Session contract; crashed runs resume exactly.
  • Strict validation of loaded snapshots, including detection of plan changes.
  • Deterministic, errors.Is-friendly error reporting.
  • memory.Store, an in-memory reference store.
  • handoff.Protocol: generic export → send → receive → adopt with SHA-256 content identity checked at every boundary.

Installation

go get github.com/justusschock/lifecycle@latest

Requires Go 1.25 or newer. The only dependency outside the standard library is github.com/justusschock/concurrency.

Quick start

The package example from example_test.go as a program:

package main

import (
	"context"
	"fmt"

	lifecycle "github.com/justusschock/lifecycle"
	"github.com/justusschock/lifecycle/memory"
)

func main() {
	step := func(message string) lifecycle.Action {
		return func(context.Context) error {
			fmt.Println(message)
			return nil
		}
	}
	plan, err := lifecycle.NewPlan([]lifecycle.Phase{
		{Name: "storage", Enter: step("open storage"), Exit: step("close storage"), Rollback: step("discard storage")},
		{Name: "workers", DependsOn: []string{"storage"}, Enter: step("start workers"), Exit: step("stop workers"), Rollback: step("discard workers")},
		{Name: "http", DependsOn: []string{"workers"}, Enter: step("listen"), Exit: step("stop listening"), Rollback: step("discard listener")},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	engine, err := lifecycle.NewEngine(plan, memory.NewStore(), lifecycle.Options{MaxParallel: 2})
	if err != nil {
		fmt.Println(err)
		return
	}
	snapshot, err := engine.Run(context.Background(), "server-1")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(snapshot.Status)
}

Output:

open storage
start workers
listen
stop listening
stop workers
close storage
succeeded

Packages

Package Purpose
github.com/justusschock/lifecycle Plans, topologies, Engine, Coordinator, snapshots, the Store/Session contract and sentinel errors.
github.com/justusschock/lifecycle/memory In-memory Store for tests and process-local workflows.
github.com/justusschock/lifecycle/handoff Integrity-checked artifacts and the generic transfer protocol.

Packages under internal/ are not part of the API and may change in any release.

Usage

Plans and topologies

A Phase has a unique name, zero or more dependencies and three idempotent actions (Enter, Exit, Rollback). NewPlan rejects empty names, duplicate phases, unknown, duplicate or self dependencies, nil actions and cycles. Input order does not matter: the plan computes stable topological levels and sorts phase names lexically within each level, so multiple roots, forks and joins need no special API. The plan owns copies of all dependency slices, and Levels returns fresh copies.

NewTopology applies the same rules to callback-free PhaseSpec values. Use it to validate a graph for your own scheduler, or with a Coordinator.

Digest is a deterministic SHA-256 digest of the phase names and sorted dependencies. Persisted runs record it to detect a changed plan. Actions are not part of the digest: if an action change is incompatible with existing snapshots, encode a version in the phase name or migrate the snapshots.

Running a lifecycle with Engine

Engine.Run performs a complete lifecycle for one run ID:

  1. Admit lexically sorted phases whose dependencies have durably entered.
  2. Start a dependent as soon as its own dependencies finish, without waiting for unrelated phases in the same level.
  3. After every entry succeeded, exit each phase once all of its dependents have durably finished exiting (successfully or not).
  4. If an entry fails, durably move the run to rolling_back, cancel running peers with the failure as cause, admit no new entries, and roll back the successfully entered phases in reverse dependency order.

At most Options.MaxParallel actions run at once; zero means 1 and negative values are rejected. Exit and rollback are best-effort: a failed cleanup action is recorded with a stage-specific status and does not stop cleanup of other phases. The run becomes failed once all cleanup has resolved. An exit failure does not trigger rollback.

Driving phases yourself with Coordinator

A Coordinator owns the fenced session and durable state of one run. EnterPhase blocks until dependencies have durably entered and capacity is available. The returned Execution reports through ShouldRun whether the work still has to be done, exposes a cancellation-aware Context, and must be finished with Complete:

topology, err := lifecycle.NewTopology([]lifecycle.PhaseSpec{
	{Name: "prepare"},
	{Name: "publish", DependsOn: []string{"prepare"}},
})
if err != nil {
	return err
}
coordinator, err := lifecycle.OpenCoordinator(ctx, topology, store, "deployment-42", lifecycle.Options{})
if err != nil {
	return err
}
defer coordinator.Close(context.WithoutCancel(ctx))

execution, err := coordinator.EnterPhase(ctx, "prepare")
if err != nil {
	return err
}
if execution.ShouldRun() {
	if err := execution.Complete(ctx, prepare(execution.Context())); err != nil {
		return err
	}
}

Direct users own the traversal: after all entries succeed, call ExitPhase in reverse dependency order; after an entry failure, retry any durable entering work and call RollbackPhase in reverse dependency order. ExitPhase is unavailable until every entry has resolved, which keeps every persisted snapshot recoverable.

Persistence and recovery

The engine saves a snapshot before every action (in-progress status, incremented Attempts) and after it (completed or stage-specific failure). The in-memory state advances only after Save succeeds: if the pre-action save fails, the action is not called; if a later save fails, the durable state stays restartable and Run returns the last durably saved snapshot with the error.

Actions must be idempotent: a process can crash after an action's side effects but before its completion is durable, so an in-progress action is retried when the run resumes. Completed actions are never repeated.

Durable phase status Recovery behaviour
pending Run Enter when all dependencies are durably entered.
entering Retry Enter.
entered Skip Enter; later run Exit, or Rollback after an entry failure.
enter_failed Preserve the entry failure while outstanding rollback completes.
exiting Retry Exit.
exited Skip Enter and Exit.
exit_failed Preserve the exit failure and continue cleanup toward dependencies.
rolling_back Retry Rollback.
rolled_back Skip Rollback.
rollback_failed Preserve the rollback failure and continue cleanup toward dependencies.

Each status has a PhaseStatus constant, from PhasePending to PhaseRollbackFailed. PhaseFailed is a deprecated alias of PhaseEnterFailed kept for compatibility; new code should use PhaseEnterFailed.

A recovered run in rolling_back retries every durable entering phase before rollback begins. Loaded snapshots are validated before any action runs: run ID, plan digest, exact phase set, statuses, attempt counts, error text, reachable run state and dependency ordering. A plan mismatch returns ErrPlanChanged joined with ErrInvalidSnapshot; a terminal run (succeeded, rolled_back, failed) returns ErrRunTerminal.

Each PhaseState records Status, Attempts (actions started across entry, exit and rollback), LastError (text of the last persisted action error) and UpdatedAt (time of the last transition, from Options.Clock, or time.Now when it is nil).

Store contract
type Store interface {
	Acquire(ctx context.Context, runID string) (lifecycle.Session, error)
}

type Session interface {
	RunID() string
	Load(context.Context) (lifecycle.Snapshot, error)
	Save(context.Context, lifecycle.Snapshot) error
	Release(context.Context) error
}

Acquire establishes one exclusive owner for the run across every process using the backend and returns ErrRunOwned while another owner is active. Each session carries a fencing generation: once released or superseded, its operations, especially Save, fail with ErrOwnershipLost. Load returns ErrSnapshotNotFound for a new run. Save atomically replaces the whole snapshot, acknowledges only once it is recoverable, and must not retain the caller's map. The engine releases with a context that is independent of the cancellation of Run, so cancelling an action does not strand ownership.

The fence protects snapshot writes, not external side effects. Callbacks that change another system must carry that system's own fencing token.

memory.Store implements this contract in process: it clones snapshots at every boundary and fences stale sessions, and its zero value is ready to use. It is not durable and cannot coordinate separate processes; production backends need a lease or transaction and a durable fencing token. Store.Load and Store.Save are conveniences for inspecting and seeding a run that no session owns.

Errors
Error Meaning
ErrInvalidPhase A phase, option, run ID, plan, topology or store is invalid, or a stage operation is not available in the run's state.
ErrDuplicatePhase More than one phase uses the same name.
ErrUnknownDependency A dependency name is not in the plan.
ErrDependencyFailed A phase cannot enter because a dependency failed entry; joined with that failure.
ErrCycle The graph contains a cycle or self-dependency.
ErrSnapshotNotFound The store has no snapshot for the run.
ErrInvalidSnapshot A loaded or saved snapshot violates the lifecycle state contract.
ErrPlanChanged A snapshot's digest differs from the plan; also matches ErrInvalidSnapshot.
ErrRunTerminal The run has already reached a terminal state.
ErrRunOwned Another session owns the run.
ErrOwnershipLost A released or superseded session, or a closed Coordinator, was used.
ErrInvalidArtifact A handoff artifact, receipt or collaborator is structurally invalid.
ErrIntegrity Artifact data, digest, ID or receipt identity do not agree.
Handoff
type Exporter[S any] interface {
	Export(context.Context, S) (handoff.Artifact, error)
}

type Transport interface {
	Send(context.Context, handoff.Artifact) (handoff.Receipt, error)
	Receive(context.Context, handoff.Receipt) (handoff.Artifact, error)
}

type Adopter[D any] interface {
	Adopt(context.Context, handoff.Artifact) (D, error)
}

Protocol.Transfer runs Export → Send → Receive → Adopt. It validates the artifact after export and after receive, checks the receipt, and requires the exported, receipt and received artifact IDs to match. Adopt is never called after an integrity failure. Errors are wrapped with handoff export, handoff send, handoff receive or handoff adopt.

An artifact's Digest is SHA-256 over a canonical, length-prefixed envelope of media type, version, data and metadata sorted by key; ID is its hex encoding. NewArtifact, Clone and the protocol copy byte slices and maps at every boundary. Because artifact fields are exported, call Validate after modifying one.

artifact, err := handoff.NewArtifact("application/octet-stream", 1, []byte("state"),
	map[string]string{"schema": "example/v1"})
if err != nil {
	return err
}
if err := artifact.Validate(); err != nil {
	return err
}

Design and guarantees

  • Concurrency. Plan, Topology, Engine, Coordinator, Execution, memory.Store and handoff.Protocol (given safe collaborators) are safe for concurrent use. Store calls for one run are serialised. Two concurrent Run calls for the same run do not queue: one owns the run and the other gets ErrRunOwned.
  • Cancellation. Blocking calls honour their context and return its cause. Running actions receive a context that is cancelled with the cause of an entry failure, a persistence failure or Coordinator.Close.
  • Errors. Use errors.Is: errors are wrapped and joined. Joined errors are ordered by topological level, then by phase name. Live action errors keep their identity; errors recovered after a restart keep only their persisted text.
  • No logging, no global state. Results are reported through return values only.
  • Not provided: a workflow DSL, timers or schedules, a durable store, retries beyond restart recovery, inferred compensation, domain-specific states, artifact encryption or transport, or panic recovery for callbacks. Callers own action idempotency, store selection and retry policy.
  • Stability. The module is at v0.x: minor releases may break the API. Every break is listed in CHANGELOG.md.

Documentation

Contributing

Contributions are made through pull requests against main; nothing is pushed to main directly. Read AGENTS.md first: it covers the docs-first process, API rules, testing requirements and the checks to run before opening a pull request.

License

Licensed under the Apache License, Version 2.0. See LICENSE and NOTICE.

Documentation

Overview

Package lifecycle runs restartable lifecycles over directed acyclic graphs of phases.

A Phase has Enter, Exit and Rollback actions and named dependencies. NewPlan validates the graph; NewTopology validates the same graph without callbacks. An Engine drives a Plan to completion: it enters phases once their dependencies have entered, exits them in reverse dependency order, and rolls back entered phases when an entry fails. A Coordinator exposes the same durable state machine to callers that run the actions themselves.

Every action boundary is persisted through a fenced Session from a Store before and after the action runs, so an interrupted run resumes without repeating completed actions. Actions must therefore be idempotent. Package memory provides a process-local Store and package handoff a generic, integrity-checked state transfer protocol.

Example

Example starts three dependent phases in order and stops them in reverse.

package main

import (
	"context"
	"fmt"

	lifecycle "github.com/justusschock/lifecycle"
	"github.com/justusschock/lifecycle/memory"
)

func main() {
	step := func(message string) lifecycle.Action {
		return func(context.Context) error {
			fmt.Println(message)
			return nil
		}
	}
	plan, err := lifecycle.NewPlan([]lifecycle.Phase{
		{Name: "storage", Enter: step("open storage"), Exit: step("close storage"), Rollback: step("discard storage")},
		{Name: "workers", DependsOn: []string{"storage"}, Enter: step("start workers"), Exit: step("stop workers"), Rollback: step("discard workers")},
		{Name: "http", DependsOn: []string{"workers"}, Enter: step("listen"), Exit: step("stop listening"), Rollback: step("discard listener")},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	engine, err := lifecycle.NewEngine(plan, memory.NewStore(), lifecycle.Options{MaxParallel: 2})
	if err != nil {
		fmt.Println(err)
		return
	}
	snapshot, err := engine.Run(context.Background(), "server-1")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(snapshot.Status)
}
Output:
open storage
start workers
listen
stop listening
stop workers
close storage
succeeded

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidPhase reports an invalid phase, engine option, run ID, plan,
	// topology, store, or a stage operation that is not available in the
	// current run state.
	ErrInvalidPhase = errors.New("lifecycle: invalid phase")
	// ErrDuplicatePhase reports that more than one phase uses the same name.
	ErrDuplicatePhase = errors.New("lifecycle: duplicate phase")
	// ErrUnknownDependency reports a dependency name that is not in the plan.
	ErrUnknownDependency = errors.New("lifecycle: unknown dependency")
	// ErrDependencyFailed is joined with the original entry error when a
	// phase cannot enter because a transitive dependency failed entry.
	ErrDependencyFailed = errors.New("lifecycle: dependency failed")
	// ErrCycle reports a dependency cycle or a self-dependency.
	ErrCycle = errors.New("lifecycle: cycle")
	// ErrSnapshotNotFound is returned by Session.Load for a run without a
	// stored snapshot.
	ErrSnapshotNotFound = errors.New("lifecycle: snapshot not found")
	// ErrInvalidSnapshot reports a loaded or saved snapshot that violates the
	// lifecycle state contract.
	ErrInvalidSnapshot = errors.New("lifecycle: invalid snapshot")
	// ErrPlanChanged reports a snapshot whose plan digest differs from the
	// supplied plan or topology. It is always joined with ErrInvalidSnapshot.
	ErrPlanChanged = errors.New("lifecycle: plan changed")
	// ErrRunTerminal reports that the run already reached succeeded,
	// rolled_back or failed.
	ErrRunTerminal = errors.New("lifecycle: run is terminal")
	// ErrRunOwned is returned by Store.Acquire while another session owns
	// the run.
	ErrRunOwned = errors.New("lifecycle: run is already owned")
	// ErrOwnershipLost reports an operation through a released or superseded
	// session, or through a closed Coordinator.
	ErrOwnershipLost = errors.New("lifecycle: run ownership lost")
	// ErrInvalidArtifact reports a structurally invalid handoff artifact,
	// receipt or protocol collaborator.
	ErrInvalidArtifact = errors.New("lifecycle: invalid artifact")
	// ErrIntegrity reports a handoff artifact whose data, digest, ID or
	// receipt identity does not agree.
	ErrIntegrity = errors.New("lifecycle: integrity check failed")
)

Sentinel errors returned by the lifecycle, memory and handoff packages. Errors are frequently wrapped or joined; test for them with errors.Is.

Functions

This section is empty.

Types

type Action

type Action func(context.Context) error

Action is one idempotent phase callback. It may be retried after a crash and must honour cancellation of ctx.

type Coordinator

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

Coordinator owns one fenced, durable lifecycle run. Callers that run the actions themselves use it directly: EnterPhase, ExitPhase and RollbackPhase block until a phase is ready and capacity is available, and the returned Execution records the outcome. A Coordinator is safe for concurrent use. Close it to cancel outstanding executions and release ownership.

func OpenCoordinator

func OpenCoordinator(ctx context.Context, topology *Topology, store Store, runID string, options Options) (*Coordinator, error)

OpenCoordinator acquires exclusive ownership of runID and restores its durable lifecycle state.

func (*Coordinator) Close

func (c *Coordinator) Close(ctx context.Context) error

Close cancels active executions and releases fenced ownership.

func (*Coordinator) EnterPhase

func (c *Coordinator) EnterPhase(ctx context.Context, name string) (*Execution, error)

EnterPhase waits until phase dependencies are durably entered and execution capacity is available. It returns an Execution whose ShouldRun is false if the phase already entered, and an error joined with ErrDependencyFailed if a dependency failed entry. It returns the cause of ctx when ctx ends first.

Example
package main

import (
	"context"
	"fmt"

	lifecycle "github.com/justusschock/lifecycle"
	"github.com/justusschock/lifecycle/memory"
)

func main() {
	topology, _ := lifecycle.NewTopology([]lifecycle.PhaseSpec{
		{Name: "root"},
		{Name: "child", DependsOn: []string{"root"}},
	})
	coordinator, _ := lifecycle.OpenCoordinator(context.Background(), topology, memory.NewStore(), "example", lifecycle.Options{})
	defer func() { _ = coordinator.Close(context.Background()) }()

	childResult := make(chan *lifecycle.Execution, 1)
	go func() {
		execution, _ := coordinator.EnterPhase(context.Background(), "child")
		childResult <- execution
	}()
	root, _ := coordinator.EnterPhase(context.Background(), "root")
	_ = root.Complete(context.Background(), nil)
	child := <-childResult
	_ = child.Complete(context.Background(), nil)

	rootExit := make(chan *lifecycle.Execution, 1)
	go func() {
		execution, _ := coordinator.ExitPhase(context.Background(), "root")
		rootExit <- execution
	}()
	childExit, _ := coordinator.ExitPhase(context.Background(), "child")
	_ = childExit.Complete(context.Background(), nil)
	_ = (<-rootExit).Complete(context.Background(), nil)

	fmt.Println(coordinator.Snapshot().Status)
}
Output:
succeeded

func (*Coordinator) ExitPhase

func (c *Coordinator) ExitPhase(ctx context.Context, name string) (*Execution, error)

ExitPhase waits until all dependent phases have durably completed exit. It returns ErrInvalidPhase unless every entry has durably succeeded.

func (*Coordinator) RollbackPhase

func (c *Coordinator) RollbackPhase(ctx context.Context, name string) (*Execution, error)

RollbackPhase waits until all dependent phases have durably resolved rollback. It returns ErrInvalidPhase unless the run is rolling back.

func (*Coordinator) Snapshot

func (c *Coordinator) Snapshot() Snapshot

Snapshot returns an isolated copy of the current durable state.

type Engine

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

Engine automatically drives a callback-bearing Plan through a durable Coordinator. Coordinator owns all topology readiness and snapshot mutation. An Engine is immutable after construction and safe for concurrent use.

Example
package main

import (
	"context"
	"fmt"

	lifecycle "github.com/justusschock/lifecycle"
	"github.com/justusschock/lifecycle/memory"
)

func main() {
	noop := func(context.Context) error { return nil }
	plan, _ := lifecycle.NewPlan([]lifecycle.Phase{
		{Name: "prepare", Enter: noop, Exit: noop, Rollback: noop},
		{Name: "left", DependsOn: []string{"prepare"}, Enter: noop, Exit: noop, Rollback: noop},
		{Name: "right", DependsOn: []string{"prepare"}, Enter: noop, Exit: noop, Rollback: noop},
		{Name: "publish", DependsOn: []string{"left", "right"}, Enter: noop, Exit: noop, Rollback: noop},
	})
	engine, _ := lifecycle.NewEngine(plan, memory.NewStore(), lifecycle.Options{MaxParallel: 2})
	snapshot, _ := engine.Run(context.Background(), "example")
	fmt.Println(snapshot.Status)
}
Output:
succeeded

func NewEngine

func NewEngine(plan *Plan, store Store, options Options) (*Engine, error)

NewEngine returns an Engine for plan backed by store. It rejects nil or uninitialized plans, nil stores (including typed nils) and negative parallelism with ErrInvalidPhase.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, runID string) (result Snapshot, resultErr error)

Run executes the complete entry, exit, or rollback lifecycle for runID. It acquires the run from the store, resumes any persisted state, and releases ownership before returning. It returns the last durably saved snapshot together with the joined action and persistence errors; a run that is already terminal returns ErrRunTerminal. Run is safe to call concurrently; concurrent calls for the same run fail with ErrRunOwned.

type Execution

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

Execution is a durable admission to execute one lifecycle action. Its methods are safe for concurrent use; Complete is idempotent once it has persisted the outcome.

func (*Execution) Complete

func (e *Execution) Complete(ctx context.Context, actionErr error) error

Complete durably records the outcome of the admitted action.

func (*Execution) Context

func (e *Execution) Context() context.Context

Context is canceled when another lifecycle action prevents this execution from continuing.

func (*Execution) ShouldRun

func (e *Execution) ShouldRun() bool

ShouldRun reports whether the caller must execute the phase action.

type Options

type Options struct {
	// MaxParallel bounds the number of concurrently admitted actions. Zero
	// means 1; negative values are rejected with ErrInvalidPhase.
	MaxParallel int
	// Clock returns the time recorded in snapshot and phase UpdatedAt
	// fields. Nil means time.Now.
	Clock func() time.Time
}

Options configures an Engine or Coordinator.

type Phase

type Phase struct {
	Name      string
	DependsOn []string
	Enter     Action
	Exit      Action
	Rollback  Action
}

Phase is a named node of a Plan with its dependencies and the three actions that enter, exit and roll it back.

type PhaseSpec

type PhaseSpec struct {
	Name      string
	DependsOn []string
}

PhaseSpec names a phase and its dependencies without callbacks.

type PhaseState

type PhaseState struct {
	// Status is the durable state-machine position.
	Status PhaseStatus
	// Attempts counts actions started for the phase across entry, exit and
	// rollback.
	Attempts uint
	// LastError is the text of the most recently persisted action error.
	LastError string
	// UpdatedAt is the time of the last transition.
	UpdatedAt time.Time
}

PhaseState is the persisted state of one phase.

type PhaseStatus

type PhaseStatus string

PhaseStatus is the durable state-machine position of one phase.

const (
	// PhasePending: entry has not started.
	PhasePending PhaseStatus = "pending"
	// PhaseEntering: Enter started and is retried on recovery.
	PhaseEntering PhaseStatus = "entering"
	// PhaseEntered: Enter completed.
	PhaseEntered PhaseStatus = "entered"
	// PhaseExiting: Exit started and is retried on recovery.
	PhaseExiting PhaseStatus = "exiting"
	// PhaseExited: Exit completed.
	PhaseExited PhaseStatus = "exited"
	// PhaseRollingBack: Rollback started and is retried on recovery.
	PhaseRollingBack PhaseStatus = "rolling_back"
	// PhaseRolledBack: Rollback completed.
	PhaseRolledBack PhaseStatus = "rolled_back"
	// PhaseEnterFailed: Enter returned an error; the run rolls back.
	PhaseEnterFailed PhaseStatus = "enter_failed"
	// PhaseExitFailed: Exit returned an error; cleanup continues.
	PhaseExitFailed PhaseStatus = "exit_failed"
	// PhaseRollbackFailed: Rollback returned an error; cleanup continues.
	PhaseRollbackFailed PhaseStatus = "rollback_failed"

	// PhaseFailed is retained as an alias for entry failures.
	//
	// Deprecated: use PhaseEnterFailed.
	PhaseFailed = PhaseEnterFailed
)

type Plan

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

Plan is a validated, immutable lifecycle graph with callbacks. It is safe for concurrent use.

func NewPlan

func NewPlan(phases []Phase) (*Plan, error)

NewPlan validates phases and returns a Plan. It rejects empty names, nil actions, duplicate phases, unknown, duplicate or self dependencies, and cycles. The plan keeps its own copies of the dependency slices.

func (*Plan) Digest

func (p *Plan) Digest() string

Digest returns the SHA-256 topology digest of the plan's phase names and dependencies. Actions are not part of the digest.

func (*Plan) Levels

func (p *Plan) Levels() [][]Phase

Levels returns fresh copies of the phases grouped by topological level, sorted lexically within each level.

type RunStatus

type RunStatus string

RunStatus is the durable state of a whole run.

const (
	// RunPending: no phase has been admitted.
	RunPending RunStatus = "pending"
	// RunRunning: entry or exit is in progress.
	RunRunning RunStatus = "running"
	// RunSucceeded: every phase exited. Terminal.
	RunSucceeded RunStatus = "succeeded"
	// RunRollingBack: an entry failed and entered phases are rolled back.
	RunRollingBack RunStatus = "rolling_back"
	// RunRolledBack: rollback completed without cleanup failures. Terminal.
	RunRolledBack RunStatus = "rolled_back"
	// RunFailed: an exit or rollback action failed. Terminal.
	RunFailed RunStatus = "failed"
)

type Session

type Session interface {
	// RunID identifies the only run this session may load or save.
	RunID() string
	// Load returns the current durable state for RunID.
	Load(context.Context) (Snapshot, error)
	// Save durably replaces the state for RunID. Implementations must reject
	// writes from a released or superseded fence with ErrOwnershipLost.
	Save(context.Context, Snapshot) error
	// Release relinquishes ownership. Callers should use a context independent
	// of cancellation of the work performed while the session was active.
	Release(context.Context) error
}

Session is exclusive, fenced ownership of one run.

type Snapshot

type Snapshot struct {
	// RunID identifies the run.
	RunID string
	// PlanDigest is the Topology.Digest the run was started with.
	PlanDigest string
	// Status is the run state.
	Status RunStatus
	// Phases maps every phase name to its state.
	Phases map[string]PhaseState
	// UpdatedAt is the time of the last transition.
	UpdatedAt time.Time
}

Snapshot is the complete durable state of one run. Stores persist and return it as a value; implementations must not retain or mutate the caller's Phases map.

type Store

type Store interface {
	// Acquire establishes exclusive, fenced ownership of runID across every
	// process that can access the store. It returns ErrRunOwned while another
	// owner is active.
	Acquire(context.Context, string) (Session, error)
}

Store hands out exclusive, fenced sessions for runs. Implementations must be safe for concurrent use; package memory provides a process-local one.

type Topology

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

Topology is a validated, immutable, callback-free dependency graph. It is safe for concurrent use.

func NewTopology

func NewTopology(phases []PhaseSpec) (*Topology, error)

NewTopology validates phases and returns a Topology. It applies the same graph rules as NewPlan.

func (*Topology) Digest

func (t *Topology) Digest() string

Digest returns the SHA-256 digest of the canonical phase names and sorted dependency names. Persisted snapshots record it to detect plan changes.

func (*Topology) Levels

func (t *Topology) Levels() [][]PhaseSpec

Levels returns fresh copies of the phases grouped by topological level, sorted lexically within each level.

Directories

Path Synopsis
Package handoff transfers state between owners through integrity-checked artifacts.
Package handoff transfers state between owners through integrity-checked artifacts.
internal
nilcheck
Package nilcheck detects nil interface values, including interfaces that hold a typed nil pointer, map, slice, channel or function.
Package nilcheck detects nil interface values, including interfaces that hold a typed nil pointer, map, slice, channel or function.
Package memory provides an in-memory lifecycle.Store for tests and process-local workflows.
Package memory provides an in-memory lifecycle.Store for tests and process-local workflows.

Jump to

Keyboard shortcuts

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