The Itinera bookJava edition

Part 5: Designing with Itinera, Chapter 42

Using a step in another workflow

What you want to do

Customers can now collect their orders at the shop's counter, paying at the counter's card terminal and taking the goods away, so nothing is shipped. You want the counter to look the order up, price it and charge it exactly as delivered orders are, without copying any of that code, and to decide for itself everything else.

The code

The shop is the one chapter 37 lists, with Orders as chapter 39 shows it. The counter's terminal is one more implementation of the Payments interface the charge already asks for, as chapter 35 shows it:

Java, from the program ch42_using_a_step_in_another_workflow
/**
 * The shop counter's card terminal, faked: it declines a card that expired before this year, and
 * prints what it does. Its receipts start with {@code C}.
 */
final class Terminal implements Payments {
  private final int thisYear;

  Terminal(int thisYear) {
    this.thisYear = thisYear;
  }

  @Override
  public Optional<String> charge(String order, String card, long amount) {
    if (Bank.expiry(card) < thisYear) {
      System.out.println("the counter's terminal declines card " + card + ": it has expired");
      return Optional.empty();
    }
    System.out.println("the counter's terminal charges " + amount + " for order " + order);
    return Optional.of("C-" + order);
  }
}

The counter's workflow class lists three of the shop's steps, Lookup, Price and Charge, under the same names, and provides the order book and the terminal. Its initial data has what those steps read, and no parcel:

Java, from the program ch42_using_a_step_in_another_workflow
/**
 * The counter's workflow: it looks the order up, and finishes an order already completed. Otherwise
 * it works out what the order costs, then charges it at the counter's terminal and audits the
 * charge. The customer takes the goods away, so nothing is shipped, and a card the terminal
 * declines is handed back rather than repaired.
 */
@Workflow(
    name = "counter",
    reporters = {Log.class})
@WithStep(
    step = Lookup.class,
    name = "lookup",
    policies = {AlreadyCompleted.class})
@WithStep(step = Price.class, name = "price")
@WithStep(
    step = Charge.class,
    name = "charge",
    policies = {Audit.class})
final class Counter implements ItineraWorkflow {
  /** 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 counter's terminal, as the payment client of the journey. */
  @Provider(key = "payments")
  public Provided<Payments> terminal() {
    return provide(new Terminal(2026));
  }
}

/** What the shop knows about an order collected at the counter when its journey starts. */
record CounterOrder(
    String order, long price, Optional<Long> discount, String card, boolean giftCard) {
  /** An order with a discount, that isn't a gift card. */
  CounterOrder(String order, long price, long discount, String card) {
    this(order, price, Optional.of(discount), card, false);
  }

  /** An order without a discount, that isn't a gift card. */
  CounterOrder(String order, long price, String card) {
    this(order, price, Optional.empty(), card, false);
  }
}

What it names is as earlier chapters show it: the lookup, AlreadyCompleted and OrderBook in chapter 22, the ID generator in chapter 11, the pricing in chapter 20, the charge in chapter 33, the audit in chapter 34, and the log in chapter 33, chapter 35 and chapter 36.

main prints the listing of each workflow with entry, as chapter 37 did:

Java, from the program ch42_using_a_step_in_another_workflow
System.out.println("orders:");
for (var listed : WorkflowDescriptor.of(Orders.class).listing()) {
  System.out.println(entry(listed));
}
System.out.println("counter:");
for (var listed : WorkflowDescriptor.of(Counter.class).listing()) {
  System.out.println(entry(listed));
}

Then it runs two new orders at the counter, each paired with its customer's name by Map.entry: Nia's, with a discount, and Omar's, whose card has expired:

Java, from the program ch42_using_a_step_in_another_workflow
var executor = new LocalExecutor();
// Each order collected at the counter: its customer, and its number, price, discount if it has
// one, and card.
var orders =
    List.of(
        Map.entry("Nia", new CounterOrder("A-17", 18, 3, "nia-2028")),
        Map.entry("Omar", new CounterOrder("A-18", 12, "omar-2023")));
for (var entry : orders) {
  var customer = entry.getKey();
  var order = entry.getValue();
  System.out.println(customer + "'s order " + order.order() + ", at the counter:");
  var instance =
      new Counter()
          .instance()
          .reportersGlobalMetadata("customer", customer)
          .initialData(order)
          .create();
  followUp(executor.run(instance));
}

followUp now reads the counter's output, a record nested in Main, and says to hand back a card the terminal declined:

Java, from the program ch42_using_a_step_in_another_workflow
/** What the counter reads back once the journey has ended. */
record Collected(Optional<String> receipt, Optional<String> audit) {}

/** Says how a journey at the counter ended. */
static void followUp(JourneyResult result) {
  var data = result.output(TypeToken.of(Collected.class));
  JourneyStatus status = result.status();
  if (status instanceof JourneyStatus.Succeeded) {
    System.out.println("the journey succeeded, with receipt " + data.receipt().orElse("none"));
    System.out.println("audit: " + data.audit().orElse("none"));
  } else if (status instanceof JourneyStatus.Failed failed) {
    Reason reason = failed.failure().reason();
    String why = reason == null ? failed.failure().cause().toString() : reason.code();
    System.out.println("the journey failed: " + why + ", hand the card back");
  } else if (status instanceof JourneyStatus.Aborted aborted) {
    System.out.println("the journey was aborted (" + aborted.abort().reason() + ")");
  }
}

