Every state of an order, written down

A statechart is a state machine whose states can nest and run in parallel, written in SCXML, a W3C standard; an actor is one statechart running with its own data. This page builds one order chart, from the cart to a shipped parcel, and you can drive it as you read. After it, you can read any chart on this site and judge whether your own workflow fits one.

Drive the order

Flags let an order be paid and cancelled

An order that tracks its progress with booleans can reach combinations nobody meant. Each one is a bug a customer finds: a card charged twice, a paid order cancelled.

Here is an order written the usual way, with a flag per step and a handler per event. The last four lines play one afternoon of it.

order.mjsjavascript
const order = { paying: false, paid: false, cancelled: false, attempts: 0 };

function charge() { order.attempts += 1; console.log('charge', order.attempts); }
function checkout() { order.paying = true; charge(); }
function onCharged() { order.paid = true; }  // paying stays true
function onTimeout() { if (order.paying && order.attempts < 3) charge(); }
function cancel() { order.cancelled = true; }

checkout();
onCharged(); // the payment service answers
onTimeout(); // the timer nobody cleared fires anyway
cancel();    // nothing stops a cancel after payment
console.log(order);
output
charge 1
charge 2
{ paying: true, paid: true, cancelled: true, attempts: 2 }

Nothing here is careless. Each handler sets the flag it owns, and the retry checks paying as it should. But onCharged forgot to clear paying, and nothing in the program says which combinations are legal.

Three booleans make eight combinations, and only four make sense: in the cart, paying, paid and cancelled. Every handler has to rule out the other four, and each new flag doubles them. A state machine starts from the other end: it lists the states, so the order is in exactly one.

An order is in one state

The order must take add while it is a cart and refuse it while the card is charged. With flags, that is one more check at the top of a handler.

A state is a situation the order waits in. An event is a named message, with optional data, that it receives. Each state lists the events it handles, and an event no transition of the current state names is discarded.

In SCXML, the W3C's XML language for statecharts, that is a <state> with a <transition> per event. The cart handles two: add puts an item in it, and checkout moves the order to paying. In paying no transition names add, so the cart can't change while the card is charged.

order.scxml
<state id="cart">
  <transition event="add">
    <assign location="items" expr="items.concat([_event.data.item])"/>
    <assign location="total" expr="total + _event.data.price"/>
  </transition>
  <transition event="checkout" cond="items.length &gt; 0" target="paying"/>
</state>

A guard decides whether a transition fires

Checkout with an empty cart must do nothing, and a payment that keeps timing out must stop after three tries. Both depend on data, not on which state the order is in.

A transition names its event, its target state and, in cond, a guard: a condition that must be true for it to fire. The cart's checkout has items.length > 0, so an empty cart stays a cart.

When several transitions of a state match one event, the first in document order whose guard holds is taken. paying uses that for its timeout. The first transition tries again while attempts < 3; the second has no guard, so it catches the third timeout and returns the order to the cart.

order.scxml
<transition event="charged" target="paid"/>
<transition event="payment.timeout" cond="attempts &lt; 3" target="paying"/>
<transition event="payment.timeout" target="cart"/>

The data model holds what states cannot

A cart holds any number of items, and a state for each cart would never end. The order also has to remember its total and how often it charged.

Each chart has a data model: variables declared in <datamodel> with their first values, read and changed by expressions in the chart's language. This chart's language is ECMAScript, named by datamodel="ecmascript" on its root.

An <assign> changes a variable when a transition fires, and _event.data is the data the event carried: the cart's add appends the item and adds its price. States say where the order is. Variables say what it holds.

order.scxml
<datamodel>
  <data id="items" expr="[]"/>
  <data id="total" expr="0"/>
  <data id="attempts" expr="0"/>
</datamodel>

A parent state handles its children's events

A customer may cancel while the order is a cart or while the card is charged, but never once it's paid. In the flag version, that rule is an if someone has to remember in cancel.

States nest. cart and paying are children of open, and while the order is in either, open is active too. A transition on open applies in every state inside it, so one line lets the customer cancel from both.

Once paid, the order has left open, and cancel finds no transition. A refund after payment would be a transition of its own, on paid, where a reviewer reads it.

order.scxml
<!-- An open order: the customer may cancel it from any state inside. -->
<state id="open" initial="cart">
  <transition event="cancel" target="cancelled"/>

  <state id="cart">

Parallel states run side by side

A paid order ships and emails its receipt, and neither waits for the other. A plain state machine would need a state for each pair: packing and emailing, packing and emailed, and two more.

A <parallel> state is in all of its children at once, each child a region with its own states. Here shipping waits in packing for the warehouse's shipped, while receipt emails the receipt and waits for sent.

When every region reaches a final state, the chart sends itself the event done.state.paid, a name SCXML makes from the parallel state's id, and the order moves to complete. The set of states active at one moment is the state configuration. The program's output shows one: paid with packing in one region and emailed in the other.

order.scxml
<!-- A paid order ships and emails its receipt at the same time. -->
<parallel id="paid">
  <state id="shipping" initial="packing">
    <state id="packing">
      <transition event="shipped" target="shipped"/>
    </state>
    <final id="shipped"/>
  </state>
  <state id="receipt" initial="emailing">
    <state id="emailing">
      <onentry>
        <send type="email" event="receipt">
          <param name="total" expr="total"/>
        </send>
      </onentry>
      <transition event="sent" target="emailed"/>
    </state>
    <final id="emailed"/>
  </state>
  <transition event="done.state.paid" target="complete"/>
</parallel>

A timer is an event sent later

