The Itinera bookJava edition

Part 4: Running it for real, Chapter 33

Giving every reporter what it needs

What you want to do

The logging service files lines by customer, and the shop needs the bank's receipt to refund an order. You want every line of the log to name the customer, and the receipt once the bank has given it, even when the journey stops right after.

The code

The shop is chapter 31's, without chapter 32's DebugReporter. main gives each instance the customer's name with reportersGlobalMetadata, beside initialData, which makes it an entry of the journey's global metadata: data for its reporters, which no step reads:

Java, from the program ch33_giving_every_reporter_what_it_needs
var instance =
    new Orders("email")
        .instance()
        .reportersGlobalMetadata("customer", order.customer())
        .initialData(order)
        .create();

Orders is the workflow chapter 23 declares, and order is each of chapter 31's orders, Ann's and Pat's.

The charge asks for its step reporter, as the shipping does since chapter 9, and sets the receipt as an entry as soon as the bank gives it, before contributing it:

Java, from the program ch33_giving_every_reporter_what_it_needs
/**
 * Charges an order's amount 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. It gives every reporter the receipt as soon
 * as the bank gives it.
 */
@Step
final class Charge implements ItineraStep {
  private final String order;
  private final long amount;
  private final String card;
  private final boolean giftCard;

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

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

The payment client it asks for is chapter 14's Payments.

The log overrides setGlobalMetadata, a method of Reporter beside report, and keeps each entry it receives in a map. A value comes as an Object, which the log tests with instanceof String. It starts each line with the customer's name and, once there is one, the receipt:

Java, from the program ch33_giving_every_reporter_what_it_needs
private final LoggingService service = new LoggingService();
private final Map<String, Object> metadata = new HashMap<>();

@Override
public void setGlobalMetadata(String key, Object value) {
  metadata.put(key, value);
}

@Override
public void report(Event event) {
  String line =
      "log "
          + event.getWorkflow()
          + " "
          + event.getJourneyId()
          + " "
          + whose()
          + " #"
          + event.getSequence()
          + " "
          + event.getKind();
  service.write(line + detail(event).map(text -> " " + text).orElse(""));
}

/** The customer the journey is for and, once the bank has given it, the charge's receipt. */
private String whose() {
  String customer = metadata.get("customer") instanceof String name ? name : "someone";
  if (metadata.get("receipt") instanceof String receipt) {
    return "for " + customer + ", receipt " + receipt;
  }
  return "for " + customer;
}

The logging service is chapter 31's. detail, chapter 22's with the parts that page points to, has one more test, for a GlobalMetadataSet, from org.itineradev.itinera.event, which names its key:

Java, from the program ch33_giving_every_reporter_what_it_needs
if (event instanceof GlobalMetadataSet set) return Optional.of(set.key());

main runs Ann's and Pat's orders, as chapter 31's does, and prints:

What ch33_giving_every_reporter_what_it_needs prints, recorded in ch33_giving_every_reporter_what_it_needs.txt
Ann's order:
log orders A-1 for Ann #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 for Ann #2 attempt_started lookup, attempt 1
log orders A-1 for Ann #3 service_provided lookup gets orderBook from ledger, a ch33_giving_every_reporter_what_it_needs.Ledger
the order book has no order A-1 yet
log orders A-1 for Ann #4 step_succeeded lookup
log orders A-1 for Ann #5 contribution_committed completed
log orders A-1 for Ann #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 for Ann #7 attempt_started price, attempt 1
log orders A-1 for Ann #8 step_succeeded price
log orders A-1 for Ann #9 contribution_committed amount
log orders A-1 for Ann #10 attempt_started charge, attempt 1
log orders A-1 for Ann #11 service_provided charge gets payments from bank, a ch33_giving_every_reporter_what_it_needs.Bank
the bank charges 30 for order A-1
log orders A-1 for Ann, receipt R-A-1 #12 global_metadata_set receipt
log orders A-1 for Ann, receipt R-A-1 #13 step_succeeded charge
log orders A-1 for Ann, receipt R-A-1 #14 contribution_committed receipt
log orders A-1 for Ann, receipt R-A-1 #15 hook_called audit: on step success of charge
log orders A-1 for Ann, receipt R-A-1 #16 contribution_committed audit
log orders A-1 for Ann, receipt R-A-1 #17 attempt_started ship, attempt 1
log orders A-1 for Ann, receipt R-A-1 #18 input_adapter_supplied ship gets weight from parcels
log orders A-1 for Ann, receipt R-A-1 #19 service_provided ship gets carrier from carriers, a ch33_giving_every_reporter_what_it_needs.MainCarrier
the main carrier books order A-1
log orders A-1 for Ann, receipt R-A-1 #20 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 for Ann, receipt R-A-1 #21 step_succeeded ship
log orders A-1 for Ann, receipt R-A-1 #22 contribution_committed tracking
log orders A-1 for Ann, receipt R-A-1 #23 optional_input_absent code
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 for Ann, receipt R-A-1 #24 hook_called notify: on workflow success
log orders A-1 for Ann, receipt R-A-1 #25 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 30, receipt R-A-1
Pat's order:
log orders A-15 for Pat #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-15 for Pat #2 attempt_started lookup, attempt 1
log orders A-15 for Pat #3 service_provided lookup gets orderBook from ledger, a ch33_giving_every_reporter_what_it_needs.Ledger
the order book has no order A-15 yet
log orders A-15 for Pat #4 step_succeeded lookup
log orders A-15 for Pat #5 contribution_committed completed
log orders A-15 for Pat #6 hook_called alreadyCompleted: on step success of lookup
log orders A-15 for Pat #7 attempt_started price, attempt 1
log orders A-15 for Pat #8 optional_input_absent discount
log orders A-15 for Pat #9 step_succeeded price
log orders A-15 for Pat #10 contribution_committed amount
log orders A-15 for Pat #11 attempt_started charge, attempt 1
log orders A-15 for Pat #12 service_provided charge gets payments from bank, a ch33_giving_every_reporter_what_it_needs.Bank
the bank charges 50 for order A-15
log orders A-15 for Pat, receipt R-A-15 #13 global_metadata_set receipt
the journey was aborted (reporter failed: the logging service is down)

How it works

