# Trying again

## What you want to do

A carrier that won't collect a parcel today may collect it on another try, a booking system that failed may work a moment later, and a bank that declines a card may accept it 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 say when something went wrong on their side: each throws an exception of the program's own, `NetworkDown` for the bank and `BookingFailed` for the carrier. Both are checked, so every method that may throw one says so.

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

```java
/**
 * A payment client: it charges an order's amount to a card, and gives back a receipt, or nothing
 * when the card has expired.
 */
interface Payments {
  Optional<String> charge(String order, String card, long amount) throws NetworkDown;
}

/**
 * A carrier: it books a parcel of this weight in kg and gives back its tracking number, then says
 * whether it collects the parcel.
 */
interface Carrier {
  String book(String order, long weight) throws BookingFailed;

  boolean collects(long weight);
}

```

Each exception is a class of its own, whose message says what failed, with the `serialVersionUID` that `-Xlint:all` asks of every exception:

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

```java
/** The error of the bank's network when it fails. */
final class NetworkDown extends Exception {
  private static final long serialVersionUID = 1L;

  NetworkDown() {
    super("the payment network is down");
  }
}

/** The error of the carrier's booking system when it fails. */
final class BookingFailed extends Exception {
  private static final long serialVersionUID = 1L;

  BookingFailed() {
    super("the booking system failed");
  }
}

```

The faked bank's network fails on any amount over 100, and the faked 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 by giving back an empty `Optional`. Nothing in `run` catches the bank's exception: `run` declares `throws NetworkDown`, and the exception escapes the step.

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

```java
/** Charges an order's price to its card through the payment client, and gives back its receipt. */
@Step
final class Charge implements ItineraStep {
  private final String order;
  private final long price;
  private final String card;

  Charge(@Input String order, @Input long price, @Input String card) {
    this.order = order;
    this.price = price;
    this.card = card;
  }

  public Outcome run(@Service Payments payments, Contributor contributor) throws NetworkDown {
    if (price <= 0) return fail("nothing-to-charge");
    Optional<String> receipt = payments.charge(order, card, price);
    if (receipt.isEmpty()) return fail("card-expired");
    contributor.contribute("receipt", receipt.orElseThrow());
    return succeed();
  }
}

```

