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 ¶
- Constants
- func CourierBehavior() state.ActorBehavior
- func GenerousGuardSource() string
- func KitchenBehavior() state.ActorBehavior
- func NewModel(opts ...Option) (*state.Machine[Stage, Signal, Order], error)
- func ServiceRegistry() *state.Registry[Order]
- type GenerousGuardBuilder
- type Option
- type Order
- type Rig
- func (r *Rig) BreachSLA(ctx context.Context) []state.FireResult[Stage]
- func (r *Rig) Cancel(ctx context.Context) state.FireResult[Stage]
- func (r *Rig) Configuration() []Stage
- func (r *Rig) InFinal() bool
- func (r *Rig) Order() Order
- func (r *Rig) PendingTimers() int
- func (r *Rig) PickUp(ctx context.Context) state.FireResult[Stage]
- func (r *Rig) RunAuthorization(ctx context.Context) (state.FireResult[Stage], bool)
- func (r *Rig) RunCourier(ctx context.Context) bool
- func (r *Rig) RunKitchen(ctx context.Context) bool
- func (r *Rig) RunRefund(ctx context.Context) (state.FireResult[Stage], bool)
- func (r *Rig) RunningActors() int
- func (r *Rig) SettleAuthorization(ctx context.Context, ok bool) state.FireResult[Stage]
- func (r *Rig) SettleRefund(ctx context.Context, amount int64) state.FireResult[Stage]
- func (r *Rig) Snapshot() state.Snapshot[Stage, Signal, Order]
- func (r *Rig) Submit(ctx context.Context) state.FireResult[Stage]
- type RigOption
- type Signal
- type Stage
Examples ¶
Constants ¶
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.
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Cancel opens the cancellation saga from any active substate, arming the refund.
func (*Rig) Configuration ¶
Configuration returns the instance's active state configuration.
func (*Rig) PendingTimers ¶
PendingTimers reports how many `after` timers the Scheduler currently holds.
func (*Rig) PickUp ¶
PickUp advances the Fulfillment region from AwaitingCourier to EnRoute, dispatching the courier actor.
func (*Rig) RunAuthorization ¶
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 ¶
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 ¶
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 ¶
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 ¶
RunningActors reports how many child actors are currently running.
func (*Rig) SettleAuthorization ¶
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 ¶
SettleRefund settles the in-flight refund service, routing Refunded with the reversed amount, and absorbs the follow-on effects.
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 ¶
WithClockStart sets the fake clock's start instant, so SLA timing is deterministic across runs.
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.
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.