Reacting to what a step did
What you want to do
The shop's accountants want an audit line for every charge that succeeded: what the order was charged, and the receipt. You want it written after every successful charge, without adding a word about auditing to the charge.
The code
The audit is a step policy: a class extending StepPolicy, marked @stepPolicy({ name: "audit" }), both from itinera/policy. Its method marked @onStepSuccess() is a hook, which the executor calls after a step it is attached to succeeds. The hook asks for the step's name, for the order's price from the data bag, and for the receipt the step contributed, and contributes the audit line under audit. It returns this.keepDefault(), leaving what happens next as it was.
/**
* Writes an audit line for every step it is attached to that succeeds: what
* the order was charged, and the receipt the step gave back.
*/
@stepPolicy({ name: "audit" })
class Audit extends StepPolicy {
@onStepSuccess()
charged(
@stepName() step: StepName,
@fromWorkflow("price", integer) price: number,
@fromStep("receipt", string) receipt: string,
@contributor() contributor: Contributor,
): OnSuccess {
contributor.contribute(
"audit",
`${step} took ${String(price)}, receipt ${receipt}`,
);
return this.keepDefault();
}
}The workflow attaches the policy to the charge, with policies: [Audit] in the charge's options:
/**
* The shop's workflow: it charges, repairing a charge that fails and auditing
* one that succeeds, then ships, and shipping may be tried once more.
*/
@workflow({ name: "orders", reporters: [Log, Desk] })
@withStep(Charge, { name: "charge", rescue: RenewCard, policies: [Audit] })
@withStep(Ship, { name: "ship", retryBudget: 1 })
class Orders extends Workflow {
/** Names each journey after its order. */
@idGenerator()
orderNumber(@dataBag() data: DataBag): string {
return data.read("order", string).option().expect("the order's number");
}
/** The bank, as the payment client of the journey. */
@provider(PAYMENTS, { key: "payments" })
bank(): Provided<Payments> {
return this.provide(new Bank(2026));
}
/**
* A carrier for every attempt of a step: the main carrier first, the backup
* carrier after.
*/
@provider(CARRIER, { key: "carrier", perAttempt: true })
carriers(@attempt() attempt: Attempt): Provided<Carrier> {
if (attempt.isFirst()) return this.provide(new MainCarrier());
return this.provide(new BackupCarrier());
}
}The rescue step RenewCard is chapter 14's, the shipping is chapter 12's and the desk is chapter 11's. The providers are those chapter 14 shows, with the tokens PAYMENTS and CARRIER of chapter 7, and the interface Carrier is chapter 12's.
The log is chapter 14's, and now also says which policy's hook was called, and after which step:
case "hook_called":
if (event.source.kind !== "step hook") return undefined;
return `${event.source.policy}: ${event.source.hook} of ${event.source.step}`;A new customer, Kim, buys a gift card, which the shop sends by email. The charge now asks whether the order is a gift card, with the type token boolean, from itinera/value, and if it is, gives back the card's code under code:
/**
* Charges an order's price to its card through the payment client, and gives
* back its receipt, and the gift card's code when the order is a gift card.
*/
@step()
class Charge extends Step {
constructor(
@input("order", string) private readonly order: string,
@input("price", integer) private readonly price: number,
@input("card", string) private readonly card: string,
@input("giftCard", boolean) private readonly giftCard: boolean,
) {
super();
}
override run(
@service("payments", PAYMENTS) payments: Payments,
@contributor() contributor: Contributor,
): Outcome {
if (this.price <= 0) return this.fail("nothing-to-charge");
const receipt = payments.charge(this.order, this.card, this.price);
if (receipt === undefined) return this.fail("card-expired");
contributor.contribute("receipt", receipt);
if (this.giftCard) contributor.contribute("code", `G-${this.order}`);
return this.succeed();
}
}The payment client it asks for is chapter 14's Payments, with chapter 7's token PAYMENTS.
The order's data now says whether it is a gift card, and the output holds the audit line. The shop runs Ann's, Gil's and Jo's orders, then Kim's, reads back the audit line, and prints it:
/**
* What the shop reads back once the journey has ended: the type of the value
* under each name.
*/
const orderOutput = {
receipt: optional(string),
tracking: optional(string),
audit: optional(string),
};
const shop = Orders.build();
// The order, the customer, the price, the parcel's weight in kg, the card, and
// whether the order is a gift card.
const orders = [
{
order: "A-1",
customer: "Ann",
price: 40,
weight: 2,
card: "ann-2028",
giftCard: false,
},
{
order: "A-7",
customer: "Gil",
price: 45,
weight: 60,
card: "gil-2027",
giftCard: false,
},
{
order: "A-8",
customer: "Jo",
price: 30,
weight: 1,
card: "jo-2024",
giftCard: false,
},
{
order: "A-9",
customer: "Kim",
price: 25,
weight: 0,
card: "kim-2027",
giftCard: true,
},
];
for (const { order, customer, price, weight, card, giftCard } of orders) {
console.log(`${customer}'s order:`);
const instance = shop.instance({ order, price, weight, card, giftCard });
const result = await new LocalExecutor().run(instance);
const data = result.output(orderOutput);
const receipt = data.receipt.unwrapOr("none");
const tracking = data.tracking.unwrapOr("none");
console.log(
`the journey ${result.status.kind}, with receipt ${receipt} and tracking ${tracking}`,
);
console.log(`audit: ${data.audit.unwrapOr("none")}`);
}It prints:
Ann's order:
log orders A-1 #1 journey_started order, price, weight, card, giftCard
log orders A-1 #2 attempt_started charge, attempt 1
log orders A-1 #3 service_provided charge gets payments from bank, a Bank
the bank charges 40 for order A-1
log orders A-1 #4 step_succeeded charge
log orders A-1 #5 contribution_committed receipt
log orders A-1 #6 hook_called audit: on step success of charge
log orders A-1 #7 contribution_committed audit
log orders A-1 #8 attempt_started ship, attempt 1
log orders A-1 #9 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-1
log orders A-1 #10 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #11 step_succeeded ship
log orders A-1 #12 contribution_committed tracking
log orders A-1 #13 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 40, receipt R-A-1
Gil's order:
log orders A-7 #1 journey_started order, price, weight, card, giftCard
log orders A-7 #2 attempt_started charge, attempt 1
log orders A-7 #3 service_provided charge gets payments from bank, a Bank
the bank charges 45 for order A-7
log orders A-7 #4 step_succeeded charge
log orders A-7 #5 contribution_committed receipt
log orders A-7 #6 hook_called audit: on step success of charge
log orders A-7 #7 contribution_committed audit
log orders A-7 #8 attempt_started ship, attempt 1
log orders A-7 #9 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-7
log orders A-7 #10 step_failed ship: too-heavy
log orders A-7 #11 step_retrying ship
log orders A-7 #12 attempt_started ship, attempt 2
log orders A-7 #13 service_provided ship gets carrier from carriers, a BackupCarrier
the backup carrier books order A-7
log orders A-7 #14 step_info ship: the parcel leaves with receipt R-A-7
log orders A-7 #15 step_succeeded ship
log orders A-7 #16 contribution_committed tracking
log orders A-7 #17 journey_succeeded
the journey succeeded, with receipt R-A-7 and tracking B-A-7
audit: charge took 45, receipt R-A-7
Jo's order:
log orders A-8 #1 journey_started order, price, weight, card, giftCard
log orders A-8 #2 attempt_started charge, attempt 1
log orders A-8 #3 service_provided charge gets payments from bank, a Bank
the bank declines card jo-2024: it has expired
log orders A-8 #4 step_failed charge: card-expired
log orders A-8 #5 step_rescuing charge: failure, rescued by charge_rescue
log orders A-8 #6 attempt_started charge_rescue, attempt 1
the bank says card jo-2024 was replaced by jo-2029
log orders A-8 #7 step_succeeded charge_rescue
log orders A-8 #8 contribution_committed card
log orders A-8 #9 data_overwritten card
log orders A-8 #10 step_rescued charge by charge_rescue
log orders A-8 #11 attempt_started charge, attempt 2
the bank charges 30 for order A-8
log orders A-8 #12 step_succeeded charge
log orders A-8 #13 contribution_committed receipt
log orders A-8 #14 hook_called audit: on step success of charge
log orders A-8 #15 contribution_committed audit
log orders A-8 #16 attempt_started ship, attempt 1
log orders A-8 #17 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-8
log orders A-8 #18 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 #19 step_succeeded ship
log orders A-8 #20 contribution_committed tracking
log orders A-8 #21 journey_succeeded
the journey succeeded, with receipt R-A-8 and tracking T-A-8
audit: charge took 30, receipt R-A-8
Kim's order:
log orders A-9 #1 journey_started order, price, weight, card, giftCard
log orders A-9 #2 attempt_started charge, attempt 1
log orders A-9 #3 service_provided charge gets payments from bank, a Bank
the bank charges 25 for order A-9
log orders A-9 #4 step_succeeded charge
log orders A-9 #5 contribution_committed receipt
log orders A-9 #6 contribution_committed code
log orders A-9 #7 hook_called audit: on step success of charge
log orders A-9 #8 contribution_committed audit
log orders A-9 #9 attempt_started ship, attempt 1
log orders A-9 #10 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-9
log orders A-9 #11 step_info ship: the parcel leaves with receipt R-A-9
log orders A-9 #12 step_succeeded ship
log orders A-9 #13 contribution_committed tracking
log orders A-9 #14 journey_succeeded
the journey succeeded, with receipt R-A-9 and tracking T-A-9
audit: charge took 25, receipt R-A-9How it works
- A step policy holds what happens around a step. It defines hooks, and the workflow attaches it to steps, so the charge never knows it is audited. A step never knows which policies are attached to it; the workflow attaches them. The policy names no step of its own, so it can be attached to any step of any workflow; a hook that needs the step's name asks for it, with a parameter marked
@stepName()and typedStepName, both fromitinera/step. - The executor calls a hook after an outcome.
@onStepSuccess()marks the hook called each time a step the policy is attached to succeeds, after its contributions are committed; the audit reads the receipt from what the charge contributed. The executor records the call ashook_called, whosesourcenames the policy, the hook, and the step and attempt it was called after; for a step policy's hook,source.kindis"step hook". Jo's charge fails on its first attempt, so the hook is called only after attempt 2, once the charge succeeded with the new card. - A hook asks for what it needs, and gets only that. Each parameter is a request, marked with what it asks for, as a step's are.
@fromStep("receipt", string), fromitinera/policy, asks for what the step contributed underreceipt;@fromWorkflow("price", integer), fromitinera/workflow, asks for data from the data bag, hereprice;@contributor()asks for a contributor. Each value is checked by its type token, as a step's inputs are. A hook never gets the data bag itself. - A hook's contributions are committed when it returns. The audit line is committed right after the hook, as
contribution_committed audit, and the shop reads it back with the journey's output. - A hook decides nothing it isn't asked to. Its return type,
OnSuccess, fromitinera/policy, could carry a decision about what happens next.this.keepDefault()keeps the default, what happens next without the hook, and after a success the next step runs. The audit only writes down what happened. - A policy is built afresh for every attempt. The executor builds it with a constructor that takes nothing, and nothing is kept from one call to the next: everything a hook needs comes through what it asks for. Nor does it keep anything on its class: a policy with a static field holding data doesn't compile, as chapter 12 shows for a step.
Now look at Kim's journey. Her charge succeeded, and gave back her gift card's code, so there is nothing left to do for her order. But the workflow still runs the shipping, and the main carrier books a parcel of 0 kg.
Outcomes
We have shown how a step policy reacts to what a step did, without the step knowing.
| The usual way | With Itinera |
|---|---|
| Auditing a call is usually a line added after it, wherever it is made, so the code that charges also knows about the audit. | The audit is a policy attached to the charge in the workflow, and the charge has no line about it. |
| What runs after a call succeeds is often spread across the callers. | Every hook call is an event, naming the policy and the hook, after the outcome it reacts to. |