# Reacting to what a step did

## What you want to do

The shop's accountants want an audit line for every charge that succeeded: what the order was charged, and the receipt. You want it written after every successful charge, without adding a word about auditing to the charge.

## The code

The audit is a **step policy**: a class marked `@StepPolicy(name = "audit")` that implements `ItineraStepPolicy`, both from `org.itineradev.itinera.policy`. Its method marked `@OnStepSuccess` is a **hook**, which the executor calls after a step it is attached to succeeds. The hook asks for the step's name, for the order's price from the data bag, and for the receipt the step contributed, and contributes the audit line under `audit`. It returns `keepDefault()`, leaving what happens next as it was.

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

```java
/**
 * Writes an audit line for every step it is attached to that succeeds: what the order was charged,
 * and the receipt the step gave back.
 */
@StepPolicy(name = "audit")
final class Audit implements ItineraStepPolicy {
  @OnStepSuccess
  public OnSuccess charged(
      StepName step, @FromWorkflow long price, @FromStep String receipt, Contributor contributor) {
    contributor.contribute("audit", step + " took " + price + ", receipt " + receipt);
    return keepDefault();
  }
}

```

The workflow attaches the policy to the charge, with `policies = {Audit.class}` in the charge's `@WithStep` annotation:

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

```java
/**
 * The shop's workflow: it charges, repairing a charge that fails and auditing one that succeeds,
 * then ships, and shipping may be tried once more.
 */
@Workflow(
    name = "orders",
    reporters = {Log.class, Desk.class})
@WithStep(
    step = Charge.class,
    name = "charge",
    rescue = RenewCard.class,
    policies = {Audit.class})
@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));
  }

  /** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
  @Provider(perAttempt = true, key = "carrier")
  public Provided<Carrier> carriers(Attempt attempt) {
    return attempt.isFirst() ? provide(new MainCarrier()) : provide(new BackupCarrier());
  }

  /** 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 rescue step `RenewCard` is [chapter 14](https://itinera-dev.org/book/java/14-repairing-then-trying-once-more.md)'s, the shipping is [chapter 12](https://itinera-dev.org/book/java/12-trying-again.md)'s and the desk is [chapter 11](https://itinera-dev.org/book/java/11-naming-a-journey.md)'s. The bank's provider and the interface `Carrier` are [chapter 12](https://itinera-dev.org/book/java/12-trying-again.md)'s, and the carriers' provider [chapter 13](https://itinera-dev.org/book/java/13-a-carrier-for-each-attempt.md)'s.

The log is [chapter 11](https://itinera-dev.org/book/java/11-naming-a-journey.md)'s, with the `detail` method [chapter 12](https://itinera-dev.org/book/java/12-trying-again.md) shows and the tests [chapter 14](https://itinera-dev.org/book/java/14-repairing-then-trying-once-more.md) added, which now also say which policy's hook was called, and after which step:

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

```java
if (event instanceof StepHookCalled called) {
  return Optional.of(
      called.source().policy()
          + ": "
          + called.source().hook()
          + " of "
          + called.source().step());
}
```

A new customer, Kim, buys a gift card, which the shop sends by email. The charge now asks whether the order is a gift card, and if it is, gives back the card's code under `code`:

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

```java
/**
 * Charges an order's price 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
final class Charge implements ItineraStep {
  private final String order;
  private final long price;
  private final String card;
  private final boolean giftCard;

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

  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());
    if (giftCard) contributor.contribute("code", "G-" + order);
    return succeed();
  }
}

```

The payment client it asks for is [chapter 14](https://itinera-dev.org/book/java/14-repairing-then-trying-once-more.md)'s `Payments`.

The order's data now says whether it is a gift card, `false` unless the order says otherwise, as the record's second constructor gives it, and the output holds the audit line:

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

```java
/** What the shop knows about an order when its journey starts. */
record NewOrder(String order, long price, long weight, String card, boolean giftCard) {
  /** An order that isn't a gift card. */
  NewOrder(String order, long price, long weight, String card) {
    this(order, price, weight, card, false);
  }
}

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

```

The shop runs Ann's, Gil's and Jo's orders, then Kim's, reads back the audit line, and prints it:

Java, from the program [`ch15_reacting_to_what_a_step_did`](https://github.com/itinera-dev/book/blob/main/java/examples/ch15_reacting_to_what_a_step_did.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, the card,
  // and whether it is a gift 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("Kim", new NewOrder("A-9", 25, 0, "kim-2027", true)));
  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);
    System.out.println("audit: " + data.audit().orElse("none"));
  }
}
```

It prints:

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

