# 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/java/23-undoing-a-charge-when-the-shipping-fails.md)'s, except that its output no longer holds the refund, which `main` no longer prints:

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

```java
/** What the shop reads back once the journey has ended. */
record Order(Optional<String> receipt, Optional<String> tracking, Optional<String> audit) {}

```

`main` now makes one executor before the loop, and hands it each order's instance in turn:

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

```java
final class Main {
  private Main() {}

  public static void main(String[] args) throws Refusal {
    // Each order: its number, its customer, its price, its discount if it has one, its parcel, as
    // its weight in kg and its size in cm, the card, and whether it is a gift card.
    var orders =
        List.of(
            new NewOrder(
                "A-1",
                "Ann",
                40,
                Optional.of(10L),
                new Parcel(2, List.of(30L, 20L, 10L)),
                "ann-2028",
                false),
            new NewOrder("A-7", "Gil", 45, new Parcel(60, List.of(120L, 80L, 60L)), "gil-2027"),
            new NewOrder("A-8", "Jo", 30, new Parcel(1, List.of(20L, 15L, 5L)), "jo-2024"),
            new NewOrder("A-9", "Kim", 25, new Parcel(0, List.of(0L, 0L, 0L)), "kim-2027", true),
            new NewOrder("A-10", "Lee", 35, new Parcel(3, List.of(40L, 30L, 20L)), "lee-2019"));
    var executor = new LocalExecutor();
    for (var order : orders) {
      System.out.println(order.customer() + "'s order:");
      var instance = new Orders("email").instance().initialData(order).create();
      var result = executor.run(instance);
      var data = result.output(TypeToken.of(Order.class));
      var ended = result.isSucceeded() ? "succeeded" : "failed";
      var receipt = data.receipt().orElse("none");
      var tracking = data.tracking().orElse("none");
      System.out.println(
          "the journey " + ended + ", with receipt " + receipt + " and tracking " + tracking);
      System.out.println("audit: " + data.audit().orElse("none"));
    }
  }
}
```

`NewOrder` and `Parcel` are as [chapter 21](https://itinera-dev.org/book/java/21-deciding-where-a-steps-data-comes-from.md) shows them, and `main` runs that chapter's five orders, none of which the order book has completed. It 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/java/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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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 ch24_one_executor_for_every_order.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. The compiler can't see either mistake, so the executor checks both when the program runs. The next program has [chapter 5](https://itinera-dev.org/book/java/05-a-first-journey.md)'s shop, which only charges, with [chapter 4](https://itinera-dev.org/book/java/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, on a `Thread` of its own. For that, `main` tells the faked bank to hold the next charge, Ben's, until `main` lets it answer, and waits until that charge has started. `said` takes a `Run`, a small interface whose one method runs an instance and may throw a `Refusal`, calls it, and says how its journey ended, or why the run was refused:

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

```java
/** Runs an instance, and gives back its journey's result, unless the run is refused. */
interface Run {
  JourneyResult run() throws Refusal;
}

final class Main {
  private Main() {}

  /** Says how the journey {@code run} runs ended, or why the run was refused. */
  static String said(Run run) {
    try {
      return run.run().isSucceeded() ? "the journey succeeded" : "the journey failed";
    } catch (Refusal refusal) {
      return "refused (" + refusal.getRefused() + "): " + refusal.getMessage();
    }
  }

  public static void main(String[] args) throws InterruptedException {
    var executor = new LocalExecutor();

    var ann = new Orders().instance().data("price", 40L).create();
    System.out.println("Ann's order: " + said(() -> executor.run(ann)));
    System.out.println("Ann's order again: " + said(() -> executor.run(ann)));

    Bank.hold();
    var ben = new Orders().instance().data("price", 25L).create();
    var bens =
        new Thread(() -> System.out.println("Ben's order: " + said(() -> executor.run(ben))));
    bens.start();
    Bank.awaitHeldCharge();
    var cat = new Orders().instance().data("price", 30L).create();
    System.out.println("Cat's order, while Ben's runs: " + said(() -> executor.run(cat)));
    Bank.answer();
    bens.join();
  }
}
```

It prints:

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

```text
the bank charges 40
Ann's order: the journey succeeded
Ann's order again: refused (InstanceRan): run refused an instance handed to an executor before: create an instance for each journey
Cat's order, while Ben's runs: refused (JourneyRunning): 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 inside the call to its `run`, and saves nothing: the journey lives only as long as that call. When `run` returns, 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/java/05-a-first-journey.md) showed. Handing it to `run` a second time is refused: `run` throws a `Refusal`, from `org.itineradev.itinera.executor`, a checked `Exception` whose `getRefused()` says why, here `InstanceRan`, 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.** `run` runs the journey on the thread that called it, and returns only once the journey has ended. Ben's journey was still running when Cat's instance was handed over from `main`'s thread, so that run was refused with `JourneyRunning`, and Ben's journey went on to succeed. That is why the shop's loop waits for 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.

The executor now runs every order. But for Lee's order, `main` 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 static 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. |
