Bringing Itinera into existing code
What you want to do
The shop's first checkout, chapter 1's, still takes some of its orders, and it works. You want to bring it into Itinera without stopping it or rewriting it: one piece at a time, keeping the bank's client, the audit trail and the log it already has, with the checkout behaving as before after each move.
The code
The program is chapter 1's checkout. Its payment, which charged the card, renewed an expired one and audited the charge inside one function, is the piece moved first, into a workflow of its own, payment. The bank's client stays as it was. The steps ask for an interface, Payments, written with the two methods the client already has:
/** What the payment's steps ask of the bank. `charge` throws `Declined` when the bank refuses. */
interface Payments {
charge(card: string, amount: number): string;
renewedCard(card: string): string;
}
const PAYMENTS = serviceType<Payments>("Payments");Bank needs no change to serve it: TypeScript checks an object against an interface by the methods it has, not by the interfaces its class names, so the client is a Payments as it stands.
The charge becomes a step, and the renewal its rescue step. The charge no longer renews anything: it catches Declined, the error the bank's client throws when it refuses a charge, whose why says whether the card had expired, and says why it failed.
/** Charges the amount to the card, and gives back the receipt. */
@step()
class Charge extends Step {
constructor(
@input("card", string) private readonly card: string,
@input("amount", integer) private readonly amount: number,
) {
super();
}
override run(
@service("payments", PAYMENTS) payments: Payments,
@contributor() contributor: Contributor,
): Outcome {
let receipt: string;
try {
receipt = payments.charge(this.card, this.amount);
} catch (error) {
if (!(error instanceof Declined)) throw error;
if (error.why === "expired card") return this.fail("card-expired");
return this.fail("declined");
}
contributor.contribute("receipt", receipt);
return this.succeed();
}
}
/** Repairs a charge whose card had expired: it asks the bank for the card that replaced it. */
@rescueStep()
class RenewCard extends RescueStep {
constructor(
@input("card", string) private readonly card: string,
@failureReason() private readonly reason: Reason,
) {
super();
}
override run(
@service("payments", PAYMENTS) payments: Payments,
@contributor() contributor: Contributor,
): RescueOutcome {
if (this.reason.code !== "card-expired") return this.fail("not-repairable");
contributor.contribute("card", payments.renewedCard(this.card));
return this.succeed();
}
}The audit becomes a policy, which writes to the audit trail with the audit.record the checkout already used:
/** Writes every successful charge to the shop's audit trail. */
@stepPolicy({ name: "audit" })
class Audit extends StepPolicy {
@onStepSuccess()
charged(
@fromWorkflow("amount", integer) amount: number,
@fromStep("receipt", string) receipt: string,
): OnSuccess {
audit.record(`charged ${String(amount)}, receipt ${receipt}`);
return this.keepDefault();
}
}The log line the payment wrote becomes a reporter, which writes with the shop's existing log.info:
/** Writes to the shop's log when a step fails, and when a rescue step repairs it. */
class Log implements Reporter {
report(event: Event): void {
if (event.kind === "step_failed") {
log.info(
`payment ${event.journeyId}: ${event.step} failed, ${event.reason.code}`,
);
}
if (event.kind === "step_rescued") {
log.info(
`payment ${event.journeyId}: ${event.step} repaired by ${event.rescue}`,
);
}
}
}The workflow has one step, and its provider makes the bank's client as the checkout did. paid is the shape of its output, and payment the workflow object, made once:
/** Charges an order, renewing a card that has expired, and audits the charge. */
@workflow({ name: "payment", reporters: [Log] })
@withStep(Charge, { name: "charge", rescue: RenewCard, policies: [Audit] })
class Payment 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 it is configured today. */
@provider(PAYMENTS, { key: "payments" })
bank(): Provided<Payments> {
return this.provide(new Bank(2026, 1000));
}
}
/** What a payment gives back: the type of the value under each name. */
const paid = { receipt: string };
const payment = Payment.build();The rest of the checkout is chapter 1's, with four changes. Shop no longer holds the bank. A new error, PaymentNotRun, covers the rest: a journey that ends neither succeeded nor failed becomes an error of the checkout. The line that took the payment now awaits pay. And since pay returns a promise, as every journey's run does, checkout and the method it calls become async:
/** An order, as the shop's website hands it over. */
interface Order {
readonly order: string;
readonly customer: string;
readonly card: string;
readonly price: number;
readonly discount?: number;
readonly weight: number;
}
/** The payment workflow ended without saying how the payment went. */
class PaymentNotRun extends Error {
constructor(why: string) {
super(`the payment did not run: ${why}`);
}
}
/** The shop, with everything it talks to. */
class Shop {
constructor(
private readonly warehouse: Warehouse,
private readonly main: Carrier,
private readonly backup: Carrier,
private readonly messages: Messages,
) {}
/** Reserves, charges and ships an order, and tells the customer how it went. */
async checkout(order: Order): Promise<string> {
log.info(`checkout ${order.order}`);
try {
const tracking = await this.reserveChargeAndShip(order);
this.messages.tell(
order.customer,
`order ${order.order} is on its way: ${tracking}`,
);
return tracking;
} catch (error) {
log.warn(`checkout ${order.order} failed: ${messageOf(error)}`);
this.messages.tell(
order.customer,
`order ${order.order} could not be completed`,
);
throw error;
}
}
private async reserveChargeAndShip(order: Order): Promise<string> {
this.warehouse.reserve(order.order);
const amount = order.price - (order.discount ?? 0);
await this.pay(order.order, order.card, amount);
const tracking = ship(this.main, this.backup, order.order, order.weight);
if (tracking === undefined) throw new Error("no carrier could take it");
return tracking;
}pay runs the workflow, reads how the journey ended as chapter 25 showed, and turns that back into the checkout's own errors:
/** Charges an order's card through the payment workflow, and gives back the receipt. */
private async pay(
order: string,
card: string,
amount: number,
): Promise<string> {
const instance = payment.instance({ order, card, amount });
const result = await new LocalExecutor().run(instance);
if (result.isSucceeded()) return result.output(paid).receipt;
if (result.isFailed()) {
const failure = result.status.failure;
if (
failure.cause === "failure" &&
failure.reason.code === "card-expired"
) {
throw new Declined("expired card");
}
throw new Declined("refused");
}
throw new PaymentNotRun(result.status.kind);
}The orders are chapter 1's four, and the shop is made without the bank. Each checkout is awaited:
const shop = new Shop(
new Warehouse([]),
new Carrier("Rapid", "T", 20),
new Carrier("Steady", "B", 50),
new Messages(),
);
const orders: Order[] = [
{
order: "A-1",
customer: "Ann",
card: "ann-card-2028",
price: 40,
discount: 5,
weight: 2,
},
{
order: "A-2",
customer: "Ben",
card: "ben-card-2024",
price: 25,
weight: 1,
},
{
order: "A-3",
customer: "Cat",
card: "cat-card-2027",
price: 30,
weight: 30,
},
{
order: "A-4",
customer: "Dan",
card: "dan-card-2025",
price: 1200,
weight: 3,
},
];
for (const order of orders) {
try {
console.log(`${order.order}: shipped, ${await shop.checkout(order)}`);
} catch (error) {
console.log(`${order.order}: failed, ${messageOf(error)}`);
}
console.log();
}It prints:
INFO checkout A-1
AUDIT charged 35, receipt R-ann-card-2028-35
to Ann: order A-1 is on its way: T-A-1
A-1: shipped, T-A-1
INFO checkout A-2
INFO payment A-2: charge failed, card-expired
INFO payment A-2: charge repaired by charge_rescue
AUDIT charged 25, receipt R-ben-card-2029-25
to Ben: order A-2 is on its way: T-A-2
A-2: shipped, T-A-2
INFO checkout A-3
AUDIT charged 30, receipt R-cat-card-2027-30
WARN Rapid cannot take A-3: 30 kg is over its 20 kg limit; trying Steady
to Cat: order A-3 is on its way: B-A-3
A-3: shipped, B-A-3
INFO checkout A-4
INFO payment A-4: charge failed, card-expired
INFO payment A-4: charge repaired by charge_rescue
INFO payment A-4: charge failed, declined
WARN checkout A-4 failed: payment declined
to Dan: order A-4 could not be completed
A-4: failed, payment declinedHow it works
- The rest of the program hardly knows.
checkoutgives the same tracking numbers and throws the same errors, the shipping and the messages are untouched, and each order ends as it did in chapter 1. Its callers now await it, the one change the move asks of them.payis the only seam: it creates an instance, runs its journey and reads how it ended. - Existing code is kept, behind the workflow's parts. The bank's client is a service through the interface it already matches, the audit trail is called from a policy, and the log from a reporter. What moves into the workflow is the decisions: when to renew a card, and when to audit. The code that talks to the outside world stays where it was.
- The log now says what happened. Chapter 1's payment logged that it was renewing a card, before it tried. Now the log follows the journey's events: Ben's charge failed with
card-expiredand the rescue step repaired it, and the audit trail shows the charge then went through. Dan's was repaired too, then failed again,declined, which chapter 1's log never said. - One piece at a time. The shipping, with its backup carrier, and the messages to the customer are still chapter 1's code, running beside the workflow. Each can move next: the shipping as a step with a retry budget and a provider for each attempt, the messages as a policy acting through a role. Move one piece, run the program, and compare what it prints with what it printed before.
- Where Itinera fits, and where it doesn't. It fits a piece of business with decisions around it: whether to try again, how to repair, what to record and whom to tell. A single call with nothing to decide around it, such as reserving the goods here, gains nothing from a workflow of its own. It stays a call, or becomes a step of a workflow that has decisions to make.
The checkout's payment is now a workflow, and the shop has one way to charge a card. It also wants a second way to sell: customers collecting their orders at the shop's counter, paying at the counter's terminal, with nothing to ship.
Outcomes
We have shown how to bring Itinera into code that already works, one piece at a time, keeping the code that talks to the outside world.
| The usual way | With Itinera |
|---|---|
| Untangling a function often means rewriting it, and its callers, in one go. | One piece becomes a workflow behind a method the callers already call, now awaited. |
| A client, a log or an audit trail written for the old code is often rewritten for the new. | Each stays, served to the steps through an interface it already matches, or called from a policy or a reporter. |