reconciliation

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: 13 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

reconciliation

reconciliation is a Go library for converging desired state toward observed state. You describe your domain once, as an adapter that observes, plans, applies and undoes; the library handles the control loop around it: validated action graphs with a deterministic order, classified retries with bounded backoff, dependency-safe rollback, keyed scheduling of many reconciliations, non-blocking status reporting, and handoff of pending work to a successor process. It is for authors of controllers, operators and services that keep an external system in a desired state and do not want to re-implement these mechanics, and their edge cases, for every resource.

Features

  • Action DAGs. Plan[A] actions declare runtime dependencies; ValidatePlan and Ordered reject invalid graphs and produce a stable topological order, including branches that later converge.
  • One-shot engine. Engine[S, O, A, U] observes, plans, validates the whole plan before mutating, applies, and verifies with a fresh observation.
  • Classified retries. Errors wrapped with Transient or Conflict are retried with exponential, capped, optionally jittered backoff; Permanent, unclassified and context errors are not.
  • Dependency-safe rollback. Completed reversible actions are undone in reverse order, without removing anything a surviving action still needs, under a bounded cleanup deadline that caller cancellation cannot suppress.
  • Keyed manager. Manager[S, O] runs one call per key at a time, bounds concurrently active keys, coalesces equal generations, supersedes stale pending ones, honours delayed requeues and shuts down gracefully.
  • Pluggable time source. Retry delays and delayed requeues use the standard library clock unless you supply a Clock (WithClock) or a ManagerClock (WithManagerClock).
  • Status events. WithStatusSink and EventStream report every phase without letting a slow consumer block reconciliation.
  • Handoff. The handoff package exports and adopts pending desired state and absolute retry deadlines as integrity-checked lifecycle artifacts.

The module defines no domain resources, persistence, leader election, transport or daemon, and performs no logging.

Installation

go get github.com/justusschock/reconciliation@latest

Requires Go 1.25 or newer. Dependencies: the standard library, concurrency and lifecycle.

Quick start

Implement Adapter for your environment. Here the environment is a map of settings; Apply returns the previous value so the engine can undo it (from ExampleEngine_Reconcile):

type settings struct {
	mu      sync.Mutex
	current map[string]string
}

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
}

Then construct an engine and reconcile one generation:

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
Plans

Dependencies are runtime prerequisites. Branches can fan out and a later action can depend on every branch:

plan := reconciliation.Plan[string]{Actions: []reconciliation.Action[string]{
	{ID: "fetch", Value: "read current state"},
	{ID: "configure", DependsOn: []reconciliation.ActionID{"fetch"}},
	{ID: "validate", DependsOn: []reconciliation.ActionID{"fetch"}},
	{ID: "publish", DependsOn: []reconciliation.ActionID{"configure", "validate"}},
}}

ordered, err := reconciliation.Ordered(plan) // fetch, configure, validate, publish

Ordered rejects empty or duplicate IDs, missing or duplicate dependencies and cycles. Among ready actions it picks the lexicographically smallest ID, so equivalent plans produce the same order (ExampleOrdered).

Managing keyed work

Manager adds keyed serialization and a concurrency limit around any Reconciler, including an Engine. A clone function is mandatory because generic specifications may contain maps, slices or pointers:

manager, err := reconciliation.NewManager[Spec, Observed](
	engine,
	8,
	func(spec Spec) Spec { return spec.Clone() },
)
if err != nil {
	return err
}
defer manager.Close(ctx)

future := manager.Submit(ctx, reconciliation.Desired[Spec]{
	Key: "service/api", Generation: 7, Spec: desired,
})
result, err := future.Await(ctx)

The Submit context controls admission only; the manager owns accepted work until it completes or the manager shuts down. A newer generation supersedes older pending work for the same key (ErrSuperseded); equal generations coalesce. A successful result with RequeueAfter keeps the generation pending until an absolute deadline, visible as Pending.RetryAt in Manager.Pending() snapshots (ExampleManager_Pending). Close stops admission, fails pending work with concurrency.ErrClosed, lets active work finish until its context ends, then cancels it with one shutdown cause.

Clocks

By default the engine waits between retries with time.After, and the manager schedules requeues with time.Now and time.After. To run against another time source, for example a simulation or a manually advanced test clock, pass reconciliation.WithClock(clock) to NewEngine (a Clock has one method, After(time.Duration) <-chan time.Time) or reconciliation.WithManagerClock(clock) to NewManager (a ManagerClock adds Now() time.Time, which determines Pending.RetryAt). Clocks must be safe for concurrent use and After must return a non-nil channel; a nil clock or a nil channel is reported with ErrNilClock. Because the defaults are the standard library timers, code built on this library can also be tested with testing/synctest without supplying a clock.

Status

Carry a StatusSink through a call with WithStatusSink, or configure one on a manager with WithManagerStatusSink. EventStream (from NewEventStream) gives each subscriber an independent bounded queue; publishers never wait, and a lagging subscriber later receives a StatusDropped event with the number of omitted events.

