The Itinera bookKotlin edition

Part 2: Getting started, Chapter 12

Trying again

What you want to do

A carrier that won't collect a parcel today may collect it on another try, a booking system that failed may work a moment later, and a bank that declines a card may accept it on a second try, so you want the shipping and the charge tried once more before an order is given up. But when the bank's network fails while charging, the bank may already have taken the money, so you want that charge never tried again.

The code

The bank and the carrier now say when something went wrong on their side: each throws an exception of the program's own, NetworkDown for the bank and BookingFailed for the carrier. Kotlin has no checked exceptions, so only their comments say so.

Kotlin, from the program ch12_trying_again
/**
 * A payment client: it charges an order's amount to a card, and gives back a receipt, or `null`
 * when the card has expired. It throws [NetworkDown] when its network fails.
 */
interface Payments {
    fun charge(order: String, card: String, amount: Long): String?
}

/**
 * A carrier: it books a parcel of this weight in kg and gives back its tracking number, or throws
 * [BookingFailed] when its booking system fails, then says whether it collects the parcel.
 */
interface Carrier {
    fun book(order: String, weight: Long): String

    fun collects(weight: Long): Boolean
}

Each exception is a class of its own, whose message says what failed:

Kotlin, from the program ch12_trying_again
/** The error of the bank's network when it fails. */
class NetworkDown : Exception("the payment network is down")

/** The error of the carrier's booking system when it fails. */
class BookingFailed : Exception("the booking system failed")

The faked bank's network fails on any amount over 100, and the faked carrier's booking system on any parcel over 100 kg. The charge charges the order's card, and fails with card-expired when the bank declines it by giving back null. Nothing in run catches the bank's exception, so it escapes the step.

Kotlin, from the program ch12_trying_again
/** Charges an order's price to its card through the payment client, and gives back its receipt. */
@Step
class Charge(
    @Input private val order: String,
    @Input private val price: Long,
    @Input private val card: String,
) : ItineraStep {
    fun run(@Service payments: Payments, contributor: Contributor): Outcome {
        if (price <= 0) return fail("nothing-to-charge")
        val receipt = payments.charge(order, card, price) ?: return fail("card-expired")
        contributor.contribute("receipt", receipt)
        return succeed()
    }
}

The shipping is chapter 9's, now giving the carrier the parcel's weight, and letting the carrier's exception escape too:

Kotlin, from the program ch12_trying_again
/**
 * Ships an order through the carrier, with its receipt in the parcel, gives back its tracking
 * number, and says when the parcel has left. A parcel the carrier won't collect may be taken on
 * another attempt.
 */
@Step
class Ship(
    @Input private val order: String,
    @Input private val weight: Long,
    @Input private val receipt: String,
) : ItineraStep {
    fun run(@Service carrier: Carrier, contributor: Contributor, reporter: StepReporter): Outcome {
        val tracking = carrier.book(order, weight)
        contributor.contribute("tracking", tracking)
        if (!carrier.collects(weight)) return fail("too-heavy")
        reporter.info("the parcel leaves with receipt $receipt")
        return succeed()
    }
}

The workflow gives both steps a retry budget of 1, with retryBudget = 1 in their @WithStep annotations, and turns off retries for the charge's errors with noRetryOnAbnormalTermination = true. The bank's provider now gives the bank the year, 2026; the ID generator and the carrier's provider are chapter 11's.

Kotlin, from the program ch12_trying_again
/**
 * The shop's workflow: it charges, then ships, and each may be tried once more, except a charge
 * that ended in an error.
 */
@Workflow(name = "orders", reporters = [Log::class, Desk::class])
@WithStep(Charge::class, name = "charge", retryBudget = 1, noRetryOnAbnormalTermination = true)
@WithStep(Ship::class, name = "ship", retryBudget = 1)
class Orders : ItineraWorkflow {
    /** The bank, as the payment client of the journey. */
    @Provider(key = "payments") fun bank(): Provided<Payments> = provide(Bank(thisYear = 2026))

    /** The main carrier, as the carrier of the journey. */
    @Provider(key = "carrier")
    fun mainCarrier(): Provided<Carrier> = provide(MainCarrier(maxWeight = 20))

    /** Names each journey after its order. */
    @IdGenerator
    fun orderNumber(data: DataBag): String =
        data.read<String>("order").orNull() ?: error("an order without a number")
}

The log and the desk are chapter 11's, and the log's detail now also names each attempt, the error that ended one, and why a step was given up:

Kotlin, from the program ch12_trying_again
/**
 * What the log says after an event's kind, for the kinds it says more about: the step the event is
 * about, and what it names.
 */