```text
Ann's order:
log orders A-1 #1 journey_started order, price, weight, card, giftCard
log orders A-1 #2 attempt_started charge, attempt 1
log orders A-1 #3 service_provided charge gets payments from bank, a ch15_reacting_to_what_a_step_did.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 hook_called audit: on step success of charge
log orders A-1 #7 contribution_committed audit
log orders A-1 #8 attempt_started ship, attempt 1
log orders A-1 #9 service_provided ship gets carrier from carriers, a ch15_reacting_to_what_a_step_did.MainCarrier
the main carrier books order A-1
log orders A-1 #10 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #11 step_succeeded ship
log orders A-1 #12 contribution_committed tracking
log orders A-1 #13 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 40, receipt R-A-1
Gil's order:
log orders A-7 #1 journey_started order, price, weight, card, giftCard
log orders A-7 #2 attempt_started charge, attempt 1
log orders A-7 #3 service_provided charge gets payments from bank, a ch15_reacting_to_what_a_step_did.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 hook_called audit: on step success of charge
log orders A-7 #7 contribution_committed audit
log orders A-7 #8 attempt_started ship, attempt 1
log orders A-7 #9 service_provided ship gets carrier from carriers, a ch15_reacting_to_what_a_step_did.MainCarrier
the main carrier books order A-7
log orders A-7 #10 step_failed ship: too-heavy
log orders A-7 #11 step_retrying ship
log orders A-7 #12 attempt_started ship, attempt 2
log orders A-7 #13 service_provided ship gets carrier from carriers, a ch15_reacting_to_what_a_step_did.BackupCarrier
the backup carrier books order A-7
log orders A-7 #14 step_info ship: the parcel leaves with receipt R-A-7
log orders A-7 #15 step_succeeded ship
log orders A-7 #16 contribution_committed tracking
log orders A-7 #17 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, price, weight, card, giftCard
log orders A-8 #2 attempt_started charge, attempt 1
log orders A-8 #3 service_provided charge gets payments from bank, a ch15_reacting_to_what_a_step_did.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_rescuing charge: failure, rescued by charge_rescue
log orders A-8 #6 attempt_started charge_rescue, attempt 1
the bank says card jo-2024 was replaced by jo-2029
log orders A-8 #7 step_succeeded charge_rescue
log orders A-8 #8 contribution_committed card
log orders A-8 #9 data_overwritten card
log orders A-8 #10 step_rescued charge by charge_rescue
log orders A-8 #11 attempt_started charge, attempt 2
the bank charges 30 for order A-8
log orders A-8 #12 step_succeeded charge
log orders A-8 #13 contribution_committed receipt
log orders A-8 #14 hook_called audit: on step success of charge
log orders A-8 #15 contribution_committed audit
log orders A-8 #16 attempt_started ship, attempt 1
log orders A-8 #17 service_provided ship gets carrier from carriers, a ch15_reacting_to_what_a_step_did.MainCarrier
the main carrier books order A-8
log orders A-8 #18 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 #19 step_succeeded ship
log orders A-8 #20 contribution_committed tracking
log orders A-8 #21 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, price, weight, card, giftCard
log orders A-9 #2 attempt_started charge, attempt 1
log orders A-9 #3 service_provided charge gets payments from bank, a ch15_reacting_to_what_a_step_did.Bank
the bank charges 25 for order A-9
log orders A-9 #4 step_succeeded charge
log orders A-9 #5 contribution_committed receipt
log orders A-9 #6 contribution_committed code
log orders A-9 #7 hook_called audit: on step success of charge
log orders A-9 #8 contribution_committed audit
log orders A-9 #9 attempt_started ship, attempt 1
log orders A-9 #10 service_provided ship gets carrier from carriers, a ch15_reacting_to_what_a_step_did.MainCarrier
the main carrier books order A-9
log orders A-9 #11 step_info ship: the parcel leaves with receipt R-A-9
log orders A-9 #12 step_succeeded ship
log orders A-9 #13 contribution_committed tracking
log orders A-9 #14 journey_succeeded
the journey succeeded, with receipt R-A-9 and tracking T-A-9
audit: charge took 25, receipt R-A-9
```

## How it works

1. **A step policy holds what happens around a step.** It defines hooks, and the workflow attaches it to steps, so the charge never knows it is audited. **A step never knows which policies are attached to it; the workflow attaches them.** The policy names no step of its own, so it can be attached to any step of any workflow; a hook that needs the step's name asks for it, with a parameter of type `StepName`, from `org.itineradev.itinera.step`.
2. **The executor calls a hook after an outcome.** `@OnStepSuccess` marks the hook, a public method like a step's `run`, called each time a step the policy is attached to succeeds, after its contributions are committed; the audit reads the receipt from what the charge contributed. The executor records the call as `hook_called`, a `StepHookCalled` for a step policy's hook, whose `source()` names the policy, the hook, and the step and attempt it was called after. Jo's charge fails on its first attempt, so the hook is called only after attempt 2, once the charge succeeded with the new card.
3. **A hook asks for what it needs, and gets only that.** Each parameter is a request. `@FromStep` asks for what the step contributed, by the parameter's name, here `receipt`; `@FromWorkflow` asks for data from the data bag, here `price`; both are from `org.itineradev.itinera.policy`, and each value is read as the parameter's type, as a step's inputs are. A `Contributor` asks for a contributor, and the `StepName` for the step's name, by their types. A hook never gets the data bag itself.
4. **A hook's contributions are committed when it returns.** The audit line is committed right after the hook, as `contribution_committed audit`, and the shop reads it back with the journey's output.
5. **A hook decides nothing it isn't asked to.** Its return type, `OnSuccess`, from `org.itineradev.itinera.policy`, could carry a decision about what happens next. `keepDefault()`, which `ItineraStepPolicy` gives the class, keeps the default, what happens next without the hook, and after a success the next step runs. The audit only writes down what happened.
6. **A policy is built afresh for every attempt.** The executor builds it with its constructor, which takes nothing, and nothing is kept from one call to the next: everything a hook needs comes through what it asks for.

Now look at Kim's journey. Her charge succeeded, and gave back her gift card's code, so there is nothing left to do for her order. But the workflow still runs the shipping, and the main carrier books a parcel of 0 kg.

## Outcomes

We have shown how a step policy reacts to what a step did, without the step knowing.

| The usual way                                                                                                               | With Itinera                                                                                       |
| --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Auditing a call is usually a line added after it, wherever it is made, so the code that charges also knows about the audit. | The audit is a policy attached to the charge in the workflow, and the charge has no line about it. |
| What runs after a call succeeds is often spread across the callers.                                                         | Every hook call is an event, naming the policy and the hook, after the outcome it reacts to.       |
