fooddelivery

package module
v0.0.0-...-12a90eb Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 6 Imported by: 1 module, 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

Food-delivery example

A complete, runnable order-lifecycle statechart built with Crucible. It models a generic food-ordering flow (place an order, hold payment, cook, deliver, capture) and exercises the whole engine at once: hierarchy and parallel regions, actors, invoked services, timed deadlines, a compensation saga, and snapshot/restore across a restart.

This is the flagship example: it is written the way Crucible recommends you write a v1 machine. Read it as a tutorial for the recommended patterns, then lift the shapes into your own domain.

The domain

An Order moves through these stages:

stateDiagram-v2
    [*] --> Placed
    Placed --> Authorizing: Submit
    Authorizing --> Rejected: decline
    Authorizing --> Active: success [admit guard]

    state Active {
        [*] --> Cooking
        Cooking --> AwaitingCourier
        AwaitingCourier --> EnRoute
        --
        [*] --> OnTime
        OnTime --> Overdue: after(SLA)
    }

    Active --> Settling: DroppedOff
    Active --> Refunding: Cancel
    Settling --> Delivered: always
    Refunding --> Canceled: refund result

    Rejected --> [*]
    Delivered --> [*]
    Canceled --> [*]

Authorizing invokes the payment authorize service. Active is a parallel superstate with two concurrent regions: a Fulfillment region (Cooking → AwaitingCourier → EnRoute, where Cooking supervises the kitchen actor and EnRoute the courier actor) and a Watchdog region (OnTime, which trips to Overdue and records a breach after(SLA)). DroppedOff exits the parallel state into Settling, which captures the payment hold and always lands in Delivered. Cancel routes into Refunding, the compensation saga, which invokes refund and ends in Canceled.

