Using a step in another workflow
What you want to do
Customers can now collect their orders at the shop's counter, paying at the counter's card terminal and taking the goods away, so nothing is shipped. You want the counter to look the order up, price it and charge it exactly as delivered orders are, without copying any of that code, and to decide for itself everything else.
The code
The shop is the one chapter 37 lists. The counter's terminal is one more implementation of the Payments interface the charge already asks for, as chapter 35 shows it. Like the bank, it reads the year a card expires with expiry, a helper of the faked bank:
/**
* The shop counter's card terminal, faked: it declines a card that expired
* before this year, and prints what it does. Its receipts start with `C`.
*/
class Terminal implements Payments {
constructor(private readonly thisYear: number) {}
async charge(
order: string,
card: string,
amount: number,
): Promise<string | undefined> {
if (expiry(card) < this.thisYear) {
console.log(
`the counter's terminal declines card ${card}: it has expired`,
);
return undefined;
}
console.log(
`the counter's terminal charges ${String(amount)} for order ${order}`,
);
return `C-${order}`;
}
}The counter's workflow lists three of the shop's steps, Lookup, Price and Charge, under the same names, and provides the order book and the terminal:
/**
* The counter's workflow: it looks the order up, and finishes an order already
* completed. Otherwise it works out what the order costs, then charges it at
* the counter's terminal and audits the charge. The customer takes the goods
* away, so nothing is shipped, and a card the terminal declines is handed back
* rather than repaired.
*/
@workflow({ name: "counter", reporters: [Log] })
@withStep(Lookup, { name: "lookup", policies: [AlreadyCompleted] })
@withStep(Price, { name: "price" })
@withStep(Charge, { name: "charge", policies: [Audit] })
class Counter 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 order book, which has the orders completed before today. */
@provider(ORDER_BOOK, { key: "orderBook" })
ledger(): Provided<OrderBook> {
return this.provide(new Ledger(["A-13"]));
}
/** The counter's terminal, as the payment client of the journey. */
@provider(PAYMENTS, { key: "payments" })
terminal(): Provided<Payments> {
return this.provide(new Terminal(2026));
}
}What it names is as earlier chapters show it: the lookup, AlreadyCompleted, OrderBook, ORDER_BOOK and Ledger in chapter 22, the pricing in chapter 20, the charge in chapter 33, the audit in chapter 34, the token PAYMENTS in chapter 7, and the log in chapter 33, chapter 35 and chapter 36. The shop's own workflow class, Orders, is as chapter 39 shows it.
The program prints the listing of each workflow with entry, as chapter 37 did:
console.log("orders:");
for (const listed of Orders.listing()) {
console.log(entry(listed));
}
console.log("counter:");
for (const listed of Counter.listing()) {
console.log(entry(listed));
}Then it runs two new orders at the counter: Nia's, with a discount, and Omar's, whose card has expired. Each order's initial data has what the three steps read, and no parcel or customer, since nothing at the counter reads them; the customer's name goes to the log as global metadata, as in chapter 33:
const counter = Counter.build();
const executor = new LocalExecutor();
// Each customer, and their order: its number, the price, the discount when
// there is one, the card, and whether it is a gift card.
const orders = [
{
customer: "Nia",
data: {
order: "A-17",
price: 18,
discount: 3,
card: "nia-2028",
giftCard: false,
},
},
{
customer: "Omar",
data: { order: "A-18", price: 12, card: "omar-2023", giftCard: false },
},
];
for (const { customer, data } of orders) {
console.log(`${customer}'s order ${data.order}, at the counter:`);
const instance = counter.instance(data, {
reportersGlobalMetadata: { customer },
});
followUp(await executor.run(instance));
}followUp now reads the counter's output, with the methods of chapter 25, and says to hand back a card the terminal declined:
/**
* What the counter reads back once the journey has ended: the type of the
* value under each name.
*/
const collected = { receipt: optional(string), audit: optional(string) };
/** Says how a journey at the counter ended. */
function followUp(result: JourneyResult): void {
if (result.isSucceeded()) {
const data = result.output(collected);
console.log(
`the journey succeeded, with receipt ${data.receipt.unwrapOr("none")}`,
);
console.log(`audit: ${data.audit.unwrapOr("none")}`);
return;
}
if (result.isFailed() && result.status.failure.cause === "failure") {
console.log(
`the journey failed: ${result.status.failure.reason.code}, hand the card back`,
);
return;
}
console.log(`the journey ended as ${result.status.kind}`);
}It prints:
orders:
1. lookup, with alreadyCompleted; services: orderBook from ledger
2. price
3. charge, with audit, outage; services: payments from bank; rescued by charge_rescue, services: cards from cards
4. ship, with failedShipping; adapted by parcels; services: carrier from carriers
counter:
1. lookup, with alreadyCompleted; services: orderBook from ledger
2. price
3. charge, with audit; services: payments from terminal
Nia's order A-17, at the counter:
log counter A-17 for Nia #1 journey_started order, price, discount, card, giftCard
log counter A-17 for Nia #2 attempt_started lookup, attempt 1
log counter A-17 for Nia #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-17 yet
log counter A-17 for Nia #4 step_succeeded lookup
log counter A-17 for Nia #5 contribution_committed completed
log counter A-17 for Nia #6 hook_called alreadyCompleted: on step success of lookup
log counter A-17 for Nia #7 attempt_started price, attempt 1
log counter A-17 for Nia #8 step_succeeded price
log counter A-17 for Nia #9 contribution_committed amount
log counter A-17 for Nia #10 attempt_started charge, attempt 1
log counter A-17 for Nia #11 service_provided charge gets payments from terminal, a Terminal
the counter's terminal charges 15 for order A-17
log counter A-17 for Nia, receipt C-A-17 #12 global_metadata_set receipt
log counter A-17 for Nia, receipt C-A-17 #13 step_succeeded charge
log counter A-17 for Nia, receipt C-A-17 #14 contribution_committed receipt
log counter A-17 for Nia, receipt C-A-17 #15 hook_called audit: on step success of charge
log counter A-17 for Nia, receipt C-A-17 #16 contribution_committed audit
log counter A-17 for Nia, receipt C-A-17 #17 journey_succeeded
the journey succeeded, with receipt C-A-17
audit: A-17: charge took 15 on attempt 1, receipt C-A-17
Omar's order A-18, at the counter:
log counter A-18 for Omar #1 journey_started order, price, card, giftCard
log counter A-18 for Omar #2 attempt_started lookup, attempt 1
log counter A-18 for Omar #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-18 yet
log counter A-18 for Omar #4 step_succeeded lookup
log counter A-18 for Omar #5 contribution_committed completed
log counter A-18 for Omar #6 hook_called alreadyCompleted: on step success of lookup
log counter A-18 for Omar #7 attempt_started price, attempt 1
log counter A-18 for Omar #8 optional_input_absent discount
log counter A-18 for Omar #9 step_succeeded price
log counter A-18 for Omar #10 contribution_committed amount
log counter A-18 for Omar #11 attempt_started charge, attempt 1
log counter A-18 for Omar #12 service_provided charge gets payments from terminal, a Terminal
the counter's terminal declines card omar-2023: it has expired
log counter A-18 for Omar #13 step_failed charge: card-expired
log counter A-18 for Omar #14 step_given_up charge: failure
log counter A-18 for Omar #15 journey_failed charge
the journey failed: card-expired, hand the card backHow it works
- A step belongs to no workflow.
Lookup,PriceandChargesay what they read and which services they ask for, by key, and how their work went. Nothing in them namesorders, the next step or a policy, so the counter lists them as they are, and they run as they do for a delivered order: Nia's price is 18 less 3, and the charge takes 15. - Each workflow provides its own services. The charge asks for
payments, and gets the bank inordersand the terminal incounter: the listings say so, and so doesservice_provided, Nia's event 11. The counter's receipts start withC, and the charge never knew which client it had. - Each workflow decides its own flow. In
orders, a charge that fails because the card has expired is rescued, as chapter 14 showed. Incounter, it has no rescue step, so the same failure,card-expired, gives the charge up and fails Omar's journey: the customer is standing there, and can hand over another card.counterhas noship, so none of its retry budget or policies, and nooutagepolicy, since the counter's terminal has no network to lose. - Each workflow decides its own policies and reporters.
AuditandAlreadyCompletedare attached in both, andAuditwrites the same audit line.counterlists theLogreporter alone, and no workflow policy, so nobody is told by email: the log's lines start with the workflow's name,counter. - Both workflows live in one program. Each is declared once and checked as its class is defined, as chapter 37 showed: had
counterlistedChargewithout providingpayments,@workflowwould throw aViolationswithservice not providedas the program loads, before any order runs.
A step can now be changed once for every workflow that lists it, which is how the shop wants its coding agents to work: they change its business rules, often in steps. The shop wants to know that such a change leaves every order's flow as a person agreed.
Outcomes
We have shown how one step runs in two workflows, each deciding its own services, flow, policies and reporters.
| The usual way | With Itinera |
|---|---|
| A second sales channel often copies the first one's code, or adds flags to it for the cases that differ. | The second workflow lists the same steps, and declares only what differs. |
| A function reused by a second channel often has to learn which channel called it. | The charge runs unchanged in both workflows, with whichever client each provides. |