The Itinera bookJava edition

Part 3: Controlling the flow, Chapter 22

Finishing a journey early

What you want to do

Now and then the website sends an order a second time: Mia's order A-13, paid and shipped yesterday, arrives again today. You want the shop to see that the order is already done, and end its journey there, as succeeded, without charging Mia or booking her parcel a second time.

The code

The shop keeps an order book, which says whether an order was already completed. It is a service, like the bank, so it is an interface of the shop's own:

Java, from the program ch22_finishing_a_journey_early
/** The shop's order book: it says whether an order was already completed. */
interface OrderBook {
  boolean completed(String order);
}

A new step, the lookup, asks the order book about the order and gives back what it says, under completed. It decides nothing about what happens next:

Java, from the program ch22_finishing_a_journey_early
/** Looks the order up in the order book, and gives back whether it was already completed. */
@Step
final class Lookup implements ItineraStep {
  private final String order;

  Lookup(@Input String order) {
    this.order = order;
  }

  public Outcome run(@Service OrderBook orderBook, Contributor contributor) {
    contributor.contribute("completed", orderBook.completed(order));
    return succeed();
  }
}

A step policy, alreadyCompleted, reads that answer. Its on step success asks for completed from the step, with @FromStep, as the audit asks for the receipt in chapter 15. For an order already completed, it returns finishWorkflow(), which ItineraStepPolicy gives the class beside keepDefault(): the lifecycle FinishWorkflow. Otherwise it keeps the default:

Java, from the program ch22_finishing_a_journey_early
/**
 * Finishes the journey of an order that was already completed: there is nothing left to do for it.
 */
@StepPolicy(name = "alreadyCompleted")
final class AlreadyCompleted implements ItineraStepPolicy {
  @OnStepSuccess
  public OnSuccess lookedUp(@FromStep boolean completed) {
    return completed ? finishWorkflow() : keepDefault();
  }
}

The workflow runs the lookup first, with the policy attached to it. Its new provider, ledger, makes the order book, which in this program is faked, and holds the one order completed before today, Mia's:

Java, from the program ch22_finishing_a_journey_early
/**
 * The shop's workflow: it looks the order up, and finishes an order already completed. Otherwise it
 * works out what the order costs, then charges it, repairing a charge that fails and auditing one
 * that succeeds, then ships, and shipping may be tried once more. Once a journey has ended, the
 * customer is told, through the channel the shop configures.
 */
@Workflow(
    name = "orders",
    reporters = {Log.class, Desk.class},
    policies = {Notify.class})
@WithStep(
    step = Lookup.class,
    name = "lookup",
    policies = {AlreadyCompleted.class})
@WithStep(step = Price.class, name = "price")
@WithStep(
    step = Charge.class,
    name = "charge",
    rescue = RenewCard.class,
    policies = {Audit.class, Outage.class})
@WithStep(
    step = Ship.class,
    name = "ship",
    retryBudget = 1,
    policies = {HeavyParcels.class})
final class Orders implements ItineraWorkflow, Messages {
  private final String channel;

  Orders(String channel) {
    this.channel = channel;
  }

  @Override
  public void tell(String customer, String message) {
    System.out.println(channel + " to " + customer + ": " + message);
  }

  /** 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());
  }

  /**
   * Gives the shipping the weight of the order's parcel, as the warehouse describes it. Every other
   * input of the shipping is read from the data bag.
   */
  @InputAdapter(steps = {"ship"})
  public Supplied parcels(@Key String key, @FromWorkflow Parcel parcel) {
    return key.equals("weight") ? supply(parcel.weight()) : fromDataBag();
  }

  /** 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 order book, which has the orders completed before today. */
  @Provider(key = "orderBook")
  public Provided<OrderBook> ledger() {
    return provide(new Ledger(List.of("A-13")));
  }
}

The other steps, policies and reporters it names are as earlier chapters show them: the pricing, the charge and the audit in chapter 20, RenewCard in chapter 14, the shipping, Outage and HeavyParcels in chapter 17, Notify and the role Messages in chapter 19 and the desk in chapter 11. The bank's provider is chapter 12's, the interface Payments it lends chapter 14's, the carriers' provider chapter 13's, with chapter 12's Carrier, and the input adapter chapter 21's.