Run it through the host Rig (the example's wiring of the Scheduler, ServiceRunner, and ActorSystem); see rig.go, or embed the pieces directly.

Requirement → engine feature

Each business requirement maps to one engine capability. This is the table to study.

Business requirement Engine feature Where to look
"An order has data (basket, tip, payment hold) that changes as it progresses." Value-semantics context (Order passed and returned by value). Order struct; m.Cast(order, ...) in rig.go.
"Only well-defined steps may change that data; nothing mutates it behind your back." Assign reducers are the sole context writers. Guards and the kernel see the context read-only. every Reducer(...) and .Assign(...); recordHold, settleReducer, etc.
"Admit an order to fulfillment only if it clears a business rule." Core guard expressions over a ContextSchema (typed compare + membership, evaluated in-kernel, type-checked at build). WithContextSchema(SchemaOf[Order]()); Field(...).Ge(...), Field(...).In(...) on the Authorized edge.
"Some rules are richer than compare-and-match." Rich (CEL) guard from state/expr, composed with the Core leaves via Or. expr.Guard(...) building generousOrder; the WhenExpr(Or(generous, And(...))).
"Cooking and delivery happen alongside a delivery-time watchdog." Hierarchy + parallel regions (an orthogonal Active superstate with two regions). SuperState(Active) with Region("Fulfillment") ∥ Region("Watchdog").
"The kitchen and the driver are independent participants that report back." Actors: child machines the order supervises; their output returns through the completion event. Actor("kitchen"), Actor("courier"); kitchenBehavior, courierBehavior.
"Hold the payment, then capture it; reverse it if the order is canceled." Invoked services with onDone/onError. Service("authorize", ...), Service("refund", ...); Invoke(...).
"A service's result must flow into the order's data." onDone-via-event: the host re-fires the routing event carrying the result; the reducer reads it from AssignCtx.Event, no side channel. recordHold, recordRefund, recordPrep, recordDrop.
"Flag an order that misses its delivery window." after / SLA timeout via the Scheduler, driven deterministically with a fake clock in tests. After(SLAWindow) in the Watchdog region; Rig.BreachSLA.
"Canceling a paid order must reverse the charge." Compensation saga: a post-payment cancellation invokes the refund and folds the reversed amount in. the Cancel cross-cutting transition → Refunding → recordRefund.
"Survive a process restart mid-order." Snapshot → restore: the value context, active parallel configuration, pending timers, and in-flight actors all round-trip. Rig.Snapshot, RestoreRig; TestScenario_SnapshotRestoreMidOrder.
"Prove the machine has no dead ends or ambiguous steps." analysis.Analyze returns no findings (no dead states, unreachable states, or nondeterminism). TestModel_AnalyzeClean.
  • Context is a value, not a pointer. Order is passed by value; the kernel and guards never alias it. The only writes happen inside Assign reducers, each a pure function from the prior Order (and the triggering event) to the next.
  • Results arrive as events, not side channels. When the payment service or an actor completes, the host re-fires the routing event with the result as its payload; the onDone reducer reads it from AssignCtx.Event. There is no "last result" back-reference to thread through the builder.
  • Decision logic is data. Guards are authored as expressions over a typed schema: Core for the common compare/membership cases (evaluated in-kernel, zero dependency), Rich (CEL) when you need real expressions, so tooling can read and check them.
  • The host owns the loop. Crucible decides; the Rig dispatches the resulting effects (start a service, arm a timer, spawn an actor) to the world. The decision core stays pure.

Running it

go test ./...            # scenario + example tests
go test -run Example -v  # the runnable Example* walkthroughs

See scenario_test.go for the happy path, the refund saga, the SLA breach, the declined-authorization edge, and the snapshot/restore-across-restart flow.

Documentation

Overview

Package fooddelivery is the flagship Crucible example: a generic, textbook food-ordering lifecycle modeled as a single statechart that exercises the whole engine the way a real service would. It is invented from scratch and carries no coupling to any real delivery product — order, kitchen, courier, and payment are the neutral nouns of the domain.

The model demonstrates the patterns Crucible recommends for v1:

  • A value-semantics context (Order, passed and returned by value) whose only writer is an Assign reducer. Guards and the kernel observe the context read-only; a reducer takes the prior Order and returns the next.
  • Decision logic authored as data: Core guard expressions over a ContextSchema (compare/membership/boolean leaves the kernel evaluates directly), plus one Rich (CEL) guard from state/expr to show the second tier.
  • Hierarchy and parallel regions: an Active orthogonal superstate runs a Fulfillment region (kitchen → courier spine) in parallel with a Watchdog region (an SLA clock driven by an `after` timeout).
  • Actors for the restaurant (kitchen) and the driver (courier), each a child machine that messages the order on completion.
  • An invoked payment service (authorize, then capture) with onDone/onError, and a refund invocation that drives the cancellation saga's compensation.
  • Deterministic time: SLA timeouts arm through the Scheduler and advance with a fake clock in tests.
  • Snapshot and restore across a simulated process restart mid-order.

Build the machine with NewModel; drive it through the host runtime with NewRig (the example's wiring of Scheduler + ServiceRunner + ActorSystem), or embed the pieces directly. See README.md for the requirement-to-feature tutorial.

Example

Example demonstrates the order lifecycle's happy path end to end: a placed order is authorized, cooked by the kitchen actor, delivered by the courier actor, and captured — driven through the example's host Rig (Scheduler + ServiceRunner + ActorSystem). The printed log is the value context's folded record, written only by Assign reducers.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/stablekernel/crucible/examples/fooddelivery"
)

func main() {
	ctx := context.Background()
	rig, err := fooddelivery.NewRig(
		fooddelivery.WithOrder(fooddelivery.Order{Subtotal: 5500, Tip: 500, Priority: "fast"}),
	)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}

	rig.Submit(ctx)
	rig.SettleAuthorization(ctx, true) // payment hold succeeds
	rig.RunKitchen(ctx)                // kitchen actor plates the meal
	rig.PickUp(ctx)                    // courier dispatched
	rig.RunCourier(ctx)                // courier delivers; order settles

	fmt.Println("final stage:", rig.Configuration()[0])
	fmt.Println("log:", strings.Join(rig.Order().Log, " -> "))
}
Output:
final stage: Delivered
log: authorized:tok-001 -> kitchen:prepared-meal -> courier:drop-confirmed -> captured
Example (RefundSaga)

