migration

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 3 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

migration-harness-go

The fleet's one typed plan / diff / apply migration cycle — so migrators, installers, and validators share one converging loop instead of each hand-rolling "compute steps, check what's done, do the rest, report".

What

Three behaviour seams over a generic state type S, plus a harness that drives them:

  • Planner[S] — produces an ordered Plan[S] of Step[S]s from a starting state (the plan verb).
  • Differ[S] — reports whether a step is already satisfied, so the harness skips no-op applies (the diff verb).
  • Applier[S] — converges the state for one step (the apply verb).
  • Harness[S] — New(planner, opts…) then Run(ctx, state) drives the canonical loop (plan → per step: diff → apply unless satisfied) and returns a typed Report.

Steps are closures over the caller's S, so the harness owns control flow (ordering, dry-run, abort-vs-continue-on-error, before/after hooks, the typed Report) while the caller owns semantics. Plan/diff/apply failures and an unsatisfied step with no applier each become typed, code-carrying errors via errors-go (migration_plan_failed / migration_diff_failed / migration_apply_failed / migration_no_applier).

Why

Migrate, install, and validate are the same shape: figure out what needs doing, skip what's done, do the rest, report. Naming that cycle once means a new migrator is a Planner plus per-step Differ/Applier closures — never a bespoke loop with ad-hoc dry-run and error handling again.

Install

go get github.com/pleme-io/migration-harness-go

Usage

planner := migration.PlannerFunc[*State](func(ctx context.Context, s *State) (migration.Plan[*State], error) {
    return migration.Plan[*State]{Steps: []migration.Step[*State]{
        {
            ID:    "create-schema",
            Diff:  migration.DifferFunc[*State](func(ctx context.Context, s *State) (bool, error) { return s.HasSchema(), nil }),
            Apply: migration.ApplierFunc[*State](func(ctx context.Context, s *State) error { return s.CreateSchema(ctx) }),
        },
    }}, nil
})

h, err := migration.New(planner, migration.WithDryRun(false))
if err != nil { return errs.Exit(err) }
rep, err := h.Run(ctx, state)         // rep is a typed value → borealis.Render
if err != nil { return errs.Exit(err) }

Configuration

A typed Config (yaml-tagged) drives run policy when loaded via shikumi-go. Load once at main, then migration.FromConfig(cfg.Migration, planner):

dry_run: false
continue_on_error: false   # default: abort on first failure

FromConfig consumes the already-loaded sub-struct and never calls shikumi.Load itself (BOREALIS §3.5).

Release

Pull-model (Go modules): an annotated vX.Y.Z tag is the release; pkg.go.dev indexes it. See the GSDS module delivery FSM.

Documentation

Overview

Package migration provides a typed plan / diff / apply migration cycle reusable by migrators, installers, and validators. It names the three behaviour seams of any state-converging operation — a Planner that produces a typed Plan of [Step]s, a Differ that decides whether each step still needs doing, and an Applier that executes a step — plus a [Run] harness that drives them through the canonical loop: plan → for each step (diff → apply unless satisfied) → report.

The generic type parameter S is the migration's state type — whatever the caller's domain models (a schema version, a set of installed components, a validated invariant). Steps carry no S directly; instead they are closures over the caller's state, so the harness stays state-agnostic while the caller keeps full typing. The harness owns the *control flow* (ordering, dry-run, abort-on-error, before/after hooks, the typed Report); the caller owns the *semantics* (what a step does, when it is satisfied).

The model is borealis-style (BOREALIS.md §3.5): New(required…, opts…) / FromConfig(cfg). Errors are typed and code-carrying via errors-go. The package is pure stdlib plus errors-go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Applier

type Applier[S any] interface {
	Apply(ctx context.Context, state S) error
}

Applier executes a step, converging the caller's state toward the desired outcome. It is the "apply" verb of the cycle. A non-nil error fails the step; whether that aborts the run is governed by WithContinueOnError.

type ApplierFunc

type ApplierFunc[S any] func(ctx context.Context, state S) error

