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 ¶
- Variables
- type Action
- type Coordinator
- func (c *Coordinator) Close(ctx context.Context) error
- func (c *Coordinator) EnterPhase(ctx context.Context, name string) (*Execution, error)
- func (c *Coordinator) ExitPhase(ctx context.Context, name string) (*Execution, error)
- func (c *Coordinator) RollbackPhase(ctx context.Context, name string) (*Execution, error)
- func (c *Coordinator) Snapshot() Snapshot
- type Engine
- type Execution
- type Options
- type Phase
- type PhaseSpec
- type PhaseState
- type PhaseStatus
- type Plan
- type RunStatus
- type Session
- type Snapshot
- type Store
- type Topology
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
ExitPhase waits until all dependent phases have durably completed exit. It returns ErrInvalidPhase unless every entry has durably succeeded.
func (*Coordinator) RollbackPhase ¶
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 ¶
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 ¶
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.
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 ¶
Phase is a named node of a Plan with its dependencies and the three actions that enter, exit and roll it back.
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 ¶
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.
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 ¶
NewTopology validates phases and returns a Topology. It applies the same graph rules as NewPlan.
Source Files
¶
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. |