fun detail(event: Event): String? =
    when (event) {
        is JourneyStarted -> event.initialKeys.joinToString(", ")
        is AttemptStarted -> "${event.step}, attempt ${event.attempt}"
        is ServiceProvided ->
            "${event.step} gets ${event.key} from ${event.provider}, a ${event.implementation}"
        is StepSucceeded -> "${event.step}"
        is StepFailed -> "${event.step}: ${event.reason.code}"
        is StepAbnormalTermination -> "${event.step}: ${event.errorMessage}"
        is StepRetrying -> "${event.step}"
        is StepGivenUp -> "${event.step}: ${event.cause.cause}"
        is ContributionCommitted -> event.key
        is JourneyFailed -> "${event.step}"
        is StepInfo -> "${event.step}: ${event.message}"
        else -> null
    }

Each order's data now holds its card, and the receipt read back may be missing:

Kotlin, from the program ch12_trying_again
/** What the shop knows about an order when its journey starts. */
data class NewOrder(val order: String, val price: Long, val weight: Long, val card: String)

/** What the shop reads back once the journey has ended. */
data class Order(val receipt: String?, val tracking: String?)

The shop runs Ann's and Gil's orders, and three from new customers: Jo, whose card expired in 2024, Cat, who spends 120, and Dan, whose parcel weighs 150 kg.

Kotlin, from the program ch12_trying_again
fun main() {
    // The customer, and their order: its number, its price, the parcel's weight in kg and the card.
    val orders =
        listOf(
            "Ann" to NewOrder("A-1", price = 40, weight = 2, card = "ann-2028"),
            "Gil" to NewOrder("A-7", price = 45, weight = 60, card = "gil-2027"),
            "Jo" to NewOrder("A-8", price = 30, weight = 1, card = "jo-2024"),
            "Cat" to NewOrder("A-3", price = 120, weight = 3, card = "cat-2027"),
            "Dan" to NewOrder("A-4", price = 50, weight = 150, card = "dan-2028"),
        )
    for ((customer, order) in orders) {
        println("$customer's order:")
        val instance = Orders().instance().initialData(order).create()
        val result = LocalExecutor().run(instance)
        val data = result.output<Order>()
        val ended = if (result.isSucceeded) "succeeded" else "failed"
        val receipt = data.receipt ?: "none"
        val tracking = data.tracking ?: "none"
        println("the journey $ended, with receipt $receipt and tracking $tracking")
    }
}

It prints:

What ch12_trying_again prints, recorded in ch12_trying_again.txt
Ann's order:
log orders A-1 #1 journey_started order, price, weight, card
log orders A-1 #2 attempt_started charge, attempt 1
log orders A-1 #3 service_provided charge gets payments from bank, a ch12_trying_again.Bank
the bank charges 40 for order A-1
log orders A-1 #4 step_succeeded charge
log orders A-1 #5 contribution_committed receipt
log orders A-1 #6 attempt_started ship, attempt 1
log orders A-1 #7 service_provided ship gets carrier from mainCarrier, a ch12_trying_again.MainCarrier
the carrier books order A-1
log orders A-1 #8 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #9 step_succeeded ship
log orders A-1 #10 contribution_committed tracking
log orders A-1 #11 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
Gil's order:
log orders A-7 #1 journey_started order, price, weight, card
log orders A-7 #2 attempt_started charge, attempt 1
log orders A-7 #3 service_provided charge gets payments from bank, a ch12_trying_again.Bank
the bank charges 45 for order A-7
log orders A-7 #4 step_succeeded charge
log orders A-7 #5 contribution_committed receipt
log orders A-7 #6 attempt_started ship, attempt 1
log orders A-7 #7 service_provided ship gets carrier from mainCarrier, a ch12_trying_again.MainCarrier
the carrier books order A-7
log orders A-7 #8 step_failed ship: too-heavy
log orders A-7 #9 step_retrying ship
log orders A-7 #10 attempt_started ship, attempt 2
the carrier books order A-7
log orders A-7 #11 step_failed ship: too-heavy
log orders A-7 #12 step_given_up ship: retries exhausted
log orders A-7 #13 journey_failed ship
desk: order A-7 failed at ship
the journey failed, with receipt R-A-7 and tracking none
Jo's order:
log orders A-8 #1 journey_started order, price, weight, card
log orders A-8 #2 attempt_started charge, attempt 1
log orders A-8 #3 service_provided charge gets payments from bank, a ch12_trying_again.Bank
the bank declines card jo-2024: it has expired
log orders A-8 #4 step_failed charge: card-expired
log orders A-8 #5 step_retrying charge
log orders A-8 #6 attempt_started charge, attempt 2
the bank declines card jo-2024: it has expired
log orders A-8 #7 step_failed charge: card-expired
log orders A-8 #8 step_given_up charge: retries exhausted
log orders A-8 #9 journey_failed charge
desk: order A-8 failed at charge
the journey failed, with receipt none and tracking none
Cat's order:
log orders A-3 #1 journey_started order, price, weight, card
log orders A-3 #2 attempt_started charge, attempt 1
log orders A-3 #3 service_provided charge gets payments from bank, a ch12_trying_again.Bank
the bank's network fails while charging order A-3
log orders A-3 #4 step_abnormal_termination charge: the payment network is down
log orders A-3 #5 step_given_up charge: abnormal termination
log orders A-3 #6 journey_failed charge
desk: order A-3 failed at charge
the journey failed, with receipt none and tracking none
Dan's order:
log orders A-4 #1 journey_started order, price, weight, card
log orders A-4 #2 attempt_started charge, attempt 1
log orders A-4 #3 service_provided charge gets payments from bank, a ch12_trying_again.Bank
the bank charges 50 for order A-4
log orders A-4 #4 step_succeeded charge
log orders A-4 #5 contribution_committed receipt
log orders A-4 #6 attempt_started ship, attempt 1
log orders A-4 #7 service_provided ship gets carrier from mainCarrier, a ch12_trying_again.MainCarrier
the carrier's booking system fails on order A-4
log orders A-4 #8 step_abnormal_termination ship: the booking system failed
log orders A-4 #9 step_retrying ship
log orders A-4 #10 attempt_started ship, attempt 2
the carrier's booking system fails on order A-4
log orders A-4 #11 step_abnormal_termination ship: the booking system failed
log orders A-4 #12 step_given_up ship: retries exhausted
log orders A-4 #13 journey_failed ship
desk: order A-4 failed at ship
the journey failed, with receipt R-A-4 and tracking none