ApplierFunc adapts a plain function to the Applier interface.

func (ApplierFunc[S]) Apply

func (f ApplierFunc[S]) Apply(ctx context.Context, state S) error

Apply calls the underlying function.

type Config

type Config struct {
	// DryRun, when true, plans and diffs every step but invokes no applier,
	// equivalent to [WithDryRun] (true).
	DryRun bool `yaml:"dry_run"`

	// ContinueOnError, when true, keeps the run going past a failed step,
	// equivalent to [WithContinueOnError] (true). Default false = abort on the
	// first failure.
	ContinueOnError bool `yaml:"continue_on_error"`
}

Config is the typed, shikumi-loadable knob surface for a Harness. It maps directly to the run-policy options: whether to plan-only (dry-run) and whether to keep going past a failed step. The planner is a behaviour dependency, not config, so it is still passed to FromConfig positionally.

type Differ

type Differ[S any] interface {
	Satisfied(ctx context.Context, state S) (bool, error)
}

Differ reports whether a step's desired state already holds, so the harness can skip an apply that would be a no-op. It is the "diff" verb of the cycle. Returning (true, nil) means satisfied (skip); (false, nil) means needs apply; a non-nil error aborts the step (the harness cannot proceed without knowing).

type DifferFunc

type DifferFunc[S any] func(ctx context.Context, state S) (bool, error)

DifferFunc adapts a plain function to the Differ interface.

func (DifferFunc[S]) Satisfied

func (f DifferFunc[S]) Satisfied(ctx context.Context, state S) (bool, error)

Satisfied calls the underlying function.

type Harness

type Harness[S any] struct {
	// contains filtered or unexported fields
}

Harness drives a Planner / Differ / Applier cycle over a typed state S. Construct it with New; run it with Harness.Run. A Harness is reusable across runs and carries no per-run state.

func FromConfig

func FromConfig[S any](cfg Config, planner Planner[S], opts ...Option) (*Harness[S], error)

FromConfig constructs a Harness from an already-loaded Config plus the (non-config) planner behaviour (§3.5). It does NOT call shikumi.Load — the caller loads cfg once at main and hands this the sub-struct. Extra options compose after the config-derived ones, so a test or caller can still attach before/after hooks over a config-driven harness.

func New

func New[S any](planner Planner[S], opts ...Option) (*Harness[S], error)

New constructs a Harness for planner with the given options (§3.5 Construct shape: New(required…, opts…)). The planner is the one required dependency — it is the seam that turns a starting state into the ordered work.

func (*Harness[S]) Run

func (h *Harness[S]) Run(ctx context.Context, state S) (Report, error)

Run executes the full cycle against the starting state: it asks the planner for a Plan, then for each step in order asks the Differ whether it is satisfied and (unless satisfied or dry-run) invokes the Applier, collecting a typed Report.

On a step failure the run aborts unless WithContinueOnError was set; the returned error is the first step failure (or the plan failure), and the Report is always returned (partial on abort) so a caller can render what happened. A successful run returns a nil error and an OK report.

type Option

type Option func(*options)

Option configures a Harness during New / FromConfig. Options apply in order; a later option of the same kind overrides an earlier one.

func WithAfterStep

func WithAfterStep(hook func(StepResult)) Option

WithAfterStep registers a hook invoked just after each step is processed, receiving the step's StepResult. Use it for progress logging. A nil hook is ignored.

func WithBeforeStep

func WithBeforeStep(hook func(step Step[any], index int)) Option

WithBeforeStep registers a hook invoked just before each step is processed, receiving the step (type-erased to Step[any] so the hook is S-agnostic for logging) and its zero-based index. Use it for progress logging; it must not mutate state. A nil hook is ignored.

func WithContinueOnError

func WithContinueOnError(cont bool) Option

WithContinueOnError keeps the harness running after a step fails (recording the failure and moving to the next step) instead of aborting at the first failure. The default is abort-on-first-failure, the safe migration posture.

func WithDryRun

func WithDryRun(dry bool) Option

