Trying again
What you want to do
A carrier that won't collect a parcel may collect it on another try, a booking system that failed may work a moment later, and a declined card may go through on a second try, so you want the shipping and the charge tried once more before an order is given up. But when the bank's network fails while charging, the bank may already have taken the money, so you want that charge never tried again.
The code
The bank and the carrier now throw an error of the program's own when something goes wrong on their side, NetworkDown for the bank and BookingFailed for the carrier; their tokens, PAYMENTS and CARRIER, are chapter 7's. The bank also charges a card now, and gives back undefined when it declines one.
/**
* A payment client: it charges an order's amount to a card, and gives back a
* receipt, or `undefined` when the card has expired. It throws `NetworkDown`
* when its network fails.
*/
interface Payments {
charge(order: string, card: string, amount: number): string | undefined;
}
/**
* A carrier: it books a parcel of this weight in kg and gives back its
* tracking number, or throws `BookingFailed` when its booking system fails,
* then says whether it collects the parcel.
*/
interface Carrier {
book(order: string, weight: number): string;
collects(weight: number): boolean;
}Each error extends Error, with a message that says what failed:
/** The error of the bank's network when it fails. */
class NetworkDown extends Error {
constructor() {
super("the payment network is down");
}
}
/** The error of the carrier's booking system when it fails. */
class BookingFailed extends Error {
constructor() {
super("the booking system failed");
}
}The faked bank's network fails on any amount over 100, and the carrier's booking system on any parcel over 100 kg. The charge charges the order's card, and fails with card-expired when the bank declines it. Nothing in it catches what payments.charge(...) throws, so the bank's error escapes run.
/**
* Charges an order's price to its card through the payment client, and gives
* back its receipt.
*/
@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,
) {
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);
return this.succeed();
}
}The shipping is chapter 9's, now giving the carrier the parcel's weight, and it catches nothing either.
/**
* Ships an order through the carrier, with its receipt in the parcel, gives
* back its tracking number, and says when the parcel has left. A parcel the
* carrier won't collect may be taken on another attempt.
*/
@step()
class Ship extends Step {
constructor(
@input("order", string) private readonly order: string,
@input("weight", integer) private readonly weight: number,
@input("receipt", string) private readonly receipt: string,
) {
super();
}
override async run(
@service("carrier", CARRIER) carrier: Carrier,
@contributor() contributor: Contributor,
@stepReporter() reporter: StepReporter,
): Promise<Outcome> {
const tracking = carrier.book(this.order, this.weight);
contributor.contribute("tracking", tracking);
if (!carrier.collects(this.weight)) return this.fail("too-heavy");
await reporter.info(`the parcel leaves with receipt ${this.receipt}`);
return this.succeed();
}
}The workflow gives both steps a retry budget of 1, with retryBudget: 1 in their @withStep options, and turns off retries for the charge's errors with noRetryOnAbnormalTermination: true. The bank's provider now gives the bank the year, 2026; the ID generator and the carrier's provider are chapter 11's.
/**
* The shop's workflow: it charges, then ships, and each may be tried once
* more, except a charge that ended in an error.
*/
@workflow({ name: "orders", reporters: [Log, Desk] })
@withStep(Charge, {
name: "charge",
retryBudget: 1,
noRetryOnAbnormalTermination: true,
})
@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));
}
/** The main carrier, as the carrier of the journey. */
@provider(CARRIER, { key: "carrier" })
mainCarrier(): Provided<Carrier> {
return this.provide(new MainCarrier(20));
}
}The log and the desk are chapter 11's; the log now also names each attempt, the error that ended one, and why a step was given up:
/**
* What the log says after an event's kind, for the kinds it says more about:
* the step the event is about, and what it names.
*/
function detail(event: Event): string | undefined {
switch (event.kind) {
case "journey_started":
return event.initialKeys.join(", ");
case "attempt_started":
return `${event.step}, attempt ${String(event.attempt)}`;
case "step_succeeded":
case "step_retrying":
return event.step;
case "service_provided":
return `${event.step} gets ${event.key} from ${event.provider}, a ${event.implementation}`;
case "step_failed":
return `${event.step}: ${event.reason.code}`;
case "step_abnormal_termination":
return `${event.step}: ${event.errorMessage}`;
case "step_given_up":
return `${event.step}: ${event.cause}`;
case "contribution_committed":
return event.key;
case "journey_failed":
return event.step;
case "step_info":
return `${event.step}: ${event.message}`;
default:
return undefined;
}
}Each order's data now holds its card, and the receipt read back may be missing. The shop runs Ann's and Gil's orders, and three from new customers: Jo, whose card expired in 2024, Cat, who spends 120, and Dan, whose parcel weighs 150 kg.
/**
* 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) };
const shop = Orders.build();
// The order, the customer, the price, the parcel's weight in kg and the card.
const orders = [
{ order: "A-1", customer: "Ann", price: 40, weight: 2, card: "ann-2028" },
{ order: "A-7", customer: "Gil", price: 45, weight: 60, card: "gil-2027" },
{ order: "A-8", customer: "Jo", price: 30, weight: 1, card: "jo-2024" },
{ order: "A-3", customer: "Cat", price: 120, weight: 3, card: "cat-2027" },
{ order: "A-4", customer: "Dan", price: 50, weight: 150, card: "dan-2028" },
];
for (const { order, customer, price, weight, card } of orders) {
console.log(`${customer}'s order:`);
const instance = shop.instance({ order, price, weight, card });
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}`,
);
}It prints:
Ann's order:
log orders A-1 #1 journey_started order, price, weight, card
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 attempt_started ship, attempt 1
log orders A-1 #7 service_provided ship gets carrier from mainCarrier, a MainCarrier
the carrier books order A-1
log orders A-1 #8 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #9 step_succeeded ship
log orders A-1 #10 contribution_committed tracking
log orders A-1 #11 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
Gil's order:
log orders A-7 #1 journey_started order, price, weight, card
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 attempt_started ship, attempt 1
log orders A-7 #7 service_provided ship gets carrier from mainCarrier, a MainCarrier
the carrier books order A-7
log orders A-7 #8 step_failed ship: too-heavy
log orders A-7 #9 step_retrying ship
log orders A-7 #10 attempt_started ship, attempt 2
the carrier books order A-7
log orders A-7 #11 step_failed ship: too-heavy
log orders A-7 #12 step_given_up ship: retries exhausted
log orders A-7 #13 journey_failed ship
desk: order A-7 failed at ship
the journey failed, with receipt R-A-7 and tracking none
Jo's order:
log orders A-8 #1 journey_started order, price, weight, card
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_retrying charge
log orders A-8 #6 attempt_started charge, attempt 2
the bank declines card jo-2024: it has expired
log orders A-8 #7 step_failed charge: card-expired
log orders A-8 #8 step_given_up charge: retries exhausted
log orders A-8 #9 journey_failed charge
desk: order A-8 failed at charge
the journey failed, with receipt none and tracking none
Cat's order:
log orders A-3 #1 journey_started order, price, weight, card
log orders A-3 #2 attempt_started charge, attempt 1
log orders A-3 #3 service_provided charge gets payments from bank, a Bank
the bank's network fails while charging order A-3
log orders A-3 #4 step_abnormal_termination charge: the payment network is down
log orders A-3 #5 step_given_up charge: abnormal termination
log orders A-3 #6 journey_failed charge
desk: order A-3 failed at charge
the journey failed, with receipt none and tracking none
Dan's order:
log orders A-4 #1 journey_started order, price, weight, card
log orders A-4 #2 attempt_started charge, attempt 1
log orders A-4 #3 service_provided charge gets payments from bank, a Bank
the bank charges 50 for order A-4
log orders A-4 #4 step_succeeded charge
log orders A-4 #5 contribution_committed receipt
log orders A-4 #6 attempt_started ship, attempt 1
log orders A-4 #7 service_provided ship gets carrier from mainCarrier, a MainCarrier
the carrier's booking system fails on order A-4
log orders A-4 #8 step_abnormal_termination ship: the booking system failed
log orders A-4 #9 step_retrying ship
log orders A-4 #10 attempt_started ship, attempt 2
the carrier's booking system fails on order A-4
log orders A-4 #11 step_abnormal_termination ship: the booking system failed
log orders A-4 #12 step_given_up ship: retries exhausted
log orders A-4 #13 journey_failed ship
desk: order A-4 failed at ship
the journey failed, with receipt R-A-4 and tracking noneA step can't count its attempts on its class, so this shipping step doesn't compile:
// A shipping step that counts its attempts in a static field of its class.
import { LocalExecutor } from "itinera/executor";
import { type Outcome, Step, step } from "itinera/step";
import { withStep, Workflow, workflow } from "itinera/workflow";
/** Ships an order, and fails its first attempt, counting attempts on its class. */
@step()
class Ship extends Step {
static attempts = 0;
override run(): Outcome {
Ship.attempts += 1;
return Ship.attempts === 1 ? this.fail("carrier-refused") : this.succeed();
}
}
/** The shop's workflow. */
@workflow({ name: "orders" })
@withStep(Ship, { name: "shipping", retryBudget: 1 })
class Orders extends Workflow {}
const result = await new LocalExecutor().run(Orders.build().instance());
console.log(`the journey ${result.status.kind}`);compile-errors/ch12_step_keeps_static_data.ts(8,2): error TS1238: Unable to resolve signature of class decorator when called as an expression.
Argument of type 'typeof Ship' is not assignable to parameter of type 'WithoutStaticData<typeof Ship, typeof Step>'.
Type 'typeof Ship' is not assignable to type '{ readonly attempts: never; }'.
Types of property 'attempts' are incompatible.
Type 'number' is not assignable to type 'never'.How it works
- Attempts count from 1. An attempt is one run of a step, and every attempt after the first is a retry. Every event of an attempt, such as
step_retrying, carries it asevent.attempt, anAttemptfromitinera/step. Each attempt builds the step afresh from the data bag, and what a failed attempt contributed is never committed, as chapter 6 showed, so Gil's journey ends with no tracking number. - An error that escapes is an abnormal termination. A failure, such as
card-expired, is an outcome the step chose. A throw out ofrun, or a promise fromrunthat rejects, is an error the step didn't handle. It ends the attempt as a failure of another kind, an abnormal termination, recorded asstep_abnormal_terminationwith the error's message, and never aborts the journey. - The retry budget alone decides whether a step is tried again. It is the number of retries the workflow allows a step, declared on its
@withStepline, 0 by default. While a retry is left, a step that failed is tried again, recorded asstep_retrying: Gil's shipping and Jo's charge each get attempt 2. A step reports what happened; the workflow decides whether it is tried again. - An abnormal termination spends the same budget. Dan's booking failed with an error, so the shipping was retried just as Gil's was, and failed again with the same parcel.
- The workflow can turn that off for a step.
noRetryOnAbnormalTermination: trueon the charge's line says an error must never be retried there, since the bank may already have taken the money. Cat's charge ended in an error, and was given up at once with the causeabnormal termination, though a retry was left. Jo's failure, which is not an error, was retried. - When the budget is spent, the step is given up. Gil's, Jo's and Dan's steps each failed again with no retry left, and were given up with the cause
retries exhausted. The executor never waits between attempts. - Every throw is caught. JavaScript has no failure code can't catch, so Itinera catches them all: a mistake in
run, such as reading a property ofundefined, is an abnormal termination just as the bank's error is. Return an outcome for anything an order can bring. - A step keeps nothing on its class. A static field holding data would be shared by every attempt of every journey, so Itinera refuses one: the step above doesn't compile, and a
private staticfield is refused as the program loads. A static method is fine.
Look at Gil's second attempt. There is no service_provided before it: the main carrier was made once for the journey, as chapter 7 showed, so the second attempt got the same carrier, which refused the same parcel again. The shop has a backup carrier, which collects parcels up to 80 kg, but no attempt is ever offered it.
Outcomes
We have shown how the workflow decides, step by step, whether a step that failed is tried again.
| The usual way | With Itinera |
|---|---|
| A retry is often a loop around a call, written where the call is, so how often something is tried, and which errors are safe to try again, is decided in many places. | Every step's retry budget, and whether its errors are retried, is declared on its line in the workflow. |
| Whether a failure was retried, and why it was finally given up, is usually known only to the loop that did it. | Every retry and every give-up is an event the executor records, with its cause, after the failure it answers. |