Documentation
¶
Overview ¶
Package reconciliation converges desired state toward observed state.
A caller implements Adapter for its domain: Observe reads the current state, Plan returns a dependency graph of actions (Plan), Apply performs one action and returns the value needed to undo it, and Undo reverses it. Engine runs one reconciliation through an adapter: it validates the plan before mutating anything, applies actions in a deterministic order, verifies the result with a fresh observation, retries failures classified with Transient or Conflict according to a Policy, and rolls back completed reversible actions in dependency-safe reverse order when an attempt fails.
Manager schedules many reconciliations: one call per Key at a time, a bound on concurrently active keys, coalescing of equal generations, supersession of stale pending generations, delayed requeues and graceful shutdown. EventStream and WithStatusSink report progress without ever blocking reconciliation. Retry delays and delayed requeues use the standard library clock unless a Clock or ManagerClock is supplied with WithClock or WithManagerClock.
The handoff subpackage transfers pending work to a successor process.
Values of generic types (specifications, observations, actions and undo values) are owned shallowly; see the documentation of each type.
Index ¶
- Constants
- Variables
- func Conflict(err error) error
- func Permanent(err error) error
- func Transient(err error) error
- func ValidatePlan[A any](plan Plan[A]) error
- func WithStatusSink(ctx context.Context, sink StatusSink) context.Context
- type Action
- type ActionID
- type Adapter
- type Clock
- type CloneSpec
- type Condition
- type ConditionStatus
- type Decision
- type Desired
- type Engine
- type EngineOption
- type EventStream
- type Generation
- type Key
- type Manager
- type ManagerClock
- type ManagerOption
- type Pending
- type Plan
- type Policy
- type Reconciler
- type Result
- type StatusEvent
- type StatusPhase
- type StatusSink
- type Undo
Examples ¶
Constants ¶
const DefaultRollbackTimeout = 30 * time.Second
DefaultRollbackTimeout bounds best-effort cleanup when Policy does not set RollbackTimeout or AttemptTimeout.
Variables ¶
var ( // ErrNilAdapter identifies a nil or typed-nil engine adapter. ErrNilAdapter = errors.New("reconciliation: nil adapter") // ErrNilClock identifies a nil or typed-nil clock supplied through // WithClock or WithManagerClock, or a clock whose After returned a nil // channel. ErrNilClock = errors.New("reconciliation: nil clock") )
var ( // ErrNilReconciler identifies a nil or typed-nil Reconciler. ErrNilReconciler = errors.New("reconciliation: nil reconciler") // ErrNilCloneSpec identifies a missing specification clone function. ErrNilCloneSpec = errors.New("reconciliation: nil specification clone function") // ErrSuperseded identifies desired work replaced by a newer generation. ErrSuperseded = errors.New("reconciliation: superseded generation") )
var ( // ErrInvalidPlan is wrapped by every plan validation failure. ErrInvalidPlan = errors.New("reconciliation: invalid plan") // ErrInvalidActionID identifies an empty action or dependency ID. ErrInvalidActionID = errors.New("reconciliation: invalid action ID") // ErrDuplicateAction identifies two actions with the same ID. ErrDuplicateAction = errors.New("reconciliation: duplicate action") // ErrMissingDependency identifies an edge to an absent action. ErrMissingDependency = errors.New("reconciliation: missing dependency") // ErrDuplicateDependency identifies a repeated edge from one action. ErrDuplicateDependency = errors.New("reconciliation: duplicate dependency") // ErrPlanCycle identifies a dependency cycle. ErrPlanCycle = errors.New("reconciliation: plan cycle") )
var ( // ErrInvalidPolicy is wrapped by Policy validation failures. ErrInvalidPolicy = errors.New("reconciliation: invalid policy") // ErrPermanent marks errors wrapped with Permanent; they are never retried. ErrPermanent = errors.New("reconciliation: permanent error") // ErrTransient marks errors wrapped with Transient; they may be retried. ErrTransient = errors.New("reconciliation: transient error") // ErrConflict marks errors wrapped with Conflict; they may be retried. ErrConflict = errors.New("reconciliation: conflict error") )
var ( // ErrInvalidKey is wrapped by Key validation failures. ErrInvalidKey = errors.New("reconciliation: invalid key") // ErrInvalidGeneration is wrapped by Generation validation failures. ErrInvalidGeneration = errors.New("reconciliation: invalid generation") // ErrInvalidDesired is wrapped by Desired validation failures. ErrInvalidDesired = errors.New("reconciliation: invalid desired state") // ErrInvalidCondition is wrapped by Condition validation failures. ErrInvalidCondition = errors.New("reconciliation: invalid condition") // ErrInvalidResult is wrapped by Result validation failures. ErrInvalidResult = errors.New("reconciliation: invalid result") )
Functions ¶
func Conflict ¶
Conflict marks err as retryable because the observed state changed concurrently. The result matches both err and ErrConflict with errors.Is and has err's message. Conflict(nil) is nil.
func Permanent ¶
Permanent marks err as not retryable. The result matches both err and ErrPermanent with errors.Is and has err's message. Permanent(nil) is nil.
func Transient ¶
Transient marks err as retryable, for example a temporary outage. The result matches both err and ErrTransient with errors.Is and has err's message. Transient(nil) is nil.
func ValidatePlan ¶
ValidatePlan verifies that all action identifiers and dependencies describe a directed acyclic graph.
func WithStatusSink ¶
func WithStatusSink(ctx context.Context, sink StatusSink) context.Context
WithStatusSink carries sink through one reconciliation call. It does not mutate Engine configuration, so one Engine may serve calls with distinct sinks concurrently. A nil or typed-nil sink is a no-op.
Types ¶
type Action ¶
Action is one planned mutation. DependsOn identifies runtime prerequisites, not only apply-order hints: rollback retains the transitive dependencies of any completed action that cannot be undone. Value ownership is shallow.
func Ordered ¶
Ordered returns a deterministic topological order. Among actions whose dependencies are satisfied, the lexicographically smallest ID is selected.
Example ¶
FR-RECON-04, NFR-RECON-01
package main
import (
"fmt"
reconciliation "github.com/justusschock/reconciliation"
)
func main() {
plan := reconciliation.Plan[string]{Actions: []reconciliation.Action[string]{
{ID: "fetch", Value: "read current state"},
{ID: "configure", DependsOn: []reconciliation.ActionID{"fetch"}, Value: "apply configuration"},
{ID: "validate", DependsOn: []reconciliation.ActionID{"fetch"}, Value: "validate inputs"},
{ID: "publish", DependsOn: []reconciliation.ActionID{"configure", "validate"}, Value: "publish result"},
}}
ordered, err := reconciliation.Ordered(plan)
if err != nil {
panic(err)
}
for _, action := range ordered {
fmt.Println(action.ID)
}
}
Output: fetch configure validate publish
type Adapter ¶
type Adapter[S, O, A, U any] interface { Observe(context.Context, Key) (O, error) Plan(context.Context, Desired[S], O) (Plan[A], error) Apply(context.Context, Action[A]) (Undo[U], error) Undo(context.Context, Undo[U]) error }
Adapter observes a value, plans changes, applies actions, and undoes reversible actions. Apply and undo payloads are independently typed. An Apply error means that action did not complete and its returned Undo value is unusable; implementations must make a subsequent observation safe. Engine does not serialize calls: Adapter implementations shared by concurrent Reconcile calls must be concurrency-safe. Keyed serialization belongs to a Manager or another caller-owned admission layer.
type Clock ¶
Clock supplies retry deadlines. After must return a non-nil channel. Implementations must be safe for concurrent use by reconciliation calls. The default clock uses time.After, so tests may also run an Engine inside a testing/synctest bubble instead of supplying a Clock.
type CloneSpec ¶
type CloneSpec[S any] func(S) S
CloneSpec returns an independently owned specification. Manager requires a clone function because generic specifications may contain reference values.
type Condition ¶
type Condition struct {
Type string
Status ConditionStatus
Reason string
Message string
LastTransitionTime time.Time
}
Condition reports one generic aspect of reconciliation state.
type ConditionStatus ¶
type ConditionStatus string
ConditionStatus is the tri-state value of a condition.
const ( ConditionTrue ConditionStatus = "true" ConditionFalse ConditionStatus = "false" ConditionUnknown ConditionStatus = "unknown" )
Condition statuses.
type Desired ¶
type Desired[S any] struct { Key Key Generation Generation Spec S }
Desired holds a desired specification. Spec ownership is shallow.
type Engine ¶
type Engine[S, O, A, U any] struct { // contains filtered or unexported fields }
Engine executes validated action plans and rolls back completed reversible actions when an attempt fails. Engine does not serialize Reconcile calls; callers that share an Engine must satisfy the Adapter, Clock, and Jitter concurrency contracts and serialize calls by key when required.
func NewEngine ¶
func NewEngine[S, O, A, U any](adapter Adapter[S, O, A, U], policy Policy, options ...EngineOption) *Engine[S, O, A, U]
NewEngine constructs a one-shot reconciliation engine. The adapter, policy and clock are validated by every Reconcile call rather than here, so a misconfigured Engine reports the problem through Reconcile's error.
func (*Engine[S, O, A, U]) Reconcile ¶
func (engine *Engine[S, O, A, U]) Reconcile(ctx context.Context, desired Desired[S]) (result Result[O], reconcileErr error)
Reconcile observes, plans, validates, applies, and verifies one desired value. A retry always starts with a fresh observation and plan.
Example ¶
FR-RECON-05
package main
import (
"context"
"fmt"
"maps"
"slices"
"sync"
"time"
reconciliation "github.com/justusschock/reconciliation"
)
// settings is a toy environment whose observed state is a map of names to
// values. Apply returns the previous value so the engine can roll it back.
type settings struct {
mu sync.Mutex
current map[string]string
}
// set changes one setting; previous restores it.
type set struct{ Name, Value string }
type previous struct {
Name, Value string
Present bool
}
func (s *settings) Observe(context.Context, reconciliation.Key) (map[string]string, error) {
s.mu.Lock()
defer s.mu.Unlock()
return maps.Clone(s.current), nil
}
func (s *settings) Plan(_ context.Context, desired reconciliation.Desired[map[string]string], observed map[string]string) (reconciliation.Plan[set], error) {
var plan reconciliation.Plan[set]
for _, name := range slices.Sorted(maps.Keys(desired.Spec)) {
if value := desired.Spec[name]; observed[name] != value {
plan.Actions = append(plan.Actions, reconciliation.Action[set]{
ID: reconciliation.ActionID("set/" + name),
Value: set{Name: name, Value: value},
Reversible: true,
})
}
}
return plan, nil
}
func (s *settings) Apply(_ context.Context, action reconciliation.Action[set]) (reconciliation.Undo[previous], error) {
s.mu.Lock()
defer s.mu.Unlock()
value, present := s.current[action.Value.Name]
s.current[action.Value.Name] = action.Value.Value
return reconciliation.Undo[previous]{Value: previous{Name: action.Value.Name, Value: value, Present: present}}, nil
}
func (s *settings) Undo(_ context.Context, undo reconciliation.Undo[previous]) error {
s.mu.Lock()
defer s.mu.Unlock()
if undo.Value.Present {
s.current[undo.Value.Name] = undo.Value.Value
} else {
delete(s.current, undo.Value.Name)
}
return nil
}
func main() {
env := &settings{current: map[string]string{"replicas": "1"}}
engine := reconciliation.NewEngine(env, reconciliation.Policy{
MaxAttempts: 3,
BaseDelay: 100 * time.Millisecond,
MaxDelay: 2 * time.Second,
AttemptTimeout: 30 * time.Second,
RollbackTimeout: 15 * time.Second,
})
result, err := engine.Reconcile(context.Background(), reconciliation.Desired[map[string]string]{
Key: "service/api",
Generation: 1,
Spec: map[string]string{"image": "api:v2", "replicas": "3"},
})
if err != nil {
panic(err)
}
fmt.Println(result.Changed, result.Observed["image"], result.Observed["replicas"])
}
Output: true api:v2 3
type EngineOption ¶
type EngineOption func(*engineConfig)
EngineOption configures an Engine.
func WithClock ¶
func WithClock(clock Clock) EngineOption
WithClock replaces the clock used for retry delays. A nil or typed-nil clock makes every Reconcile call fail with ErrNilClock before the adapter is called. Nil options passed to NewEngine are ignored.
type EventStream ¶
type EventStream struct {
// contains filtered or unexported fields
}
EventStream broadcasts status through independently bounded subscriber streams. A slow subscriber loses events without delaying publishers and eventually receives a StatusDropped count after it resumes consumption.
func NewEventStream ¶
func NewEventStream(capacity int) (*EventStream, error)
NewEventStream constructs a stream with the per-subscriber queue capacity.
func (*EventStream) Close ¶
func (stream *EventStream) Close()
Close idempotently closes every subscriber stream. Concurrent Publish and Close calls are safe.
func (*EventStream) Publish ¶
func (stream *EventStream) Publish(event StatusEvent)
Publish offers event to every current subscriber without waiting for a subscriber to consume it. Publish after Close is a no-op.
func (*EventStream) Subscribe ¶
func (stream *EventStream) Subscribe() <-chan StatusEvent
Subscribe returns a new independently bounded event channel. The channel is closed when EventStream.Close is called.
type Generation ¶
type Generation uint64
Generation identifies a positive revision of desired state.
func (Generation) Validate ¶
func (generation Generation) Validate() error
Validate reports an error wrapping ErrInvalidGeneration if generation is zero.
type Manager ¶
type Manager[S, O any] struct { // contains filtered or unexported fields }
Manager serializes reconciliation by key and bounds concurrently active keys. Accepted work runs with a manager-owned context; Submit contexts govern admission only.
func NewManager ¶
func NewManager[S, O any]( reconciler Reconciler[S, O], limit int, cloneSpec CloneSpec[S], options ...ManagerOption, ) (*Manager[S, O], error)
NewManager constructs a keyed reconciliation manager. CloneSpec is required and is used both when accepting work and when returning Pending snapshots.
func (*Manager[S, O]) Close ¶
Close atomically stops admission and fails work that has not started. Active calls may finish normally until ctx expires. On expiry, their manager-owned context and futures fail with the shutdown cause.
func (*Manager[S, O]) Pending ¶
Pending returns key-sorted, independently cloned snapshots of work that has not started.
Example ¶
FR-RECON-12
package main
import (
"bytes"
"context"
"fmt"
"time"
reconciliation "github.com/justusschock/reconciliation"
)
func main() {
reconciler := &blockingReconciler{
started: make(chan struct{}),
release: make(chan struct{}),
}
manager, err := reconciliation.NewManager[[]byte, string](
reconciler,
1,
func(spec []byte) []byte { return bytes.Clone(spec) },
)
if err != nil {
panic(err)
}
active := manager.Submit(context.Background(), reconciliation.Desired[[]byte]{
Key: "active", Generation: 1, Spec: []byte("first"),
})
<-reconciler.started
queued := manager.Submit(context.Background(), reconciliation.Desired[[]byte]{
Key: "queued", Generation: 1, Spec: []byte("second"),
})
pending := manager.Pending()
fmt.Println(pending[0].Desired.Key, pending[0].RetryAt.IsZero())
close(reconciler.release)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if _, err := active.Await(ctx); err != nil {
panic(err)
}
if _, err := queued.Await(ctx); err != nil {
panic(err)
}
if err := manager.Close(ctx); err != nil {
panic(err)
}
}
type blockingReconciler struct {
started chan struct{}
release chan struct{}
}
func (reconciler *blockingReconciler) Reconcile(
ctx context.Context,
desired reconciliation.Desired[[]byte],
) (reconciliation.Result[string], error) {
if desired.Key == "active" {
close(reconciler.started)
select {
case <-ctx.Done():
return reconciliation.Result[string]{}, context.Cause(ctx)
case <-reconciler.release:
}
}
return reconciliation.Result[string]{
Key: desired.Key, Generation: desired.Generation, Observed: string(desired.Spec),
}, nil
}
Output: queued true
func (*Manager[S, O]) Submit ¶
func (manager *Manager[S, O]) Submit(ctx context.Context, desired Desired[S]) *concurrency.Future[Result[O]]
Submit validates and clones desired before acceptance. Invalid, closed, canceled, stale, and superseded submissions are represented by failed futures; Submit never returns a nil future. Coalesced futures own independent Conditions slices, while Result.Observed ownership remains deliberately shallow.
type ManagerClock ¶
ManagerClock supplies absolute time and retry deadlines. Now determines Pending.RetryAt for delayed requeues and After schedules them; After must return a non-nil channel. Implementations must be safe for concurrent use. The default clock uses time.Now and time.After.
type ManagerOption ¶
type ManagerOption func(*managerConfig)
ManagerOption configures a Manager.
func WithManagerClock ¶
func WithManagerClock(clock ManagerClock) ManagerOption
WithManagerClock replaces the clock used for delayed requeues. NewManager rejects a nil or typed-nil clock with ErrNilClock.
func WithManagerStatusSink ¶
func WithManagerStatusSink(sink StatusSink) ManagerOption
WithManagerStatusSink publishes queued work and carries sink into Reconciler calls. Engine reads the sink from that per-call context.
type Pending ¶
Pending describes accepted work that has not started. Desired.Spec is cloned for the caller. RetryAt is zero when the work is ready to run immediately.
type Plan ¶
Plan is a directed acyclic graph of actions. Action values are shallowly owned; functions in this package copy action and dependency slice storage.
type Policy ¶
type Policy struct {
MaxAttempts int
BaseDelay time.Duration
MaxDelay time.Duration
AttemptTimeout time.Duration
RollbackTimeout time.Duration
// Jitter may be called concurrently by Reconcile calls on the same Engine.
Jitter func(time.Duration) time.Duration
}
Policy bounds retry attempts, timeouts, and backoff. MaxAttempts counts the first attempt and must be positive. The delay after failed attempt n is BaseDelay doubled n-1 times, capped at MaxDelay, then passed through Jitter and clamped to [0, MaxDelay]. Zero AttemptTimeout means no per-attempt deadline; RollbackTimeout falls back to AttemptTimeout and then to DefaultRollbackTimeout. A Policy is a value and safe for concurrent use if Jitter is.
func (Policy) Decide ¶
Decide reports whether attempt (one-based) failing with err should be retried and after what delay. Only errors matching ErrTransient or ErrConflict are retried, and only while attempts remain; context cancellation and deadline errors and ErrPermanent always stop. An invalid policy never retries.
type Reconciler ¶
Reconciler reconciles one desired value. Implementations may be called concurrently for different keys, but Manager serializes calls for one key.
type Result ¶
type Result[O any] struct { Key Key Generation Generation Observed O Changed bool Conditions []Condition RequeueAfter time.Duration }
Result holds observed reconciliation output. Observed ownership is shallow. Changed reports whether a change made by the reconciliation remains in place. A positive RequeueAfter asks a Manager to run the same generation again after that delay.
type StatusEvent ¶
type StatusEvent struct {
Key Key
Generation Generation
Phase StatusPhase
Attempt int
ActionID ActionID
Err error
Dropped uint64
}
StatusEvent reports one reconciliation phase boundary. Dropped is positive only for a StatusDropped marker and counts events omitted for one subscriber.
type StatusPhase ¶
type StatusPhase string
StatusPhase identifies a resource-independent reconciliation phase.
const ( StatusQueued StatusPhase = "queued" StatusObserving StatusPhase = "observing" StatusPlanning StatusPhase = "planning" StatusApplying StatusPhase = "applying" StatusRetrying StatusPhase = "retrying" StatusRollingBack StatusPhase = "rolling-back" StatusSucceeded StatusPhase = "succeeded" StatusFailed StatusPhase = "failed" StatusDropped StatusPhase = "dropped" )
Status phases. StatusQueued is published by a Manager; StatusDropped is synthesized by EventStream; the others are published by Engine.
type StatusSink ¶
type StatusSink interface {
Publish(StatusEvent)
}
StatusSink receives reconciliation events. Publish implementations must not block reconciliation. EventStream provides a bounded non-blocking sink.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package handoff transfers pending reconciliation state through lifecycle artifacts.
|
Package handoff transfers pending reconciliation state through lifecycle artifacts. |
|
internal
|
|
|
conformance
Package conformance provides test adapters for this module's contract tests.
|
Package conformance provides test adapters for this module's contract tests. |