The payment service sometimes never answers, so the order must charge again after five seconds. In the flag version, that timer outlived the payment and charged the card twice.

A delayed send is a <send> with a delay: with no target, the event comes back to the chart itself, later. Each time the order enters paying, it sends itself payment.timeout five seconds out.

Its <onexit> cancels that send by its id, so leaving the state takes the timer with it. A charged that arrives first leaves no timeout behind to charge again.

order.scxml
<!-- Each entry charges the card and starts a five-second timer.
     Leaving the state cancels the timer, so a late timeout cannot charge again. -->
<state id="paying">
  <onentry>
    <assign location="attempts" expr="attempts + 1"/>
    <send type="payments" event="charge">
      <param name="amount" expr="total"/>
    </send>
    <send id="timeout" event="payment.timeout" delay="5s"/>
  </onentry>
  <onexit>
    <cancel sendid="timeout"/>
  </onexit>

The timer runs on the host's clock, not on a setTimeout of yours. A test gives the host a simulated clock and moves it: the program's clock.increment(5000) fires the timeout at once, and the output shows the second charge at 5000 ms.

The chart never calls the network

Charging a card and sending an email are I/O, and I/O is what makes a workflow hard to test. A chart that made its own HTTP calls would make every test stub the network or wait for it.

A chart reaches the world only by sending events. <send type="payments"> leaves the order as an effect, a request for your code. The host, the part of tinyactors that runs charts in your program, hands it to the I/O processor your program gave it for payments. The processor does the I/O and answers with an event, charged, which the order receives like any other.

So your program decides how a charge happens: a payment API in production, a stand-in in a test. This one ignores the first charge and answers the second. In the diagram, you play the payment service yourself by pressing charged.

main.mjsjavascript
const clock = new SimulatedClock();
let charges = 0;
const payments = {
  receive(send) {                    // the chart's <send type="payments">
    charges += 1;
    console.log(`${clock.now} ms: charge ${send.data.amount}, attempt ${charges}`);
    if (charges > 1) send.answer('charged'); // the first charge never answers
  },
};

An actor is one running chart

A shop has thousands of open orders, each at its own step with its own cart. They must not share variables, and two events for one order must never interleave.

An actor is one instance of a chart: its own state configuration, its own variables, its own queue of events and its own timers. The host is the part of tinyactors that runs actors in your process. It starts one with spawn, here under the name order-1042, and any part of the program finds it by that name.

Events sent to an actor wait in its queue, and it handles them one at a time, each to completion. So an add and a checkout for one order never run halfway into each other, and your code holds no lock. That holds within one host: with several processes, give each order to one of them and send its events there.

main.mjsjavascript
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);
const host = new Host(compiled, { system: 'shop', clock, ioProcessors: { payments, email } });
compiled.close();

host.spawn('order', { name: 'order-1042' });
const order = host.actor('order-1042');  // any part of your program finds it by name
order.send('add', { item: 'notebook', price: 30 });
order.send('add', { item: 'pen', price: 12 });
order.send('checkout');
await host.idle();
console.log('waiting in', JSON.stringify((await order.state()).value));

An actor is small: about 530 bytes each for a one-variable chart, measured in Node.js with a million in one process. That is small enough to make each order, payment or chat session an actor of its own.

Run the whole order

Each section showed one piece of the chart. A program must start the order, answer its charges and move its clock.

Here are the whole chart and the program. spawn('order') names the chart by its name attribute, not its file. Open the Diagram tab beside order.scxml, press Add a notebook, then checkout, and watch the active states light up.

import { readFileSync } from 'node:fs';
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const clock = new SimulatedClock();
let charges = 0;
const payments = {
  receive(send) {                    // the chart's <send type="payments">
    charges += 1;
    console.log(`${clock.now} ms: charge ${send.data.amount}, attempt ${charges}`);
    if (charges > 1) send.answer('charged'); // the first charge never answers
  },
};
const email = {
  receive(send) {                    // the chart's <send type="email">
    console.log(`${clock.now} ms: receipt for ${send.data.total}`);
    send.answer('sent');
  },
};

const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);
const host = new Host(compiled, { system: 'shop', clock, ioProcessors: { payments, email } });
compiled.close();

host.spawn('order', { name: 'order-1042' });
const order = host.actor('order-1042');  // any part of your program finds it by name
order.send('add', { item: 'notebook', price: 30 });
order.send('add', { item: 'pen', price: 12 });
order.send('checkout');
await host.idle();
console.log('waiting in', JSON.stringify((await order.state()).value));

clock.increment(5000);               // five seconds pass, at once: the timeout fires
await host.idle();
console.log('then in', JSON.stringify((await order.state()).value));

order.send('shipped');               // the warehouse reports the parcel
console.log('complete, total', await order.done);
host.close();
output
0 ms: charge 42, attempt 1
waiting in {"open":"paying"}
5000 ms: charge 42, attempt 2
5000 ms: receipt for 42
then in {"paid":{"shipping":"packing","receipt":"emailed"}}
complete, total 42

Read the output from the top. The first charge got no answer, so the order waited in paying. Five seconds later the timeout charged again, the stand-in answered, and the order entered paid.

Both regions started then: the receipt went out at once, while shipping waited in packing. The warehouse's shipped finished the last region, and the order completed with its total.

Build a system of actors next

One chart is one entity. A real system has many actors that send each other events, go idle and come back.

The chat tutorial builds a team chat from actors like this order, one step at a time, with rooms, presence and idle users saved to a store. Writing charts covers the rest of SCXML as tinyactors runs it: scripts, sends between actors and charts that start other charts.

Run it in five minutesBuild a team chatWrite your first chart