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(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(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(Ship::class, name = "ship", retryBudget = 1)
class Orders : ItineraWorkflow, Messages {
/** One payment client for the journey, used by the charge and its rescue step. */
@Provider(key = "payments") fun bank(): Provided<Payments> = provide(BANK)
/** One stock store for the journey, shared by reserve and ship. */
@Provider(key = "stock") fun warehouse(): Provided<StockStore> = provide(WAREHOUSE)
/** A carrier for every attempt: the main carrier first, the backup carrier after. */
@Provider(perAttempt = true)
fun carrier(attempt: Attempt): Provided<Carrier> =
provide(if (attempt.isFirst) MAIN_CARRIER else BACKUP_CARRIER)
/** How the shop tells a customer something, for the notify policy: here, by printing it. */
override fun tell(customer: String, message: String) {
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 {
data class Paid(val receipt: String) : Answer
data object ExpiredCard : Answer
data object Refused : Answer
}
/** A payment client: it charges a card, and knows the card that replaced an expired one. */
interface Payments {
fun charge(card: String, amount: Long): Answer
fun renewedCard(card: String): String
}
/** A stock store: it reserves an order's goods, then hands them over for shipping. */
interface StockStore {
fun reserve(order: String): Boolean
fun handOver(order: String)
}
/** A carrier: it takes a parcel and gives back its tracking number, or `null` when it cannot. */
interface Carrier {
fun send(order: String, weight: Long): String?
}
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
class Reserve(@Input private val order: String) : ItineraStep {
fun run(@Service stock: StockStore): Outcome {
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
class Charge(
@Input private val card: String,
@Input private val price: Long,
@Input private val discount: Long?,
) : ItineraStep {
fun run(@Service payments: Payments, contributor: Contributor): Outcome {
val amount = price - (discount ?: 0)
return when (val answer = payments.charge(card, amount)) {
is Answer.Paid -> {
contributor.contribute("charged", amount)
contributor.contribute("receipt", answer.receipt)
succeed()
}
Answer.ExpiredCard -> fail("expired-card")
Answer.Refused -> 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
class RenewCard(@Input private val card: String, private val reason: Reason?) : ItineraRescueStep {
fun run(@Service payments: Payments, contributor: Contributor): RescueOutcome {
if (reason?.code != "expired-card") 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
class Ship(@Input private val order: String, @Input private val weight: Long) : ItineraStep {
fun run(
@Service carrier: Carrier,
@Service stock: StockStore,
contributor: Contributor,
): Outcome {
val tracking = carrier.send(order, weight) ?: return fail("parcel-refused")
stock.handOver(order)
contributor.contribute("tracking", tracking)
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")
class Audit : ItineraStepPolicy {
@OnStepSuccess
fun audited(
@FromStep charged: Long,
@FromStep receipt: String,
reporter: HookReporter,
): OnSuccess {
reporter.info("charged $charged, receipt $receipt")
return keepDefault()
}
}
/** A role the shop provides: telling a customer something. */
@Role
interface Messages {
fun tell(customer: String, message: String)
}
/** Tells the customer how the order went, once, when the journey ends. */
@WorkflowPolicy(name = "notify")
class Notify : ItineraWorkflowPolicy {
@OnWorkflowSuccess
fun shipped(
@FromWorkflow customer: String,
@FromWorkflow order: String,
@FromWorkflow tracking: String,
@Role messages: Messages,
) {
messages.tell(customer, "order $order is on its way: $tracking")
}
@OnWorkflowFailure
fun failed(
@FromWorkflow customer: String,
@FromWorkflow order: String,
@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 (listed in WorkflowDescriptor.of(Orders::class.java).listing()) {
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.
val orders =
listOf(
NewOrder("A-1", "Ann", "ann-card-2028", price = 40, discount = 5, weight = 2),
NewOrder("A-2", "Ben", "ben-card-2024", price = 25, weight = 1),
NewOrder("A-3", "Cat", "cat-card-2027", price = 30, weight = 30),
NewOrder("A-4", "Dan", "dan-card-2025", price = 1200, weight = 3),
NewOrder("A-5", "Eve", "eve-card-2027", price = 20, weight = 2),
NewOrder("A-6", "Fin", "fin-card-2028", price = 1500, weight = 4),
NewOrder("A-7", "Gil", "gil-card-2029", price = 45, weight = 60),
)
// One executor runs every journey, one after another, each an instance of the workflow made
// with the order's data.
val executor = LocalExecutor()
for (order in orders) {
println("${order.order}:")
val result = executor.run(Orders().instance().initialData(order).create())
when (val status = result.status) {
is JourneyStatus.Succeeded -> println("succeeded")
is JourneyStatus.Failed -> println("failed: ${why(status.failure)}")
is JourneyStatus.Aborted -> 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 functions that meet the failure, so finding them means reading those functions. | Every retry budget, rescue step and policy is in the workflow's declaration. |
| Which services a function 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. |