The Itinera bookTypeScript edition

Part 4: Running it for real, Chapter 26

Running async journeys while others wait

What you want to do

The shop's bank and carriers answer over the network, and while one order waits for them, the shop waits too, though it could take other orders forward in the meantime. You want the shop to run several orders at once, each going on while the others wait.

The code

The shop is chapter 25's, with the bank and the carriers answering asynchronously. Itinera's TypeScript executor is asynchronous, and accepts steps and hooks in either execution mode, synchronous or asynchronous: as chapter 9 showed, a step's run may return its outcome or a promise of it, and the executor waits for whichever it gets. So nothing needs to be turned on: Node's own event loop runs the promises.

The payment client and the carrier now return promises, and reject with chapter 12's errors; their tokens are chapter 7's. The order book of chapter 22 answers from the shop's own records without waiting, so it stays synchronous, as any service or role that doesn't wait may:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
/**
 * 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 rejects with
 * `NetworkDown` when its network fails. And it says which card replaced one,
 * if any did. Each answer comes over the network.
 */
interface Payments {
  charge(
    order: string,
    card: string,
    amount: number,
  ): Promise<string | undefined>;
  replacement(card: string): Promise<string | undefined>;
}

/**
 * A carrier: it books a parcel of this weight in kg and gives back its
 * tracking number, or rejects with `BookingFailed` when its booking system
 * fails, then says whether it collects the parcel. Each answer comes over the
 * network.
 */
interface Carrier {
  book(order: string, weight: number): Promise<string>;
  collects(weight: number): Promise<boolean>;
}

The faked bank and carriers await network before each answer. It waits for one turn of Node's event loop, with setImmediate from node:timers/promises, as a real call waits for the other side. No clock is involved, so the answers come in the order they were asked for:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
/**
 * The network the fakes answer over: it waits for one turn of Node's event
 * loop before the answer comes, as a real call waits for the other side.
 */
function network(): Promise<void> {
  return setImmediate();
}

/**
 * The shop's bank, faked: a card is its holder's name and the year it
 * expires, and the bank declines a card that expired before this year. Its
 * network fails on any amount over 100. It prints what it does once it has
 * answered.
 */
class Bank implements Payments {
  constructor(private readonly thisYear: number) {}

  async charge(
    order: string,
    card: string,
    amount: number,
  ): Promise<string | undefined> {
    await network();
    if (amount > 100) {
      console.log(`the bank's network fails while charging order ${order}`);
      throw new NetworkDown();
    }
    if (expiry(card) < this.thisYear) {
      console.log(`the bank declines card ${card}: it has expired`);
      return undefined;
    }
    console.log(`the bank charges ${String(amount)} for order ${order}`);
    return `R-${order}`;
  }

  /**
   * A card that expired in the last three years was replaced by its holder's
   * card that expires in three years. An older one was not.
   */
  async replacement(card: string): Promise<string | undefined> {
    await network();
    if (expiry(card) + 3 < this.thisYear) {
      console.log(`the bank says nothing replaced card ${card}`);
      return undefined;
    }
    const holder = card.slice(0, card.lastIndexOf("-"));
    const replacement = `${holder}-${String(this.thisYear + 3)}`;
    console.log(`the bank says card ${card} was replaced by ${replacement}`);
    return replacement;
  }
}

The charge and its rescue step now await the bank, so their run becomes async, returning a promise of their outcome:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
/**
 * Charges an order's amount 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("amount", integer) private readonly amount: number,
    @input("card", string) private readonly card: string,
    @input("giftCard", boolean) private readonly giftCard: boolean,
  ) {
    super();
  }

  override async run(
    @service("payments", PAYMENTS) payments: Payments,
    @contributor() contributor: Contributor,
  ): Promise<Outcome> {
    if (this.amount <= 0) return this.fail("nothing-to-charge");
    const receipt = await payments.charge(this.order, this.card, this.amount);
    if (receipt === undefined) return this.fail("card-expired");
    contributor.contribute("receipt", receipt);
    if (this.giftCard) contributor.contribute("code", `G-${this.order}`);
    return this.succeed();
  }
}

/**
 * Repairs a charge that failed because its card had expired: it asks the bank
 * for the card that replaced it, and gives it back as the order's card.
 */
@rescueStep()
class RenewCard extends RescueStep {
  constructor(
    @input("card", string) private readonly card: string,
    @failureReason() private readonly reason: Reason,
  ) {
    super();
  }