WithDryRun makes the harness plan and diff every step but never invoke an applier: unsatisfied steps are recorded as OutcomePlanned. It is the migrate/install/validate "what would change?" mode.

type Outcome

type Outcome int

Outcome classifies what the harness did with a single step.

const (
	// OutcomeApplied means the step was not satisfied and its applier ran
	// successfully.
	OutcomeApplied Outcome = iota
	// OutcomeSkipped means the step's differ reported it already satisfied.
	OutcomeSkipped
	// OutcomePlanned means the step would have applied but the run was a
	// dry-run ([WithDryRun]); the applier did not run.
	OutcomePlanned
	// OutcomeFailed means the step's diff or apply returned an error.
	OutcomeFailed
)

func (Outcome) String

func (o Outcome) String() string

String reports the outcome name, for diagnostics/reporting.

type Plan

type Plan[S any] struct {
	// Steps are executed in order.
	Steps []Step[S]
}

Plan is an ordered set of [Step]s produced by a Planner. The harness executes steps in slice order; a Planner that needs a different order returns them pre-sorted (the harness does not topologically sort — keeping it a thin, predictable loop, Law 2).

type Planner

type Planner[S any] interface {
	Plan(ctx context.Context, state S) (Plan[S], error)
}

Planner produces the Plan for a migration. It is the "plan" verb of the cycle — the seam where a migrator computes which steps a given starting state requires. A non-nil error from Plan aborts the run before any apply.

type PlannerFunc

type PlannerFunc[S any] func(ctx context.Context, state S) (Plan[S], error)

PlannerFunc adapts a plain function to the Planner interface.

func (PlannerFunc[S]) Plan

func (f PlannerFunc[S]) Plan(ctx context.Context, state S) (Plan[S], error)

Plan calls the underlying function.

type Report

type Report struct {
	// Steps are the per-step results in execution order.
	Steps []StepResult
	// DryRun records whether the run was a dry-run.
	DryRun bool
}

Report is the typed summary of a [Run]: the per-step results in execution order plus convenience counts. It is a value (not a string) so it renders the uniform borealis way — a caller passes it to borealis.Render rather than this package hand-formatting output (Law 4 / §3.5).

func (Report) Applied

func (r Report) Applied() int

Applied returns the number of steps whose applier ran successfully.

func (Report) Failed

func (r Report) Failed() int

Failed returns the number of failed steps.

func (Report) OK

func (r Report) OK() bool

OK reports whether the run completed with no failed steps.

func (Report) Planned

func (r Report) Planned() int

Planned returns the number of steps that would apply in a non-dry run.

func (Report) Skipped

func (r Report) Skipped() int

Skipped returns the number of already-satisfied steps.

type Step

type Step[S any] struct {
	// ID uniquely identifies the step within its plan and keys its result.
	ID string

	// Description is human-facing prose for the report/diagnostics. Optional.
	Description string

	// Diff reports whether the step is already satisfied (true → skip apply).
	// A nil Diff means "never satisfied" — the step always applies.
	Diff Differ[S]

	// Apply executes the step. Required unless Diff always reports satisfied.
	Apply Applier[S]
}

Step is one unit of a migration: a named, optionally-diffable, applyable operation. The harness drives a step by first asking its Differ whether it is already satisfied (skip if so), then invoking its Applier. A step with a nil Differ is treated as never-satisfied (always apply); a step with a nil Applier that is not satisfied is a codeNoApplier error (nothing can converge it).

Steps are closures over the caller's state of type S, so the harness never touches S itself — it only orders and invokes. ID must be unique within a Plan; it keys the step's StepResult in the Report.

type StepResult

type StepResult struct {
	// ID is the step's [Step.ID].
	ID string
	// Outcome classifies the step's disposition.
	Outcome Outcome
	// Duration is how long the step's diff+apply took.
	Duration time.Duration
	// Err is the error that failed the step (nil unless Outcome is
	// OutcomeFailed). It is the typed, code-carrying errors-go value.
	Err error
}

StepResult records what happened to one step during a [Run].

Jump to

Keyboard shortcuts

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