Example_refundSaga demonstrates the cancellation saga: after the payment hold, the order is canceled and the refund service reverses the hold. The reversed amount reaches the onDone reducer through the event — the recommended onDone-via-event result flow, with no host side channel.

package main

import (
	"context"
	"fmt"

	"github.com/stablekernel/crucible/examples/fooddelivery"
)

func main() {
	ctx := context.Background()
	rig, err := fooddelivery.NewRig(
		fooddelivery.WithOrder(fooddelivery.Order{Subtotal: 5000, Tip: 1500, Priority: "fast"}),
	)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}

	rig.Submit(ctx)
	rig.SettleAuthorization(ctx, true)
	rig.RunKitchen(ctx)
	rig.Cancel(ctx)             // open the compensation saga
	rig.SettleRefund(ctx, 6500) // refund reverses the held amount

	fmt.Println("final stage:", rig.Configuration()[0])
	fmt.Println("refunded:", rig.Order().Refund)
}
Output:
final stage: Canceled
refunded: 6500
Example (SlaBreach)

Example_slaBreach demonstrates the deterministic SLA timeout: with the kitchen still cooking, the fake clock advances past the delivery window, firing the Watchdog region's `after` timeout. The order is flagged breached but still delivers — the monitoring region runs orthogonally to the fulfillment spine.

package main

import (
	"context"
	"fmt"

	"github.com/stablekernel/crucible/examples/fooddelivery"
)

func main() {
	ctx := context.Background()
	rig, err := fooddelivery.NewRig(
		fooddelivery.WithOrder(fooddelivery.Order{Subtotal: 7000, Priority: "standard"}),
	)
	if err != nil {
		fmt.Println("build error:", err)
		return
	}

	rig.Submit(ctx)
	rig.SettleAuthorization(ctx, true)
	rig.BreachSLA(ctx) // clock advances past the SLA window

	fmt.Println("breached:", rig.Order().Breached)

	rig.RunKitchen(ctx)
	rig.PickUp(ctx)
	rig.RunCourier(ctx)
	fmt.Println("final stage:", rig.Configuration()[0])
	fmt.Println("still breached:", rig.Order().Breached)
}
Output:
breached: true
final stage: Delivered
still breached: true

Index

Examples

Constants

View Source
const CourierDrive = courierDrive

CourierDrive is the actor-driving message that advances the courier child machine to its final, delivered state. It is exported so hosts (and the dispatch showcase) can drive the fulfillment actors directly: deliver it to a running courier actor (as an any) to complete it and re-fire the parent's DroppedOff. Its type is unexported by design; consumers pass it as an opaque any to the actor delivery seam.

View Source
const GenerousGuardName = "generousOrder"

GenerousGuardName is the registry name the generous-order guard is bound under, and the name the Authorized transition's guard expression references. A consumer that injects an alternate engine via WithGenerousGuard must bind its node under this same name so the machine's guard expression resolves it unchanged.

View Source
const KitchenCook = kitchenCook

KitchenCook is the actor-driving message that advances the kitchen child machine to its final, plated state. It is exported so hosts (and the dispatch showcase) can drive the fulfillment actors directly: deliver it to a running kitchen actor (as an any) to complete it and re-fire the parent's PlatedUp. Its type is unexported by design; consumers pass it as an opaque any to the actor delivery seam.

View Source
const SLAWindow = 30 * time.Minute

SLAWindow is the delivery service-level window after which the Watchdog region's `after` timeout fires SLABreached. Tests advance a fake clock past it to drive the breach deterministically.