Handoff

The handoff package transfers only desired state that has not started, with its absolute retry deadline. Convert Manager.Pending() to handoff.Pending, export with handoff.NewExporter, adopt with handoff.NewAdopter, and resubmit on the successor, honouring a future RetryAt (handoff.ExampleExporter). Artifacts use media type application/vnd.justusschock.reconciliation+json, schema version 1, canonical key order and UTC deadlines. A Codec encodes specifications: Marshal may reuse scratch storage, while Unmarshal must return an independently owned value (for example bytes.Clone(data)).

Packages

Package Description
github.com/justusschock/reconciliation Plans, engine, retry policy, manager and status events.
github.com/justusschock/reconciliation/handoff Export and adoption of pending work through lifecycle artifacts.

Packages under internal/ (currently internal/conformance, a function-field Adapter used for testing) are not part of the API.

Design and guarantees

  • Concurrency. Engine does not serialize calls; adapters, clocks and Policy.Jitter shared by concurrent calls must be safe for concurrent use. Manager and EventStream are safe for concurrent use. The test suite runs under the race detector.
  • Cancellation. Every blocking operation takes a context.Context and reports context.Cause. Rollback deliberately outlives caller cancellation, bounded by RollbackTimeout.
  • Errors. Failure categories are sentinels (ErrInvalidPlan, ErrInvalidPolicy, ErrSuperseded, …) matched with errors.Is. A failed rollback is joined to the primary error and stops retries. Messages may contain keys and action IDs but never specifications or undo values.
  • Ownership. Specifications, observations, actions and undo values are shallow; the manager clones specifications with your CloneSpec, and the library copies the slices it owns.
  • Stability. The module is v0.x: a minor release may break the API. Every break is listed in the changelog and backed by an ADR.

Documentation

Contributing

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

License

Apache License 2.0. See LICENSE and NOTICE.

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

Examples

Constants

View Source
const DefaultRollbackTimeout = 30 * time.Second

DefaultRollbackTimeout bounds best-effort cleanup when Policy does not set RollbackTimeout or AttemptTimeout.

Variables

View Source
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")
)
View Source
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")
)
View Source
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")
)
View Source
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")
)
View Source
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

func Conflict(err error) error

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

func Permanent(err error) error

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

func Transient(err error) error

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

func ValidatePlan[A any](plan Plan[A]) error

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

type Action[A any] struct {
	ID         ActionID
	DependsOn  []ActionID
	Value      A
	Reversible bool
}

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

func Ordered[A any](plan Plan[A]) ([]Action[A], error)

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 ActionID

type ActionID string

ActionID identifies one action within a plan.

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

type Clock interface {
	After(time.Duration) <-chan time.Time
}

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.

func (Condition) Validate

func (condition Condition) Validate() error

Validate reports an error wrapping ErrInvalidCondition if the type is empty, the status is unknown, or the type, reason or message is not valid UTF-8 or contains NUL. Type and reason must also be single-line.

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 Decision

type Decision struct {
	Retry bool
	Delay time.Duration
}

Decision reports whether another attempt should run and after what delay.

type Desired

type Desired[S any] struct {
	Key        Key
	Generation Generation
	Spec       S
}

Desired holds a desired specification. Spec ownership is shallow.

func (Desired[S]) Validate

func (desired Desired[S]) Validate() error

Validate reports an error wrapping ErrInvalidDesired and the key or generation sentinel if desired has an invalid identity. Spec is not inspected.

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 Key

type Key string

Key identifies one independently reconciled value.

func (Key) Validate

func (key Key) Validate() error

Validate reports an error wrapping ErrInvalidKey if key is empty.

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

func (manager *Manager[S, O]) Close(ctx context.Context) error

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

func (manager *Manager[S, O]) Pending() []Pending[S]

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

type ManagerClock interface {
	Now() time.Time
	After(time.Duration) <-chan time.Time
}

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

type Pending[S any] struct {
	Desired Desired[S]
	RetryAt time.Time
}

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

type Plan[A any] struct {
	Actions []Action[A]
}

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

func (policy Policy) Decide(attempt int, err error) Decision

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.

func (Policy) Validate

func (policy Policy) Validate() error

Validate reports an error wrapping ErrInvalidPolicy if MaxAttempts is not positive, a duration is negative, or MaxDelay is below BaseDelay.

type Reconciler

type Reconciler[S, O any] interface {
	Reconcile(context.Context, Desired[S]) (Result[O], error)
}

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.

func (Result[O]) Clone

func (result Result[O]) Clone() Result[O]

Clone returns a shallow value copy with independent Conditions storage.

func (Result[O]) Validate

func (result Result[O]) Validate() error

Validate reports an error wrapping ErrInvalidResult if the identity is invalid, RequeueAfter is negative or any condition is invalid.

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.

type Undo

type Undo[U any] struct {
	ActionID ActionID
	Value    U
}

Undo contains the adapter-defined value needed to reverse an action. Value ownership is shallow.

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.

Jump to

Keyboard shortcuts

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