The shipping is [chapter 9](https://itinera-dev.org/book/java/09-saying-what-only-a-step-knows.md)'s, now giving the carrier the parcel's weight, and letting the carrier's exception escape too, with `throws BookingFailed`:

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

```java
/**
 * 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
final class Ship implements ItineraStep {
  private final String order;
  private final long weight;
  private final String receipt;

  Ship(@Input String order, @Input long weight, @Input String receipt) {
    this.order = order;
    this.weight = weight;
    this.receipt = receipt;
  }

  public Outcome run(@Service Carrier carrier, Contributor contributor, StepReporter reporter)
      throws BookingFailed {
    String tracking = carrier.book(order, weight);
    contributor.contribute("tracking", tracking);
    if (!carrier.collects(weight)) return fail("too-heavy");
    reporter.info("the parcel leaves with receipt " + receipt);
    return succeed();
  }
}

```

The workflow gives both steps a **retry budget** of 1, with `retryBudget = 1` in their `@WithStep` annotations, 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](https://itinera-dev.org/book/java/11-naming-a-journey.md)'s.

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

```java
/**
 * 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.class, Desk.class})
@WithStep(
    step = Charge.class,
    name = "charge",
    retryBudget = 1,
    noRetryOnAbnormalTermination = true)
@WithStep(step = Ship.class, name = "ship", retryBudget = 1)
final class Orders implements ItineraWorkflow {
  /** The bank, as the payment client of the journey. */
  @Provider(key = "payments")
  public Provided<Payments> bank() {
    return provide(new Bank(2026));
  }

  /** The main carrier, as the carrier of the journey. */
  @Provider(key = "carrier")
  public Provided<Carrier> mainCarrier() {
    return provide(new MainCarrier(20));
  }

  /** Names each journey after its order. */
  @IdGenerator
  public String orderNumber(DataBag data) {
    String order = data.read("order", TypeToken.of(String.class)).orNull();
    if (order == null) throw new IllegalStateException("an order without a number");
    return order;
  }
}

```

The log and the desk are [chapter 11](https://itinera-dev.org/book/java/11-naming-a-journey.md)'s, and the log's `detail` now also names each attempt, the error that ended one, and why a step was given up:

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

```java
/**
 * 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.
 */
static Optional<String> detail(Event event) {
  if (event instanceof JourneyStarted started) {
    return Optional.of(String.join(", ", started.initialKeys()));
  }
  if (event instanceof AttemptStarted started) {
    return Optional.of(started.step() + ", attempt " + started.attempt());
  }
  if (event instanceof ServiceProvided provided) {
    return Optional.of(
        provided.step()
            + " gets "
            + provided.key()
            + " from "
            + provided.provider()
            + ", a "
            + provided.implementation());
  }
  if (event instanceof StepSucceeded succeeded) return Optional.of(succeeded.step().toString());
  if (event instanceof StepFailed failed) {
    return Optional.of(failed.step() + ": " + failed.reason().code());
  }
  if (event instanceof StepAbnormalTermination ended) {
    return Optional.of(ended.step() + ": " + ended.errorMessage());
  }
  if (event instanceof StepRetrying retrying) return Optional.of(retrying.step().toString());
  if (event instanceof StepGivenUp givenUp) {
    return Optional.of(givenUp.step() + ": " + givenUp.cause().getCause());
  }
  if (event instanceof ContributionCommitted committed) return Optional.of(committed.key());
  if (event instanceof JourneyFailed failed) return Optional.of(failed.step().toString());
  if (event instanceof StepInfo info) return Optional.of(info.step() + ": " + info.message());
  return Optional.empty();
}
```

Each order's data now holds its card, and the receipt read back may be missing:

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

```java
/** What the shop knows about an order when its journey starts. */
record NewOrder(String order, long price, long weight, String card) {}

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

```

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.

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

```java
public static void main(String[] args) throws Refusal {
  // The customer, and their order: its number, its price, the parcel's weight in kg and the card.
  var orders =
      List.of(
          Map.entry("Ann", new NewOrder("A-1", 40, 2, "ann-2028")),
          Map.entry("Gil", new NewOrder("A-7", 45, 60, "gil-2027")),
          Map.entry("Jo", new NewOrder("A-8", 30, 1, "jo-2024")),
          Map.entry("Cat", new NewOrder("A-3", 120, 3, "cat-2027")),
          Map.entry("Dan", new NewOrder("A-4", 50, 150, "dan-2028")));
  for (var entry : orders) {
    System.out.println(entry.getKey() + "'s order:");
    var instance = new Orders().instance().initialData(entry.getValue()).create();
    var result = new LocalExecutor().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);
  }
}
```

It prints:

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

```text
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 ch12_trying_again.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 ch12_trying_again.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 ch12_trying_again.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 ch12_trying_again.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 ch12_trying_again.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 ch12_trying_again.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 ch12_trying_again.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 ch12_trying_again.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 none
```

## How it works

1. **Attempts count from 1.** An attempt is one run of a step, as [chapter 6](https://itinera-dev.org/book/java/06-passing-data-on.md) says, and every attempt after the first is a retry. Every event of an attempt carries it as `attempt()`, an `Attempt` from `org.itineradev.itinera.step`. Each attempt builds the step afresh from the data bag, and a failed attempt's contributions are never committed, so Gil's journey ends with no tracking number.
2. **An exception that escapes is an abnormal termination.** A failure, such as `card-expired`, is an outcome the step chose; an exception thrown out of `run` is an error it didn't handle. It ends the attempt as a failure of another kind, an **abnormal termination**, recorded as `step_abnormal_termination` with the exception's message. It never aborts the journey.
3. **The retry budget alone decides whether a step is tried again.** It is the number of retries the workflow allows a step, declared in its `@WithStep` annotation, 0 by default. While a retry is left, a step that failed is tried again, recorded as `step_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.**
4. **An abnormal termination spends the same budget.** Dan's booking failed with an exception, so the shipping was retried as Gil's was, and failed again with the same parcel.
5. **The workflow can turn that off for a step.** `noRetryOnAbnormalTermination = true` on the charge says an error must never be retried there, since the bank may already have taken the money. Cat's charge ended in an exception, and was given up at once with the cause `abnormal termination`, though a retry was left. Jo's failure, which is not an error, was retried.
6. **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 event's `cause().getCause()`.
7. **A `java.lang.Error` is outside the model.** Itinera never catches an `Error`, such as a `StackOverflowError` or an `AssertionError`: one thrown in a step stops the journey with no more events and no result, and reaches whoever called `run`. Throw an exception or return an outcome for anything an order can bring.

In Gil's log, there is no `service_provided` before the second attempt: the main carrier was made once for the journey, as [chapter 7](https://itinera-dev.org/book/java/07-giving-a-step-the-tools-it-needs.md) showed, so the second attempt was lent the same carrier, which refused the 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. |