  override async run(
    @service("payments", PAYMENTS) payments: Payments,
    @contributor() contributor: Contributor,
  ): Promise<RescueOutcome> {
    if (this.reason.code !== "card-expired") {
      return this.fail("not-repairable");
    }
    const card = await payments.replacement(this.card);
    if (card === undefined) return this.fail("not-replaced");
    contributor.contribute("card", card);
    return this.succeed();
  }
}

The shipping's run was already async, for its step reporter. It now awaits the carrier too:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
/**
 * 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. A gift card has
 * nothing to ship, and the shop ships no parcel over 80 kg.
 */
@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,
    @input("giftCard", boolean) private readonly giftCard: boolean,
  ) {
    super();
  }

  override async run(
    @service("carrier", CARRIER) carrier: Carrier,
    @contributor() contributor: Contributor,
    @stepReporter() reporter: StepReporter,
  ): Promise<Outcome> {
    if (this.giftCard) return this.skipBecause("nothing-to-ship");
    if (this.weight > 80) return this.fail("over-parcel-limit");
    const tracking = await carrier.book(this.order, this.weight);
    contributor.contribute("tracking", tracking);
    if (!(await carrier.collects(this.weight))) return this.fail("too-heavy");
    await reporter.info(`the parcel leaves with receipt ${this.receipt}`);
    return this.succeed();
  }
}

Telling a customer and giving money back go over the network too, so the shop's roles return promises the same way:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
/** What the shop does for its policies: tell a customer something. */
interface Messages {
  tell(customer: string, message: string): Promise<void>;
}

/** What the shop does for its policies: give an order's money back. */
interface Refunds {
  refund(receipt: string, amount: number): Promise<void>;
}

The workflow's implementations of them await network before they answer. The rest of the workflow class is chapter 23's:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
async tell(customer: string, message: string): Promise<void> {
  await network();
  console.log(`${this.channel} to ${customer}: ${message}`);
}

async refund(receipt: string, amount: number): Promise<void> {
  await network();
  console.log(`the bank gives ${String(amount)} back on receipt ${receipt}`);
}

The hooks that call a role become async as well, and await it: Notify's two hooks, which now return a promise of nothing, and FailedShipping's, which return a promise of their decision. refund, which calls the role, becomes async too:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
/** Tells the customer how their order went, once its journey has ended. */
@workflowPolicy({ name: "notify" })
class Notify extends WorkflowPolicy<Messages> {
  @onWorkflowSuccess()
  async succeeded(
    @fromWorkflow("customer", string) customer: string,
    @fromWorkflow("order", string) order: string,
    @fromWorkflow("tracking", optional(string)) tracking: Option<string>,
    @fromWorkflow("code", optional(string)) code: Option<string>,
    @role<Messages>() messages: Messages,
  ): Promise<void> {
    let message = `Order ${order} is complete.`;
    if (tracking.isSome()) {
      message = `Order ${order} is on its way, tracking ${tracking.value}.`;
    } else if (code.isSome()) {
      message = `Order ${order} is paid: your gift card's code is ${code.value}.`;
    }
    await messages.tell(customer, message);
  }

  @onWorkflowFailure()
  async failed(
    @fromWorkflow("customer", string) customer: string,
    @fromWorkflow("order", string) order: string,
    @role<Messages>() messages: Messages,
  ): Promise<void> {
    await messages.tell(
      customer,
      `Sorry, order ${order} could not be completed.`,
    );
  }
}
TypeScript, from the program ch26_running_async_journeys_while_others_wait
/**
 * Deals with a shipping that fails for good. It gives up a parcel over the
 * shop's limit rather than try it again, since the limit is the same on every
 * attempt, whichever carrier comes. And whatever gave the shipping up, it
 * refunds the order's charge.
 */
@stepPolicy({ name: "failedShipping" })
class FailedShipping extends StepPolicy<Refunds> {
  @onStepRetry()
  async beforeRetrying(
    @failureReason({ optional: true }) reason: Option<Reason>,
    @fromWorkflow("receipt", string) receipt: string,
    @fromWorkflow("amount", integer) amount: number,
    @role<Refunds>() refunds: Refunds,
    @contributor() contributor: Contributor,
  ): Promise<OnFailure> {
    if (reason.isSome() && reason.value.code === "over-parcel-limit") {
      await this.refund(
        refunds,
        contributor,
        receipt,
        amount,
        "over-parcel-limit",
      );
      return this.failWorkflow("no-carrier-can-take-it");
    }
    return this.keepDefault();
  }

  @onStepFailure()
  async givenUp(
    @failureCause() cause: StepFailureCause,
    @fromWorkflow("receipt", string) receipt: string,
    @fromWorkflow("amount", integer) amount: number,
    @role<Refunds>() refunds: Refunds,
    @contributor() contributor: Contributor,
  ): Promise<OnFailure> {
    await this.refund(refunds, contributor, receipt, amount, cause);
    return this.keepDefault();
  }