It prints:

What ch42_using_a_step_in_another_workflow prints, recorded in ch42_using_a_step_in_another_workflow.txt
orders:
1. lookup, with alreadyCompleted; services: orderBook from ledger
2. price
3. charge, with audit, outage; services: payments from bank; rescued by charge_rescue, services: cards from cards
4. ship, with failedShipping; adapted by parcels; services: carrier from carriers
counter:
1. lookup, with alreadyCompleted; services: orderBook from ledger
2. price
3. charge, with audit; services: payments from terminal
Nia's order A-17, at the counter:
log counter A-17 for Nia #1 journey_started order, price, discount, card, giftCard
log counter A-17 for Nia #2 attempt_started lookup, attempt 1
log counter A-17 for Nia #3 service_provided lookup gets orderBook from ledger, a ch42_using_a_step_in_another_workflow.Ledger
the order book has no order A-17 yet
log counter A-17 for Nia #4 step_succeeded lookup
log counter A-17 for Nia #5 contribution_committed completed
log counter A-17 for Nia #6 hook_called alreadyCompleted: on step success of lookup
log counter A-17 for Nia #7 attempt_started price, attempt 1
log counter A-17 for Nia #8 step_succeeded price
log counter A-17 for Nia #9 contribution_committed amount
log counter A-17 for Nia #10 attempt_started charge, attempt 1
log counter A-17 for Nia #11 service_provided charge gets payments from terminal, a ch42_using_a_step_in_another_workflow.Terminal
the counter's terminal charges 15 for order A-17
log counter A-17 for Nia, receipt C-A-17 #12 global_metadata_set receipt
log counter A-17 for Nia, receipt C-A-17 #13 step_succeeded charge
log counter A-17 for Nia, receipt C-A-17 #14 contribution_committed receipt
log counter A-17 for Nia, receipt C-A-17 #15 hook_called audit: on step success of charge
log counter A-17 for Nia, receipt C-A-17 #16 contribution_committed audit
log counter A-17 for Nia, receipt C-A-17 #17 journey_succeeded
the journey succeeded, with receipt C-A-17
audit: A-17: charge took 15 on attempt 1, receipt C-A-17
Omar's order A-18, at the counter:
log counter A-18 for Omar #1 journey_started order, price, card, giftCard
log counter A-18 for Omar #2 attempt_started lookup, attempt 1
log counter A-18 for Omar #3 service_provided lookup gets orderBook from ledger, a ch42_using_a_step_in_another_workflow.Ledger
the order book has no order A-18 yet
log counter A-18 for Omar #4 step_succeeded lookup
log counter A-18 for Omar #5 contribution_committed completed
log counter A-18 for Omar #6 hook_called alreadyCompleted: on step success of lookup
log counter A-18 for Omar #7 attempt_started price, attempt 1
log counter A-18 for Omar #8 optional_input_absent discount
log counter A-18 for Omar #9 step_succeeded price
log counter A-18 for Omar #10 contribution_committed amount
log counter A-18 for Omar #11 attempt_started charge, attempt 1
log counter A-18 for Omar #12 service_provided charge gets payments from terminal, a ch42_using_a_step_in_another_workflow.Terminal
the counter's terminal declines card omar-2023: it has expired
log counter A-18 for Omar #13 step_failed charge: card-expired
log counter A-18 for Omar #14 step_given_up charge: failure
log counter A-18 for Omar #15 journey_failed charge
the journey failed: card-expired, hand the card back

How it works

  1. A step belongs to no workflow. Lookup, Price and Charge say what they read and which services they ask for, by key, and how their work went. Nothing in them names orders, the next step or a policy, so the counter lists them as they are, and they run as they do for a delivered order: Nia's price is 18 less 3, and the charge takes 15.
  2. Each workflow provides its own services. The charge asks for payments, and gets the bank in orders and the terminal in counter: the listings say so, and so does service_provided, event 11. The counter's receipts start with C, and the charge never knew which client it had.
  3. Each workflow decides its own flow. In orders, a charge that fails because the card has expired is rescued, as chapter 14 showed. In counter, it has no rescue step, so the same failure, card-expired, gives the charge up and fails Omar's journey: the customer is standing there, and can hand over another card. counter has no ship, so none of its retry budget or policies, and no outage policy, since the counter's terminal has no network to lose.
  4. Each workflow decides its own policies and reporters. Audit and AlreadyCompleted are attached in both, and Audit writes the same audit line. counter lists the Log reporter alone, and no workflow policy, so nobody is told by email: the log's lines start with the workflow's name, counter.
  5. Both workflows live in one program. Each is declared once and checked by itinera's checker as the program is built, as chapter 37 showed: had counter listed Charge without providing payments, it would not compile, with the violation service not provided.

A step can now be changed once for every workflow that lists it, which is how the shop wants its coding agents to work: they change its business rules, often in steps. The shop wants to know that such a change leaves every order's flow as a person agreed.

Outcomes

We have shown how one step runs in two workflows, each deciding its own services, flow, policies and reporters.

The usual way With Itinera
A second sales channel often copies the first one's code, or adds flags to it for the cases that differ. The second workflow lists the same steps, and declares only what differs.
A method reused by a second channel often has to learn which channel called it. The charge runs unchanged in both workflows, with whichever client each provides.