  1. Global metadata is for the reporters. Each entry is a key and a value, which every reporter of the journey receives. Steps and hooks never read it, so it changes no decision.
  2. The entries come before the first event. The journey ID comes first, under the key journey_id, then the instance's entries, in the order they were set. So Pat's first line, journey_started, already names Pat. The key journey_id is the executor's own.
  3. A reporter does what it wants with an entry. setGlobalMetadata is a default method that does nothing unless a reporter overrides it, which is why chapter 11's desk is unchanged. The log keeps the entries, and reads them back from its map, checking that a value is a String before it writes it.
  4. A step can set an entry while it runs. Every reporter receives it, then the journey emits global_metadata_set, which names the key and who set it, but not the value, all before setGlobalMetadata returns. The log wrote that line with the receipt in it, event 13, before it failed on the charge's success.
  5. An entry stands whatever happens after. Pat's receipt never reached the data bag, since the journey was aborted first, but the log had it. So the shop finds Pat's payment, R-A-15, in the log's last line, and can refund it.

Every line of the log now says whose order it is and, from the charge on, how it was paid. But the audit's line, which a hook writes, says neither which journey nor which attempt took the money.

Outcomes

We have shown how a journey's reporters receive data of their own, from the instance and from the steps, as global metadata.

The usual way With Itinera
A value every log line needs, such as a customer's name, is often passed down through every call, or kept in a global variable. The instance gives it once to every reporter, before the first event.
A value a log line needs, found halfway through a request, is often lost when the request crashes right after. A step sets it for every reporter as soon as it has it, and it stands whatever happens next.