  /** Gives the order's money back, and records why. */
  private async refund(
    refunds: Refunds,
    contributor: Contributor,
    receipt: string,
    amount: number,
    why: string,
  ): Promise<void> {
    await refunds.refund(receipt, amount);
    contributor.contribute(
      "refund",
      `${String(amount)} back on ${receipt}: ${why}`,
    );
  }
}

The program runs three of the day's orders, Ann's, Gil's and Jo's, at the same time. journey runs an instance with an executor of its own; WorkflowInstance, from itinera/instance, is the type of what instance(...) makes, here for Orders. Promise.all waits for the three journeys together, and gives their results in the order it was given them. It then prints each result's journeyId, which a result carries as events do, and how it ended:

TypeScript, from the program ch26_running_async_journeys_while_others_wait
/** Runs an order's journey with an executor of its own. */
function journey(instance: WorkflowInstance<Orders>): Promise<JourneyResult> {
  return new LocalExecutor().run(instance);
}

const shop = Orders.build("email");
const results = await Promise.all([
  journey(
    shop.instance({
      order: "A-1",
      customer: "Ann",
      price: 40,
      discount: 10,
      parcel: { weight: 2, size: [30, 20, 10] },
      card: "ann-2028",
      giftCard: false,
    }),
  ),
  journey(
    shop.instance({
      order: "A-7",
      customer: "Gil",
      price: 45,
      parcel: { weight: 60, size: [120, 80, 60] },
      card: "gil-2027",
      giftCard: false,
    }),
  ),
  journey(
    shop.instance({
      order: "A-8",
      customer: "Jo",
      price: 30,
      parcel: { weight: 1, size: [20, 15, 5] },
      card: "jo-2024",
      giftCard: false,
    }),
  ),
]);
for (const result of results) {
  console.log(`order ${result.journeyId} ${result.status.kind}`);
}

It prints:

What ch26_running_async_journeys_while_others_wait prints, recorded in ch26_running_async_journeys_while_others_wait.txt
log orders A-1 #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-7 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-1 #2 attempt_started lookup, attempt 1
log orders A-7 #2 attempt_started lookup, attempt 1
log orders A-8 #2 attempt_started lookup, attempt 1
log orders A-1 #3 service_provided lookup gets orderBook from ledger, a Ledger
log orders A-7 #3 service_provided lookup gets orderBook from ledger, a Ledger
log orders A-8 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-1 yet
the order book has no order A-7 yet
the order book has no order A-8 yet
log orders A-1 #4 step_succeeded lookup
log orders A-7 #4 step_succeeded lookup
log orders A-8 #4 step_succeeded lookup
log orders A-1 #5 contribution_committed completed
log orders A-7 #5 contribution_committed completed
log orders A-8 #5 contribution_committed completed
log orders A-1 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-7 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 #7 attempt_started price, attempt 1
log orders A-7 #7 attempt_started price, attempt 1
log orders A-8 #7 attempt_started price, attempt 1
log orders A-7 #8 optional_input_absent discount
log orders A-8 #8 optional_input_absent discount
log orders A-1 #8 step_succeeded price
log orders A-7 #9 step_succeeded price
log orders A-8 #9 step_succeeded price
log orders A-1 #9 contribution_committed amount
log orders A-7 #10 contribution_committed amount
log orders A-8 #10 contribution_committed amount
log orders A-1 #10 attempt_started charge, attempt 1
log orders A-7 #11 attempt_started charge, attempt 1
log orders A-8 #11 attempt_started charge, attempt 1
log orders A-1 #11 service_provided charge gets payments from bank, a Bank
log orders A-7 #12 service_provided charge gets payments from bank, a Bank
log orders A-8 #12 service_provided charge gets payments from bank, a Bank
the bank charges 30 for order A-1
log orders A-1 #12 step_succeeded charge
log orders A-1 #13 contribution_committed receipt
log orders A-1 #14 hook_called audit: on step success of charge
log orders A-1 #15 contribution_committed audit
log orders A-1 #16 attempt_started ship, attempt 1
log orders A-1 #17 input_adapter_supplied ship gets weight from parcels
log orders A-1 #18 service_provided ship gets carrier from carriers, a MainCarrier
the bank charges 45 for order A-7
log orders A-7 #13 step_succeeded charge
log orders A-7 #14 contribution_committed receipt
log orders A-7 #15 hook_called audit: on step success of charge
log orders A-7 #16 contribution_committed audit
log orders A-7 #17 attempt_started ship, attempt 1
log orders A-7 #18 input_adapter_supplied ship gets weight from parcels
log orders A-7 #19 service_provided ship gets carrier from carriers, a MainCarrier
the bank declines card jo-2024: it has expired
log orders A-8 #13 step_failed charge: card-expired
log orders A-8 #14 step_rescuing charge: failure, rescued by charge_rescue
log orders A-8 #15 attempt_started charge_rescue, attempt 1
the main carrier books order A-1
the main carrier books order A-7
the bank says card jo-2024 was replaced by jo-2029
log orders A-8 #16 step_succeeded charge_rescue
log orders A-8 #17 contribution_committed card
log orders A-8 #18 data_overwritten card
log orders A-8 #19 step_rescued charge by charge_rescue
log orders A-8 #20 attempt_started charge, attempt 2
log orders A-1 #19 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #20 step_succeeded ship
log orders A-1 #21 contribution_committed tracking
log orders A-1 #22 optional_input_absent code
log orders A-7 #20 step_failed ship: too-heavy
log orders A-7 #21 hook_called failedShipping: on step retry of ship
log orders A-7 #22 step_retrying ship
log orders A-7 #23 attempt_started ship, attempt 2
log orders A-7 #24 input_adapter_supplied ship gets weight from parcels
log orders A-7 #25 service_provided ship gets carrier from carriers, a BackupCarrier
the bank charges 30 for order A-8
log orders A-8 #21 step_succeeded charge
log orders A-8 #22 contribution_committed receipt
log orders A-8 #23 hook_called audit: on step success of charge
log orders A-8 #24 contribution_committed audit
log orders A-8 #25 attempt_started ship, attempt 1
log orders A-8 #26 input_adapter_supplied ship gets weight from parcels
log orders A-8 #27 service_provided ship gets carrier from carriers, a MainCarrier
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 #23 hook_called notify: on workflow success
log orders A-1 #24 journey_succeeded
the backup carrier books order A-7
the main carrier books order A-8
log orders A-7 #26 step_info ship: the parcel leaves with receipt R-A-7
log orders A-7 #27 step_succeeded ship
log orders A-7 #28 contribution_committed tracking
log orders A-7 #29 optional_input_absent code
log orders A-8 #28 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 #29 step_succeeded ship
log orders A-8 #30 contribution_committed tracking
log orders A-8 #31 optional_input_absent code
email to Gil: Order A-7 is on its way, tracking B-A-7.
log orders A-7 #30 hook_called notify: on workflow success
log orders A-7 #31 journey_succeeded
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 #32 hook_called notify: on workflow success
log orders A-8 #33 journey_succeeded
order A-1 succeeded
order A-7 succeeded
order A-8 succeeded

How it works

  1. Only what waits changes. The charge, its rescue step, the shipping and the hooks that call a role await what they call, so they are async. The rest waits for nothing, and stays as it was: the lookup and AlreadyCompleted as chapter 22 shows them, the pricing and the audit as chapter 20 does, and Outage as chapter 17 does. The workflow's declaration, its input adapter, its ID generator and its providers don't change, nor do the log, as chapter 22 shows it, and the desk, as chapter 11 does.
  2. Each step and each hook has its own execution mode. There is no mode to choose for the workflow, or for the executor: the executor waits for whatever a step's run or a hook returns, a value or a promise of it, so the same journey runs synchronous and asynchronous steps alike. The journeys end as they did in chapter 25: Gil's parcel goes with the backup carrier, and Jo's card is renewed.
  3. A journey that waits lets the others go on. The executor awaits everything it calls, reporters, steps and hooks alike, even one that answers at once, so from their first events the three journeys take turns: Ann's journey_started, then Gil's, then Jo's. Then each answer of the bank or a carrier comes in its turn, and its journey goes on from where it waited, until it waits again. So the log interleaves the three journeys.
  4. The output is the same on every run. Nothing here waits for a clock, so the turns come in the same order each time. Real answers over the network come when they come, and their journeys go on in that order, but each journey's own events keep their order whatever the others do.
  5. An executor runs one journey at a time, as chapter 24 showed, so each journey that runs at the same time as others gets an executor of its own.

Ann's, Gil's and Jo's journeys now go on together, each while the others wait. But the only way to know that the shop still gives the same answers after a change is to run every order again, against the bank and the carriers, and read the log.

Outcomes

We have shown how the shop runs journeys at the same time, each going on while the others wait.

The usual way With Itinera
Making code asynchronous often means changing every function between the request and the call that waits. The services and roles that wait return promises, and the steps and hooks that await them become async; nothing between them and the executor changes, since it waits for whatever each returns.