The big picture
What you want to do
You want to see chapter 1's checkout written with Itinera, all at once, before learning any of it. Don't try to understand every line. The comments say what each piece is for, and answer chapter 1's questions where the code answers them. The chapters after this one teach each piece, as you need it.
The code
Start with the workflow. Its annotations tell you at once what happens to every order: which steps run, in what order, how many times, what repairs a failure and who reacts, without reading any of the code they name. Its methods supply what the steps and policies use: the bank, the warehouse and a carrier for every attempt, for the steps, and, for the notify policy, the way the shop tells a customer something.
/**
* The shop's workflow: reserve, charge and ship, auditing the charge, rescuing it when the card has
* expired, and telling the customer how the order went.
*/
@Workflow(
name = "orders",
policies = {Notify.class},
reporters = {Log.class})
// The steps run in this order, and nothing reorders them.
@WithStep(step = Reserve.class, name = "reserve")
// The charge runs at most twice: once, and once more after its rescue step succeeds.
// Every successful charge is audited.
@WithStep(
step = Charge.class,
name = "charge",
rescue = RenewCard.class,
policies = {Audit.class})
// Shipping may be tried once more after a failure, which, for a parcel the carrier refused, is
// worth trying again.
@WithStep(step = Ship.class, name = "ship", retryBudget = 1)
final class Orders implements ItineraWorkflow, Messages {
/** One payment client for the journey, used by the charge and its rescue step. */
@Provider(key = "payments")
public Provided<Payments> bank() {
return provide(Fakes.BANK);
}
/** One stock store for the journey, shared by reserve and ship. */
@Provider(key = "stock")
public Provided<StockStore> warehouse() {
return provide(Fakes.WAREHOUSE);
}
/** A carrier for every attempt: the main carrier first, the backup carrier after. */
@Provider(perAttempt = true)
public Provided<Carrier> carrier(Attempt attempt) {
return provide(attempt.isFirst() ? Fakes.MAIN_CARRIER : Fakes.BACKUP_CARRIER);
}
/** How the shop tells a customer something, for the notify policy: here, by printing it. */
@Override
public void tell(String customer, String message) {
System.out.println(" to " + customer + ": " + message);
}
}
The steps reach the bank, the warehouse and the carriers through services: an interface saying what each one does, which a step asks for by a key, here the name of its parameter.
/** What the bank answers to a charge: the receipt, or why it refused. */
sealed interface Answer {
record Paid(String receipt) implements Answer {}
record ExpiredCard() implements Answer {}
record Refused() implements Answer {}
}
/** A payment client: it charges a card, and knows the card that replaced an expired one. */
interface Payments {
Answer charge(String card, long amount);
String renewedCard(String card);
}
/** A stock store: it reserves an order's goods, then hands them over for shipping. */
interface StockStore {
boolean reserve(String order);
void handOver(String order);
}
/** A carrier: it takes a parcel and gives back its tracking number, or nothing when it cannot. */
interface Carrier {
Optional<String> send(String order, long weight);
}
The business rules the workflow lists are steps, one for each: reserve the goods, charge the card, renew an expired card, ship the parcel. Each is a class whose constructor takes the data it needs, and whose run does the work and says how it went.
/** Reserves the order's goods in the stock store. */
@Step
final class Reserve implements ItineraStep {
private final String order;
Reserve(@Input String order) {
this.order = order;
}
public Outcome run(@Service StockStore stock) {
if (!stock.reserve(order)) return fail("out-of-stock");
return succeed();
}
}
/**
* Charges the card the price, less any discount. It only says how it went: what happens after a
* declined card is not its business.
*/
@Step
final class Charge implements ItineraStep {
private final String card;
private final long price;
private final Optional<Long> discount;
Charge(@Input String card, @Input long price, @Input Optional<Long> discount) {
this.card = card;
this.price = price;
this.discount = discount;
}
public Outcome run(@Service Payments payments, Contributor contributor) {
long amount = price - discount.orElse(0L);
Answer answer = payments.charge(card, amount);
if (answer instanceof Answer.Paid paid) {
contributor.contribute("charged", amount);
contributor.contribute("receipt", paid.receipt());
return succeed();
}
if (answer instanceof Answer.ExpiredCard) return fail("expired-card");
return fail("declined");
}
}
/**
* The charge's rescue step: asks the customer's bank for the card that replaced an expired one. A
* charge that failed for any other reason, or ended in an abnormal termination, which has no
* reason, cannot be repaired this way.
*/
@RescueStep
final class RenewCard implements ItineraRescueStep {
private final String card;
private final Optional<Reason> reason;
RenewCard(@Input String card, Optional<Reason> reason) {
this.card = card;
this.reason = reason;
}
public RescueOutcome run(@Service Payments payments, Contributor contributor) {
if (reason.map(Reason::code).filter("expired-card"::equals).isEmpty()) {
return fail("nothing-to-renew");
}
contributor.contribute("card", payments.renewedCard(card));
return succeed();
}
}
/**
* Ships the order through the carrier it is given, without knowing which one it is. A carrier that
* cannot take the parcel might be replaced on another try, so that failure is worth trying again.
*/
@Step
final class Ship implements ItineraStep {
private final String order;
private final long weight;
Ship(@Input String order, @Input long weight) {
this.order = order;
this.weight = weight;
}
public Outcome run(@Service Carrier carrier, @Service StockStore stock, Contributor contributor) {
Optional<String> tracking = carrier.send(order, weight);
if (tracking.isEmpty()) return fail("parcel-refused");
stock.handOver(order);
contributor.contribute("tracking", tracking.orElseThrow());
return succeed();
}
}
The policies the workflow attaches react to how things went: audit a successful charge, tell the customer at the end.
/** Audits every successful charge, in the journey's events, including one after a rescue. */
@StepPolicy(name = "audit")
final class Audit implements ItineraStepPolicy {
@OnStepSuccess
public OnSuccess audited(
@FromStep long charged, @FromStep String receipt, HookReporter reporter) {
reporter.info("charged " + charged + ", receipt " + receipt);
return keepDefault();
}
}
/** A role the shop provides: telling a customer something. */
@Role
interface Messages {
void tell(String customer, String message);
}
/** Tells the customer how the order went, once, when the journey ends. */
@WorkflowPolicy(name = "notify")
final class Notify implements ItineraWorkflowPolicy {
@OnWorkflowSuccess
public void shipped(
@FromWorkflow String customer,
@FromWorkflow String order,
@FromWorkflow String tracking,
@Role Messages messages) {
messages.tell(customer, "order " + order + " is on its way: " + tracking);
}
@OnWorkflowFailure
public void failed(
@FromWorkflow String customer, @FromWorkflow String order, @Role Messages messages) {
messages.tell(customer, "order " + order + " could not be completed");
}
}
The bank, the warehouse and the carriers are faked, as in chapter 1, so the program prints the same thing every time. Before it runs anything, it prints the workflow's listing:
// The workflow lists its steps, their policies, services and rescue step, without running
// anything.
for (var listed : WorkflowDescriptor.of(Orders.class).listing()) {
System.out.println(entry(listed));
}Then it runs seven orders, one journey after another, each an instance of the workflow that the executor runs, and prints how each journey ended. Ann, Ben, Cat and Dan come from chapter 1, with the same data. Three more customers take the paths none of them takes: Eve's goods are out of stock, Fin's card is valid but the order is above the bank's limit of 1,000, and Gil's parcel weighs 60 kg, too heavy for both carriers.
// The order, the customer, the card, the price, the discount when there is one, and the
// parcel's weight in kg.
var orders =
List.of(
new NewOrder("A-1", "Ann", "ann-card-2028", 40, Optional.of(5L), 2),
new NewOrder("A-2", "Ben", "ben-card-2024", 25, Optional.empty(), 1),
new NewOrder("A-3", "Cat", "cat-card-2027", 30, Optional.empty(), 30),
new NewOrder("A-4", "Dan", "dan-card-2025", 1200, Optional.empty(), 3),
new NewOrder("A-5", "Eve", "eve-card-2027", 20, Optional.empty(), 2),
new NewOrder("A-6", "Fin", "fin-card-2028", 1500, Optional.empty(), 4),
new NewOrder("A-7", "Gil", "gil-card-2029", 45, Optional.empty(), 60));
// One executor runs every journey, one after another, each an instance of the workflow made
// with the order's data.
var executor = new LocalExecutor();
for (var order : orders) {
System.out.println(order.order() + ":");
var result = executor.run(new Orders().instance().initialData(order).create());
var status = result.status();
if (status instanceof JourneyStatus.Succeeded) {
System.out.println("succeeded");
} else if (status instanceof JourneyStatus.Failed failed) {
System.out.println("failed: " + why(failed.failure()));
} else {
System.out.println("aborted");
}
}It prints the listing, then, under each order, what the shop's log and the customer were told, and how it ended:
1. reserve; services: stock from warehouse
2. charge, with audit; services: payments from bank; rescued by charge_rescue, services: payments from bank
3. ship; services: carrier from carrier, stock from warehouse
A-1:
INFO audit: charged 35, receipt R-ann-card-2028-35
to Ann: order A-1 is on its way: T-A-1
succeeded
A-2:
WARN charge, attempt 1: expired-card
INFO charge to be rescued by charge_rescue
INFO audit: charged 25, receipt R-ben-card-2029-25
to Ben: order A-2 is on its way: T-A-2
succeeded
A-3:
INFO audit: charged 30, receipt R-cat-card-2027-30
WARN ship, attempt 1: parcel-refused
INFO ship tried again
to Cat: order A-3 is on its way: B-A-3
succeeded
A-4:
WARN charge, attempt 1: expired-card
INFO charge to be rescued by charge_rescue
WARN charge, attempt 2: declined
WARN charge given up: failure
to Dan: order A-4 could not be completed
failed: failure, declined
A-5:
WARN reserve, attempt 1: out-of-stock
WARN reserve given up: failure
to Eve: order A-5 could not be completed
failed: failure, out-of-stock
A-6:
WARN charge, attempt 1: declined
INFO charge to be rescued by charge_rescue
WARN charge_rescue, attempt 1: nothing-to-renew
WARN charge_rescue given up: failure
to Fin: order A-6 could not be completed
failed: failure, nothing-to-renew
A-7:
INFO audit: charged 45, receipt R-gil-card-2029-45
WARN ship, attempt 1: parcel-refused
INFO ship tried again
WARN ship, attempt 2: parcel-refused
WARN ship given up: retries exhausted
to Gil: order A-7 could not be completed
failed: retries exhausted, parcel-refusedHow it works
Every order follows the path the diagram draws, and the output shows which.
flowchart TD accTitle: A journey through the shop accDescr: The journey reserves the goods, then charges the card. A successful charge is audited, then the order is shipped. A failed charge is rescued by charge_rescue; when the rescue succeeds the charge runs once more, and when the rescue or the second charge fails the journey fails. Shipping is tried with the main carrier; when it cannot take the parcel, shipping is tried once more with the backup carrier. When shipping succeeds, notify tells the customer and the journey succeeds. Any failure that is not repaired leads notify to tell the customer, and the journey fails. start([The journey starts with the order]) --> reserve[reserve] reserve -- success --> charge[charge] reserve -- failure --> told_failed[notify tells the customer the order could not be completed] charge -- success --> audit[audit logs the charge] charge -- failure --> rescue[charge_rescue renews an expired card] rescue -- success --> again[charge runs once more] rescue -- failure --> told_failed again -- success --> audit again -- failure --> told_failed audit --> ship[ship, attempt 1, main carrier] ship -- success --> told_shipped[notify tells the customer the order is on its way] ship -- failure, retry budget left --> ship2[ship, attempt 2, backup carrier] ship2 -- success --> told_shipped ship2 -- failure --> told_failed told_shipped --> succeeded([The journey succeeded]) told_failed --> failed([The journey failed])
The diagram shows:
- The journey starts with the order's data and runs
reserve. If reserving fails, as Eve's does, the journey goes to its end as failed. - Then
chargeruns. When it succeeds, as Ann's does, theauditpolicy logs the charge. - When the charge fails, the rescue step, which the listing names
charge_rescue, runs: for an expired card it asks the bank for the new card, and for any other reason it fails, as Fin's does, and the journey goes to its end as failed. - When the rescue succeeds, the charge runs once more. If it succeeds, as Ben's does,
auditlogs it; if it fails, as Dan's does, the journey goes to its end as failed. - After the audit,
shipmakes its first attempt, with the main carrier. If it succeeds, as Ann's does, the journey goes to its end as succeeded. - If the first attempt fails,
shiphas a retry left, so it makes a second attempt, with the backup carrier. If that succeeds, as Cat's does, the journey goes to its end as succeeded; if it fails, as Gil's does, the journey goes to its end as failed. - At a successful end,
notifytells the customer the order is on its way, and the journey succeeded. - At a failed end,
notifytells the customer the order could not be completed, and the journey failed.
Outcomes
We have shown the whole checkout as one workflow, where every question of chapter 1 is answered in one place.
| The usual way | With Itinera |
|---|---|
| Retries, repairs and fallbacks usually live in the methods that meet the failure, so finding them means reading those methods. | Every retry budget, rescue step and policy is in the workflow's declaration. |
| Which services a method uses is often known only from its body or its constructor. | The listing shows every step's services and where each comes from, before anything runs. |