Variables

This section is empty.

Functions

func CourierBehavior

func CourierBehavior() state.ActorBehavior

CourierBehavior returns the courier actor's behavior. It is exported so hosts (and the dispatch showcase) can drive the fulfillment actors directly — for example registering it in a durable runner's actor palette under "courier" — rather than only through the example's Rig.

func GenerousGuardSource

func GenerousGuardSource() string

GenerousGuardSource returns the predicate source the default (CEL) generous-order guard compiles: subtotal + tip ≥ 6000. A consumer building an alternate-engine guard (for example a WebAssembly evaluator) reads it so the swapped engine reproduces the exact same predicate, the precondition for the two engines being behaviorally identical.

func KitchenBehavior

func KitchenBehavior() state.ActorBehavior

KitchenBehavior returns the kitchen actor's behavior. It is exported so hosts (and the dispatch showcase) can drive the fulfillment actors directly — for example registering it in a durable runner's actor palette under "kitchen" — rather than only through the example's Rig.

func NewModel

func NewModel(opts ...Option) (*state.Machine[Stage, Signal, Order], error)

NewModel forges the order lifecycle machine and returns it alongside the registry the rich generous-order guard is compiled into. The machine is authored with the fluent builder, then round-tripped through its IR (ToJSON → LoadFromJSON → Provide) so the rich-tier guard binds to the live machine the same way a host that loads a serialized definition would wire it — the in-repo demonstration of the rich tier.

The generous-order guard is named (GenerousGuardName), registry-bound, and engine-agnostic: by default it is the CEL predicate GenerousGuardSource, but a consumer may swap the engine — for example to a WebAssembly evaluator — with WithGenerousGuard, without touching the machine. The supplied options leave every other behavior unchanged, so NewModel() with no options builds the original CEL model.

func ServiceRegistry

func ServiceRegistry() *state.Registry[Order]

ServiceRegistry returns a registry holding the order's payment services (authorize and refund), so a host's ServiceRunner can actually run them rather than settling them deterministically. The example's Rig wires its runner with this registry; a host embedding the model would do the same.

Types

type GenerousGuardBuilder

type GenerousGuardBuilder func(reg *state.Registry[Order], schema state.ContextSchema) (state.GuardNode[Stage], error)

GenerousGuardBuilder builds the generous-order guard node, binding it into reg under GenerousGuardName and type-checking it against schema. The default builder compiles the CEL predicate GenerousGuardSource; an alternate builder supplied via WithGenerousGuard may evaluate the same predicate in any engine, so long as it binds a node named GenerousGuardName into reg. The returned node is dropped into the Authorized transition's guard expression unchanged, so the machine is agnostic to which engine computes the verdict.

type Option

type Option func(*modelConfig)

Option configures NewModel at construction. Options follow the functional-options pattern so the model gains seams additively: NewModel takes no required arguments (it has a sound default for every knob), and each capability arrives as an Option, so existing NewModel() callers are unaffected when a new seam is added.

func WithGenerousGuard

func WithGenerousGuard(build GenerousGuardBuilder) Option

WithGenerousGuard overrides the engine that computes the generous-order guard, without changing the machine. The supplied builder must bind a guard node named GenerousGuardName into the registry and return it; NewModel drops that node into the Authorized transition's guard expression in place of the default CEL node, so the admission logic — a generous order OR a big fast-lane basket — is unchanged and only the engine that decides "generous" differs. This is the seam the polyglot showcase uses to swap the CEL guard for a behaviorally identical WebAssembly guard.

type Order

