Explanation

How features become machines

Source Trax.StateMachine.Gherkin/, FromIr/

A machine written as features passes through four forms: the lexicon and the features a team writes, the <machine>.ir.json and host.json that trax machine from-gherkin writes (with glossary.json, the lexicon elaborated to the JSON derivation reads), the machine a host builds from them, and the GraphQL fields and generated client a caller sees. This page follows one machine through all four, so that a change in one place can be traced to the others. The how-to is Write machines as features, every key is in the lexicon and feature files references, and the reasons are ADR 0058 and ADR 0059.

One scenario, followed through

The CheckIn sample's passenger owns a booking. Its lexicon names the words (an excerpt):

Machine: booking
  Owned by: passenger
  Started by: "has a booking"
  Context: seat may be empty
 
  State: Booked   "is booked"
  State: Open     "is open for check-in"
  State: Issuing  "is getting a boarding pass"
 
  Trigger: CheckIn "checks in for {subject} in seat {seat}"
    Input: seat is a string
    Sets: seat
 
  Guard: hasPassport when passport is not empty
    Holds: "has a passport number"
    Fails: "has no passport number"

Trax elaborates it to the glossary before anything else reads it: the machine's noun is booking, its id, it starts in Booked, and its context holds seat, a string that may be empty, and passport, which another trigger's Sets: writes. The glossary is what derivation reads, and from-gherkin commits it as glossary.json.

Two scenarios use them:

Scenario: A passenger checks in and gets a boarding pass
  Given Ada is a passenger
  And Ada has a booking
  And Ada's booking is open for check-in
  And Ada's booking has a passport number
  When Ada checks in for her booking in seat "14C"
  Then Ada's booking is getting a boarding pass
 
Scenario: Checking in with no passport number is refused
  Given Ada is a passenger
  And Ada has a booking
  And Ada's booking is open for check-in
  And Ada's booking has no passport number
  When Ada checks in for her booking in seat "14C"
  Then Ada is told "Add your passport number first."
  And Ada's booking is still open for check-in

Derivation reads the steps against the lexicon's phrases. Ada's booking is the booking machine, because its noun is booking, and it is Ada's instance. checks in for her booking in seat "14C" is the trigger CheckIn, fired by Ada, with 14C as its seat input. has no passport number is the guard hasPassport failing. The first scenario shows CheckIn moving Open to Issuing when the guard holds. The second shows it refused when the guard fails, with a message. Merged, they are one guarded edge, written to booking.ir.json:

{ "from": "Open", "trigger": "CheckIn", "to": "Issuing",
  "guard": { "rule": "nonEmpty", "source": "context", "field": "passport" },
  "guardMessage": "Add your passport number first.",
  "reduce": { "reduce": "set", "steps": [ { "field": "seat", "value": { "input": "seat" } } ] } }

Ada fired CheckIn herself and Ada is a passenger, so passengers may fire it. That goes to host.json, which clients never see:

"triggers": { "CheckIn": { "roles": [["passenger"]] } }

It also goes to access.txt, the line a reviewer reads, as booking CheckIn: passenger. Served with ServeFeatures, the trigger becomes the mutation machines { booking { checkIn(id, input, requestId) } }, held to that rule. A caller who is not a passenger is answered FORBIDDEN, and a booking with no passport number is answered with the guard's message.

Where each part ends up

