# Running many journeys

## What you want to do

Orders come in all day, and the shop shouldn't make a new executor for each one. You want one executor that runs every order of the day, one journey after another, each starting from its own order and nothing else.

## The code

The shop is [chapter 23](https://itinera-dev.org/book/typescript/23-undoing-a-charge-when-the-shipping-fails.md)'s, except that its output no longer holds the refund, which the program no longer prints. The program now makes one executor before the loop, and hands it each order's instance in turn:

TypeScript, from the program [`ch24_one_executor_for_every_order`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch24_one_executor_for_every_order.ts)

```typescript
/**
 * 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("email");
const executor = new LocalExecutor();
// The order, the customer, the price, the discount when there is one, the
// parcel, the card, and whether the order is a gift card.
const orders = [
  {
    order: "A-1",
    customer: "Ann",
    price: 40,
    discount: 10,
    parcel: { weight: 2, size: [30, 20, 10] },
    card: "ann-2028",
    giftCard: false,
  },
  {
    order: "A-7",
    customer: "Gil",
    price: 45,
    parcel: { weight: 60, size: [120, 80, 60] },
    card: "gil-2027",
    giftCard: false,
  },
  {
    order: "A-8",
    customer: "Jo",
    price: 30,
    parcel: { weight: 1, size: [20, 15, 5] },
    card: "jo-2024",
    giftCard: false,
  },
  {
    order: "A-9",
    customer: "Kim",
    price: 25,
    parcel: { weight: 0, size: [0, 0, 0] },
    card: "kim-2027",
    giftCard: true,
  },
  {
    order: "A-10",
    customer: "Lee",
    price: 35,
    parcel: { weight: 3, size: [40, 30, 20] },
    card: "lee-2019",
    giftCard: false,
  },
];
for (const order of orders) {
  console.log(`${order.customer}'s order:`);
  const result = await executor.run(shop.instance(order));
  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 runs [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md)'s five orders, none of which the order book has completed, and prints:

What `ch24_one_executor_for_every_order` prints, recorded in [`ch24_one_executor_for_every_order.txt`](https://github.com/itinera-dev/book/blob/main/typescript/expected/ch24_one_executor_for_every_order.txt)

```text
Ann's order:
log orders A-1 #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 #2 attempt_started lookup, attempt 1
log orders A-1 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-1 yet
log orders A-1 #4 step_succeeded lookup
log orders A-1 #5 contribution_committed completed
log orders A-1 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 #7 attempt_started price, attempt 1
log orders A-1 #8 step_succeeded price
log orders A-1 #9 contribution_committed amount
log orders A-1 #10 attempt_started charge, attempt 1
log orders A-1 #11 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 main carrier books order A-1
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
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 journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 30, receipt R-A-1
Gil's order:
log orders A-7 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-7 #2 attempt_started lookup, attempt 1
log orders A-7 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-7 yet
log orders A-7 #4 step_succeeded lookup
log orders A-7 #5 contribution_committed completed
log orders A-7 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-7 #7 attempt_started price, attempt 1
log orders A-7 #8 optional_input_absent discount
log orders A-7 #9 step_succeeded price
log orders A-7 #10 contribution_committed amount
log orders A-7 #11 attempt_started charge, attempt 1
log orders A-7 #12 service_provided charge gets payments from bank, a Bank
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 main carrier books order A-7
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 backup carrier books order A-7
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
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
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, customer, price, parcel, card, giftCard
log orders A-8 #2 attempt_started lookup, attempt 1
log orders A-8 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-8 yet
log orders A-8 #4 step_succeeded lookup
log orders A-8 #5 contribution_committed completed
log orders A-8 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 #7 attempt_started price, attempt 1
log orders A-8 #8 optional_input_absent discount
log orders A-8 #9 step_succeeded price
log orders A-8 #10 contribution_committed amount
log orders A-8 #11 attempt_started charge, attempt 1
log orders A-8 #12 service_provided charge gets payments from bank, a Bank
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 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
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
the main carrier books order A-8
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 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
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, customer, price, parcel, card, giftCard
log orders A-9 #2 attempt_started lookup, attempt 1
log orders A-9 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-9 yet
log orders A-9 #4 step_succeeded lookup
log orders A-9 #5 contribution_committed completed
log orders A-9 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-9 #7 attempt_started price, attempt 1
log orders A-9 #8 optional_input_absent discount
log orders A-9 #9 step_succeeded price
log orders A-9 #10 contribution_committed amount
log orders A-9 #11 attempt_started charge, attempt 1
log orders A-9 #12 service_provided charge gets payments from bank, a Bank
the bank charges 25 for order A-9
log orders A-9 #13 step_succeeded charge
log orders A-9 #14 contribution_committed receipt
log orders A-9 #15 contribution_committed code
log orders A-9 #16 hook_called audit: on step success of charge
log orders A-9 #17 contribution_committed audit
log orders A-9 #18 attempt_started ship, attempt 1
log orders A-9 #19 input_adapter_supplied ship gets weight from parcels
log orders A-9 #20 service_provided ship gets carrier from carriers, a MainCarrier
log orders A-9 #21 step_skipped ship: nothing-to-ship
log orders A-9 #22 contributions_discarded ship
log orders A-9 #23 optional_input_absent tracking
email to Kim: Order A-9 is paid: your gift card's code is G-A-9.
log orders A-9 #24 hook_called notify: on workflow success
log orders A-9 #25 journey_succeeded
the journey succeeded, with receipt R-A-9 and tracking none
audit: charge took 25, receipt R-A-9
Lee's order:
log orders A-10 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-10 #2 attempt_started lookup, attempt 1
log orders A-10 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-10 yet
log orders A-10 #4 step_succeeded lookup
log orders A-10 #5 contribution_committed completed
log orders A-10 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-10 #7 attempt_started price, attempt 1
log orders A-10 #8 optional_input_absent discount
log orders A-10 #9 step_succeeded price
log orders A-10 #10 contribution_committed amount
log orders A-10 #11 attempt_started charge, attempt 1
log orders A-10 #12 service_provided charge gets payments from bank, a Bank
the bank declines card lee-2019: it has expired
log orders A-10 #13 step_failed charge: card-expired
log orders A-10 #14 step_rescuing charge: failure, rescued by charge_rescue
log orders A-10 #15 attempt_started charge_rescue, attempt 1
the bank says nothing replaced card lee-2019
log orders A-10 #16 step_failed charge_rescue: not-replaced
log orders A-10 #17 step_given_up charge_rescue: failure
email to Lee: Sorry, order A-10 could not be completed.
log orders A-10 #18 hook_called notify: on workflow failure
log orders A-10 #19 journey_failed charge_rescue
desk: order A-10 failed at charge_rescue
the journey failed, with receipt none and tracking none
audit: none
```

An instance runs one journey and no more, and an executor runs one journey at a time. TypeScript can't see either mistake when it compiles the program, so the executor checks both when the program runs. The next program has [chapter 5](https://itinera-dev.org/book/typescript/05-a-first-journey.md)'s shop, which only charges, with [chapter 4](https://itinera-dev.org/book/typescript/04-a-first-step.md)'s charge. It hands one executor Ann's instance twice, then Cat's while Ben's journey is still running. `said` awaits each run, and says how its journey ended, or why the run was refused:

TypeScript, from the program [`ch24_runs_refused`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch24_runs_refused.ts)

```typescript
/** Says how a run went: how its journey ended, or why it was refused. */
async function said(run: Promise<JourneyResult>): Promise<string> {
  try {
    const result = await run;
    return `the journey ${result.status.kind}`;
  } catch (error) {
    if (!(error instanceof Refusal)) throw error;
    return `refused (${error.refused.kind}): ${error.message}`;
  }
}

const shop = Orders.build();
const executor = new LocalExecutor();

const ann = shop.instance({ price: 40 });
console.log(`Ann's order: ${await said(executor.run(ann))}`);
console.log(`Ann's order again: ${await said(executor.run(ann))}`);

const ben = executor.run(shop.instance({ price: 25 }));
const cat = executor.run(shop.instance({ price: 30 }));
console.log(`Cat's order, while Ben's runs: ${await said(cat)}`);
console.log(`Ben's order: ${await said(ben)}`);
```

It prints:

What `ch24_runs_refused` prints, recorded in [`ch24_runs_refused.txt`](https://github.com/itinera-dev/book/blob/main/typescript/expected/ch24_runs_refused.txt)

```text
the bank charges 40
Ann's order: the journey succeeded
Ann's order again: refused (instance ran): run refused an instance that already ran: make an instance for each journey
Cat's order, while Ben's runs: refused (journey running): run refused an instance while the executor runs a journey: wait for it, or run on another executor
the bank charges 25
Ben's order: the journey succeeded
```

## How it works

1. **An executor keeps nothing between journeys.** The local executor runs a journey while the promise its `run` returns is pending, and saves nothing: the journey lives only until that promise settles. Then nothing of that journey remains in the executor, so the next journey starts from its own order alone. Gil's shipping needed the backup carrier and Jo's card was replaced, yet Kim's journey, run next by the same executor, starts like every other: `journey_started` with Kim's data, the lookup's first attempt, and the bank made anew for Kim's charge, as `service_provided` shows. Its log starts again at `#1`, since an event's sequence number counts the events of its own journey, never those of the journeys before it. **What one journey did never reaches another through the executor.**
2. **The loop still creates an instance for every order.** An instance is made for one journey, and runs once, as [chapter 5](https://itinera-dev.org/book/typescript/05-a-first-journey.md) showed. Handing it to `run` a second time is refused: the promise rejects with a `Refusal`, from `itinera/executor`, an `Error` whose `refused.kind` says why, here `instance ran`, and whose message says what to do instead. No journey starts, so the bank charges Ann only once. To run an order again, for example after the customer has corrected it, create a new instance with the corrected data.
3. **An executor runs one journey at a time.** Ben's journey was still running when Cat's instance was handed over, so that run was refused with `journey running`, and Ben's journey went on to succeed. That is why the shop's loop awaits each journey before it hands over the next order. **These two refusals are mistakes in the program, found when it runs:** neither is an answer of the business, so the shop's loop doesn't catch them, and one there would end the program at its `await`.

The executor now runs every order. But for Lee's order, the program learns only that the journey failed. The log shows why, line by line, but the code that runs the shop has only the result, and reads from it only how the journey ended and its output.

## Outcomes

We have shown how one executor runs every order of the day, each journey starting from its own data.

| The usual way                                                                                                                               | With Itinera                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Code that handles many requests often keeps state between them, in a cache or a field, and a request can be affected by the ones before it. | The executor keeps nothing between journeys: each starts from its own order, with services made for it.                      |
| Running the same request twice by mistake often goes unnoticed, until a customer is charged twice.                                          | The executor refuses an instance it has run before, with a `Refusal` saying why, so an instance never runs a second journey. |