type Order struct {
	// Subtotal is the order's pre-tip total, in whole currency minor units (cents).
	// The "expedite" Core guard compares it against a threshold.
	Subtotal int64 `json:"subtotal"`
	// Tip is the gratuity in cents. The Rich CEL guard reasons over subtotal+tip.
	Tip int64 `json:"tip"`
	// Priority marks an order the dispatcher flagged for the fast lane. The Core
	// membership guard reads it.
	Priority string `json:"priority"`
	// AuthHold is the payment-authorization token captured on Authorized. The
	// settlement and refund reducers fold the held amount through it.
	AuthHold string `json:"authHold"`
	// Refund is the amount reversed by the cancellation saga's compensating refund,
	// in cents.
	Refund int64 `json:"refund"`
	// Breached records that the Watchdog region's SLA timer fired before delivery.
	Breached bool `json:"breached"`
	// Log records the milestones the run folded, so a test can assert observable
	// behavior without a side channel.
	Log []string `json:"log"`
}

Order is the value-semantics context the machine is bound to. It is passed and returned by value; every change to it flows through an Assign reducer, so guards and the kernel only ever read it. The json tags name the fields for the ContextSchema and the Core/Rich guard expressions' field references.

type Rig

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

Rig is the example's host runtime: it casts an order instance and wires the three host drivers — a Scheduler (the SLA `after` timer), a ServiceRunner (the payment authorize/refund services), and an ActorSystem (the kitchen and courier actors). It is the realistic embedding a service would build around the pure decision core: Crucible decides, the Rig dispatches the resulting effects to the world.

A Rig is created with NewRig and driven with its Submit/Authorize/... helpers, each of which fires an event (or settles a driver) and routes the resulting effects back through every driver, exactly as a production host loop would.

func NewRig

func NewRig(opts ...RigOption) (*Rig, error)

NewRig forges the order machine, casts an instance around the supplied order, and wires all three host drivers, arming the initial configuration's effects. The returned Rig is ready to Submit. A build error from NewModel (e.g. a guard that fails to compile) is returned to the caller.

func RestoreRig

func RestoreRig(snap state.Snapshot[Stage, Signal, Order], opts ...RigOption) (*Rig, error)

RestoreRig rebuilds a Rig from a persisted snapshot, as a recovering host would after a process restart: it forges a fresh machine, restores the instance into it, re-wires a fresh driver set, and re-arms the resumed configuration's effects (pending SLA timers and in-flight actors). The restored Rig resumes exactly where the snapshot was taken — same configuration, same pending work.

func (*Rig) BreachSLA

func (r *Rig) BreachSLA(ctx context.Context) []state.FireResult[Stage]

BreachSLA advances the fake clock past the SLA window and ticks the Scheduler, firing the delayed SLABreached edge in the Watchdog region and absorbing its effects. It returns the timer-driven FireResults.

func (*Rig) Cancel

func (r *Rig) Cancel(ctx context.Context) state.FireResult[Stage]

Cancel opens the cancellation saga from any active substate, arming the refund.

func (*Rig) Configuration

func (r *Rig) Configuration() []Stage

Configuration returns the instance's active state configuration.

func (*Rig) InFinal

func (r *Rig) InFinal() bool

InFinal reports whether the instance has reached a terminal state.

func (*Rig) Order

func (r *Rig) Order() Order

Order returns the instance's current context value (read-only).

func (*Rig) PendingTimers

func (r *Rig) PendingTimers() int

PendingTimers reports how many `after` timers the Scheduler currently holds.

func (*Rig) PickUp

func (r *Rig) PickUp(ctx context.Context) state.FireResult[Stage]

PickUp advances the Fulfillment region from AwaitingCourier to EnRoute, dispatching the courier actor.

func (*Rig) RunAuthorization

func (r *Rig) RunAuthorization(ctx context.Context) (state.FireResult[Stage], bool)

RunAuthorization runs the real authorize service synchronously through the runner (executing authorizeFn) and routes its outcome, rather than settling it with a fixed token. It returns the resulting FireResult and whether a service ran.

func (*Rig) RunCourier

func (r *Rig) RunCourier(ctx context.Context) bool