Written asIn the IRIn host.jsonServed as
a machine with Owned by:the machine, by its idowner: "user", start and read rulesmachines.<machine>: start, get, discard and the push
a machine with System or System at:the machineowner: { "system": "<key>" }nothing a client calls: the host starts its one instance, and views read it
a machine with System keyed by:the machineowner: { "system": { "keyedBy": [...] } }nothing a client calls: host code starts and moves each instance
State: lines, with committed, Requires: and a state's own Context:states, initialState, context, committedStates, invariantsthe state enum and context records of the generated client
Context:, Starts with:, and the fields the lines writecontext (each state's), initialContextthe context record
a trigger a person fires (When Ada checks in for her booking in seat "14C")triggers, a transitiontriggers.<T>.roles (or anyAuthenticated)the mutation <trigger>
a trigger no person fires (When check-in opens for the flight)triggers, a transitiontriggers.<T>.server: truenothing: only the server fires it
a trigger only ever denied, or never firednothingnothingnothing
a trigger's Input: and Sets: (or Keeps, Clears, Resets, Reduces with:)inputs.<T>, the transition's reducethe mutation's input
a guard, with a scenario where it holds and one where it failsthe transition's guard and guardMessagethe refusal's message
When 10 seconds pass then a new statetimers (<State>.after)nothing: the server fires it
Runs: <train> in <State> and its Outcome: linesoutcomes (<State>.done, .failed, .cancelled) with outputinvokes.<State>.train and inputnothing: outcomes come from the run
Input: <field> from the owner, or owner in Takes:nothinginvokes.<State>.inputnothing: the server sets it
a Then about another instance moving after a Whenthe moved machine's transitionpolicies (linked, toSystem, broadcast)nothing: the server fires it
Link:nothingthe linked policy's link fieldnothing
View: and a show(s) Thennothingviews, with its readersviews { <view> { ... } } and views.g.ts
a trigger's Effect:the trigger, with its keyPrefixeffectsthe effect event, sent with no input
Rule:, Reduction:custom rules and reductions by namehandlers
a machine's Version:, Migrates from:versionmigrations
Differentialdifferential, from what the scenarios sent
every scenarioprovenance, by file, line and namethe console's Board page

Three rules hold across the table:

  • The IR is behaviour, host.json is everything else. The IR ships to clients and its hash is in every persisted id, so it holds what any engine needs to move an instance and nothing about who may. Access, trains, policies, views, handler types and provenance are in host.json only.
  • What no scenario shows is not served. A trigger, a view or a grant exists because a scenario shows it. A lexicon line no scenario uses derives nothing, and trax machine missing lists it.
  • A person acts only on their own instance. A step where Ada acts on Bo's booking, or on a system machine, is a derivation problem, not a grant.

Who acts in a step

Every When has an actor, and the actor decides what derivation records:

The WhenWho fires itWhat it grants
Ada checks in for her booking in seat "14C"Ada, on her own instanceher actor gets the trigger
Ada's booking misses the flight, check-in opens for the flightthe servernothing: the trigger is server-only
the boarding pass is issuedthe train the state invokesnothing: an outcome is never a client's
10 seconds passthe clocknothing: a timer is never a client's

A Then after the When says where each instance went. The first Then about the acting instance is where the When took it. A later Then about another instance moving is a policy that the move set off, and derivation works out its shape from whose instances they are: the same owner through a link is linked, a user's machine moving a system machine is toSystem, and a system machine moving every user instance in a state is broadcast. A trigger a policy fires is also server-only, and needs a scenario of its own showing it as a plain move.

The same machine in C#

A machine served from features is the same machine a hand-written [TraxMachine] class builds: the host replays the IR into the same builder and refuses to start if the result exports a different IR. For a reader who knows the builder, each lexicon line is the call it stands for:

LexiconBuilder
Machine: bookingId("booking")
a machine's Version:Version(2)
Begins in:, Starts with:StartsAt(State.Booked, () => ...)
Context:, a state's own Context:In(state).Context<TContext>()
committed on a State: lineIn(state).Committed()
a state's Requires:In(state).Requires(rule)
Migrates from:MigrateFrom(version, ...)
DifferentialDifferential(d => ...), written from the scenarios
a trigger with Input:On(trigger).WithInput<TInput>()
a trigger's Sets:.Reduce(Set(...).FromInput(...))
a Guard:'s rule, its refusal's message.When(rule).Because("...")
a scenario's move.To(state)
Rule:, Reduction:CustomGuard(name, ...), CustomReducer(name, ...)
a trigger's Effect:.RunsOnce<TEffect>(keyPrefix)
Runs: and its outcomesIn(state).Invokes<TTrain, TInput, TOutput>(...) with OnDone, OnFailed, OnCancelled
time passing in a scenarioIn(state).After(delay).GoTo(target)
an actor shown firing a trigger.Requires("role") on the transition
an actor shown starting oneStart<TStartInput>(s => s.Requires("role"))
who reads itGet(r => r.OwnerOnly().Requires("role")), the same for Watch and Discard
System, System at:SystemOwned()

Some of each side has no counterpart on the other:

  • Only from features: server-only triggers (a hand-written machine has no public call for one), policies between machines, views, the started system instance at its fixed key, and provenance.
  • Only in C#: spawning a child machine (Spawns, Ends, Fails), delegate guards and reducers, RequiresPolicy, Anonymous, InvokedRunLimit, and a timer whose duration a context field holds. A machine that needs one of these is written in C#. One host serves both kinds: ServeFeatures and the assemblies of [TraxMachine] classes go in the same AddStateMachines call.

Checking that the forms agree

Each step checks the one before it, so a mismatch is found where it was made rather than at a client:

  • from-gherkin replays every scenario on the machines it derived, access included, and writes nothing if one fails.
  • The lexicon is read whole: a line it cannot read gives no glossary, and every problem, the glossary reader's included, names its lexicon line.
  • from-gherkin --check in CI fails when the committed machines/, glossary.json among it, no longer matches the features and the lexicon.
  • The host refuses a host.json whose schemaHash is not the IR's, and a machine that does not export back to the IR it was built from.
  • trax machine run plays the features on the committed files, and the Reqnroll bindings play them against the running host.

trax machine explain prints what derivation read from each scenario: the edges, guards, timers and policies, and which Then caused which. It is the quickest way to see why a part of the table above came out as it did.

SDK Reference

Lexicon | ServeFeatures | FeatureMachines | Feature bindings | IR format | Machine | Views root