How it works

  1. Attempts count from 1. An attempt is one run of a step, as chapter 6 says, and every attempt after the first is a retry. Every event of an attempt, such as step_retrying, carries it as event.attempt, an Attempt from org.itineradev.itinera.step. Each attempt builds the step afresh with its constructor, from the data bag, and what a failed attempt contributed is never committed, as that chapter showed, so Gil's journey ends with no tracking number.
  2. An exception that escapes is an abnormal termination. A failure, such as card-expired, is an outcome the step chose. An exception thrown out of run is an error the step didn't handle. It ends the attempt as a failure of another kind, an abnormal termination, recorded as step_abnormal_termination with the exception's message. It never aborts the journey.
  3. The retry budget alone decides whether a step is tried again. It is the number of retries the workflow allows a step, declared in its @WithStep annotation, 0 by default. While a retry is left, a step that failed is tried again, recorded as step_retrying: Gil's shipping and Jo's charge each get attempt 2. A step reports what happened; the workflow decides whether it is tried again.
  4. An abnormal termination spends the same budget. Dan's booking failed with an exception, so the shipping was retried just as Gil's was, and failed again with the same parcel.
  5. The workflow can turn that off for a step. noRetryOnAbnormalTermination = true on the charge says an error must never be retried there, since the bank may already have taken the money. Cat's charge ended in an exception, and was given up at once with the cause abnormal termination, though a retry was left. Jo's failure, which is not an error, was retried.
  6. When the budget is spent, the step is given up. Each of Gil's, Jo's and Dan's steps failed again with no retry left, and was given up with the cause retries exhausted, the event's cause.cause.
  7. A java.lang.Error is outside the model. Itinera never catches an Error, such as a StackOverflowError or the NotImplementedError of Kotlin's TODO(): one thrown in a step stops the journey with no more events and no result, and reaches whoever called run. Throw an exception or return an outcome for anything an order can bring.

In Gil's log, there is no service_provided before the second attempt: the main carrier was made once for the journey, as chapter 7 showed, so the second attempt was lent the same carrier, which refused the same parcel again. The shop has a backup carrier, which collects parcels up to 80 kg, but no attempt is ever offered it.

Outcomes

We have shown how the workflow decides, step by step, whether a step that failed is tried again.

The usual way With Itinera
A retry is often a loop around a call, written where the call is, so how often something is tried, and which errors are safe to try again, is decided in many places. Every step's retry budget, and whether its errors are retried, is declared on its line in the workflow.
Whether a failure was retried, and why it was finally given up, is usually known only to the loop that did it. Every retry and every give-up is an event the executor records, with its cause, after the failure it answers.