RunCourier steps the courier actor to its final state, so its completion re-fires DroppedOff (carrying the drop proof) back through the order. It returns whether a courier actor was running to step.

func (*Rig) RunKitchen

func (r *Rig) RunKitchen(ctx context.Context) bool

RunKitchen steps the kitchen actor to its final state, so its completion re-fires PlatedUp (carrying the prepared item) back through the order. It returns whether a kitchen actor was running to step.

func (*Rig) RunRefund

func (r *Rig) RunRefund(ctx context.Context) (state.FireResult[Stage], bool)

RunRefund runs the real refund service synchronously through the runner (executing refundFn) and routes its outcome. It returns the resulting FireResult and whether a service ran.

func (*Rig) RunningActors

func (r *Rig) RunningActors() int

RunningActors reports how many child actors are currently running.

func (*Rig) SettleAuthorization

func (r *Rig) SettleAuthorization(ctx context.Context, ok bool) state.FireResult[Stage]

SettleAuthorization settles the in-flight authorization service, routing Authorized with the hold token on success or Declined on failure, and absorbs the follow-on effects.

func (*Rig) SettleRefund

func (r *Rig) SettleRefund(ctx context.Context, amount int64) state.FireResult[Stage]

SettleRefund settles the in-flight refund service, routing Refunded with the reversed amount, and absorbs the follow-on effects.

func (*Rig) Snapshot

func (r *Rig) Snapshot() state.Snapshot[Stage, Signal, Order]

Snapshot captures the instance's full runtime state (value context, active configuration, history, pending timers, and in-flight drivers) for persistence.

func (*Rig) Submit

func (r *Rig) Submit(ctx context.Context) state.FireResult[Stage]

Submit places the order, arming the payment authorization service.

type RigOption

type RigOption func(*rigConfig)

RigOption configures a Rig at construction. Options follow the functional-options pattern so the rig gains capabilities additively: required inputs are none (a Rig has sensible defaults), and every knob arrives as an option.

func WithClockStart

func WithClockStart(t time.Time) RigOption

WithClockStart sets the fake clock's start instant, so SLA timing is deterministic across runs.

func WithOrder

func WithOrder(o Order) RigOption

WithOrder seeds the initial order context the Rig is cast with.

type Signal

type Signal int

Signal is the order machine's event type. Authorized/Declined route the payment authorization outcome; Refunded routes the refund outcome; Cancel opens the saga; the kitchen/courier signals advance the Fulfillment region; SLABreached is the Watchdog region's delayed timeout; PlatedUp/PickedUp/DroppedOff move the spine.

const (
	Submit Signal = iota
	Authorized
	Declined
	PlatedUp
	PickedUp
	DroppedOff
	SLABreached
	Cancel
	Captured
	Refunded
)

The order lifecycle signals.

func (Signal) String

func (e Signal) String() string

String renders a Signal by name so traces and diagrams read symbolically.

type Stage

type Stage int

Stage is the order's lifecycle state. The leaves of the Active superstate's two regions (the Fulfillment spine and the Watchdog clock) are separate Stage values so a parallel configuration names both at once.

const (
	Placed Stage = iota
	Authorizing
	Active
	// Fulfillment region leaves.
	Cooking
	AwaitingCourier
	EnRoute
	// Watchdog region leaves.
	OnTime
	Overdue
	// Post-Active spine.
	Settling
	Delivered
	Refunding
	Canceled
	Rejected
)

The order lifecycle stages. Placed is the resting start; Authorizing invokes the payment hold; Active is the orthogonal superstate where the kitchen cooks and the courier delivers while an SLA clock runs alongside; Settling captures the held payment; Delivered is the happy-path terminal. The cancellation saga runs Refunding (a compensating payment reversal) to the Canceled terminal, and a declined authorization lands in Rejected.

func (Stage) String

func (s Stage) String() string

String renders a Stage by name so traces, diagrams, and analysis read symbolically.

Jump to

Keyboard shortcuts

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