The log is chapter 21's, with the parts that page points to, and now also says which policy finished a journey:

Java, from the program ch22_finishing_a_journey_early
if (event instanceof JourneySucceeded succeeded) {
  if (succeeded.decidedBy() instanceof DecidingHook hook) {
    return Optional.of("FinishWorkflow from " + hook.policy());
  }
  return Optional.empty();
}

NewOrder and Parcel are as chapter 21 shows them, and Order, the output, as chapter 19 does. main runs two orders, Ann's and Mia's:

Java, from the program ch22_finishing_a_journey_early
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, and the 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-13", "Mia", 50, new Parcel(4, List.of(40L, 30L, 30L)), "mia-2029"));
    for (var order : orders) {
      System.out.println(order.customer() + "'s order:");
      var instance = new Orders("email").instance().initialData(order).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 ch22_finishing_a_journey_early prints, recorded in ch22_finishing_a_journey_early.txt
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 ch22_finishing_a_journey_early.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 ch22_finishing_a_journey_early.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 ch22_finishing_a_journey_early.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
Mia's order:
log orders A-13 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-13 #2 attempt_started lookup, attempt 1
log orders A-13 #3 service_provided lookup gets orderBook from ledger, a ch22_finishing_a_journey_early.Ledger
the order book has order A-13 completed already
log orders A-13 #4 step_succeeded lookup
log orders A-13 #5 contribution_committed completed
log orders A-13 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-13 #7 optional_input_absent tracking
log orders A-13 #8 optional_input_absent code
email to Mia: Order A-13 is complete.
log orders A-13 #9 hook_called notify: on workflow success
log orders A-13 #10 journey_succeeded FinishWorkflow from alreadyCompleted
the journey succeeded, with receipt none and tracking none
audit: none

How it works

  1. FinishWorkflow ends the journey at once, as succeeded. It is the second lifecycle, after FailWorkflow in chapter 17. Mia's lookup succeeded and contributed completed, so alreadyCompleted finished the journey. Her price, charge and shipping never ran: her log has no attempt of theirs, and the bank and the carriers were never asked, so Mia is charged only once.
  2. The journey says who finished it. journey_succeeded, a JourneySucceeded, carries decidedBy(), a DecidedBy, which is one of two things: a DecidingHook, naming the policy whose hook returned FinishWorkflow, or DecidedBy.Default, which names none. The log tests for a DecidingHook with instanceof, and says nothing more otherwise. Mia's is a DecidingHook, and the log prints it: FinishWorkflow from alreadyCompleted. Ann's journey ended by default, after its last step, so hers is DecidedBy.Default.
  3. Only on step success may finish a journey, and its type says so. What finishWorkflow() returns is an OnSuccess, which on step success returns, and never an OnFailure, which on step retry and on step abnormal termination return. So a step that hasn't succeeded can never finish its journey.
  4. What the step contributed is kept. The hook runs after the lookup's contributions are committed, so completed is in Mia's data bag, as in Ann's.
  5. The workflow's own hooks still run. A journey finished early has succeeded, so Notify's on workflow success tells Mia. Her data bag holds no tracking number and no gift card's code, so she reads Order A-13 is complete. The receipt and the tracking of yesterday's journey belong to that journey, so main reads none of them in this one.
  6. The step reports what it found, and the policy decides what follows. The lookup only says whether the order was completed. Ending the journey there is a decision about the flow, so it lives in a policy. The price, the charge and the shipping could each skip an order already completed, but each of them would then need to know about the order book, and a step added later would need to know too. A decision about the whole journey belongs in a policy, not in every step it would stop.

The shop no longer charges an order twice. But it still keeps the money of an order it charges and never ships, such as Ned's in chapter 17.

Outcomes

We have shown how a step policy finishes a journey early, as succeeded, once nothing is left to do.

The usual way With Itinera
A process that stops early often does so through a return deep in the code, and nothing records which check stopped it. on step success returns FinishWorkflow, and journey_succeeded names the policy that finished the journey.
Skipping work for a request already handled often means a check at the top of each method that does the work. One policy, attached to one lookup, ends the journey, and the steps it stops know nothing about it.