# Running async journeys while others wait

## What you want to do

The shop's bank and carriers answer over the network, and while one order waits for them, the program's thread waits too. You want the shop to take other orders forward in the meantime.

## The code

The shop is [chapter 25](https://itinera-dev.org/book/kotlin/25-reading-the-result.md)'s, written in Itinera's other **execution mode**: asynchronous, on Kotlin's coroutines, where a `suspend` function waits for an answer without holding its thread. `itinera-kotlin` brings this mode. To start coroutines itself, as `main` does, the shop adds kotlinx.coroutines, Kotlin's library of coroutines, to its build, as `org.jetbrains.kotlinx:kotlinx-coroutines-core`.

The payment client and the carrier now answer over the network, so their methods are `suspend` functions, still throwing [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md)'s errors. The order book answers from the shop's own records without waiting, so it stays as [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md) shows it:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/**
 * 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. And it says which card
 * replaced one, or `null` when none did. Each answer comes over the network.
 */
interface Payments {
    suspend fun charge(order: String, card: String, amount: Long): String?

    suspend fun replacement(card: String): 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. Each
 * answer comes over the network.
 */
interface Carrier {
    suspend fun book(order: String, weight: Long): String

    suspend fun collects(weight: Long): Boolean
}

```

The faked bank and carriers call `network` before each answer. It calls `yield()`, from kotlinx.coroutines, which hands the thread back once, as a real call does while it waits for the other side:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/**
 * The network the fakes answer over: it hands the thread back once before the answer comes, as a
 * real call does while it waits.
 */
suspend fun network() {
    yield()
}

/**
 * The shop's bank, faked: a card is its holder's name and the year it expires, and the bank
 * declines a card that expired before this year. Its network fails on any amount over 100. It
 * prints what it does once it has answered.
 */
class Bank(private val thisYear: Int) : Payments {
    override suspend fun charge(order: String, card: String, amount: Long): String? {
        network()
        if (amount > 100) {
            println("the bank's network fails while charging order $order")
            throw NetworkDown()
        }
        if (expiry(card) < thisYear) {
            println("the bank declines card $card: it has expired")
            return null
        }
        println("the bank charges $amount for order $order")
        return "R-$order"
    }

    /**
     * A card that expired in the last three years was replaced by its holder's card that expires in
     * three years. An older one was not.
     */
    override suspend fun replacement(card: String): String? {
        network()
        if (expiry(card) + 3 < thisYear) {
            println("the bank says nothing replaced card $card")
            return null
        }
        val replacement = "${card.substringBeforeLast('-')}-${thisYear + 3}"
        println("the bank says card $card was replaced by $replacement")
        return replacement
    }
}

```

Each step's `run` becomes a `suspend` function, even the pricing's, which has nothing to wait for:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/**
 * Works out what an order costs: its price, less its discount if it has one, given back as the
 * amount to charge.
 */
@Step
class Price(@Input private val price: Long, @Input private val discount: Long?) : ItineraStep {
    suspend fun run(contributor: Contributor): Outcome {
        contributor.contribute("amount", price - (discount ?: 0L))
        return succeed()
    }
}

```

The shipping's step reporter is now an `AsyncStepReporter`, from `org.itineradev.itinera.step.async`, whose `info` is a `suspend` function too:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/**
 * 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. A gift card has nothing to ship, and the shop ships no parcel over 80 kg.
 */
@Step
class Ship(
    @Input private val order: String,
    @Input private val weight: Long,
    @Input private val receipt: String,
    @Input private val giftCard: Boolean,
) : ItineraStep {
    suspend fun run(
        @Service carrier: Carrier,
        contributor: Contributor,
        reporter: AsyncStepReporter,
    ): Outcome {
        if (giftCard) return skipBecause("nothing-to-ship")
        if (weight > 80) return fail("over-parcel-limit")
        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()
    }
}

```

Telling a customer and giving money back go over the network too, so the shop's roles become `suspend` the same way. A role whose methods don't wait may stay as it is, as a service may, like the order book:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/** What the shop does for its policies: tell a customer something. */
@Role
interface Messages {
    suspend fun tell(customer: String, message: String)
}

/** What the shop does for its policies: give an order's money back. */
@Role
interface Refunds {
    suspend fun refund(receipt: String, amount: Long)
}

```

Each hook becomes a `suspend` function as well, and so does `refund`, which calls a role:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/**
 * Deals with a shipping that fails for good. It gives up a parcel over the shop's limit rather than
 * try it again, since the limit is the same on every attempt, whichever carrier comes. And whatever
 * gave the shipping up, it refunds the order's charge.
 */
@StepPolicy(name = "failedShipping")
class FailedShipping : ItineraStepPolicy {
    @OnStepRetry
    suspend fun beforeRetrying(
        reason: Reason?,
        @FromWorkflow receipt: String,
        @FromWorkflow amount: Long,
        @Role refunds: Refunds,
        contributor: Contributor,
    ): OnFailure {
        if (reason?.code != "over-parcel-limit") return keepDefault()
        refund(refunds, contributor, receipt, amount, "over-parcel-limit")
        return failWorkflow("no-carrier-can-take-it")
    }

    @OnStepFailure
    suspend fun givenUp(
        cause: FailureCause,
        @FromWorkflow receipt: String,
        @FromWorkflow amount: Long,
        @Role refunds: Refunds,
        contributor: Contributor,
    ): OnFailure {
        refund(refunds, contributor, receipt, amount, "$cause")
        return keepDefault()
    }

    /** Gives the order's money back, and records why. */
    private suspend fun refund(
        refunds: Refunds,
        contributor: Contributor,
        receipt: String,
        amount: Long,
        why: String,
    ) {
        refunds.refund(receipt, amount)
        contributor.contribute("refund", "$amount back on $receipt: $why")
    }
}

```

The log and the desk now implement `AsyncReporter`, from `org.itineradev.itinera.report.async`, whose `report` is a `suspend` function:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/**
 * The shop's log: it writes a line for every event of a journey, starting with the workflow's name
 * and the journey's ID.
 */
class Log : AsyncReporter {
    override suspend fun report(event: Event) {
        val line = "log ${event.workflow} ${event.journeyId} #${event.sequence} ${event.kind}"
        when (val detail = detail(event)) {
            null -> println(line)
            else -> println("$line $detail")
        }
    }
}

/** The customer service desk: of all the events of a journey, it keeps only a failed journey's. */
class Desk : AsyncReporter {
    override suspend fun report(event: Event) {
        if (event is JourneyFailed)
            println("desk: order ${event.journeyId} failed at ${event.step}")
    }
}

```

The workflow class implements `ItineraAsyncWorkflow`, from `org.itineradev.itinera.workflow.async`, in place of `ItineraWorkflow`. Its providers and its input adapter become `suspend` functions, and its roles' methods call `network` before they answer:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/**
 * The shop's workflow: it looks the order up, and finishes an order already completed. Otherwise it
 * works out what the order costs, then charges it, repairing a charge that fails and auditing one
 * that succeeds, then ships, and shipping may be tried once more. Once a journey has ended, the
 * customer is told, through the channel the shop configures.
 */
@Workflow(name = "orders", reporters = [Log::class, Desk::class], policies = [Notify::class])
@WithStep(Lookup::class, name = "lookup", policies = [AlreadyCompleted::class])
@WithStep(Price::class, name = "price")
@WithStep(
    Charge::class,
    name = "charge",
    rescue = RenewCard::class,
    policies = [Audit::class, Outage::class],
)
@WithStep(Ship::class, name = "ship", retryBudget = 1, policies = [FailedShipping::class])
class Orders(private val channel: String) : ItineraAsyncWorkflow, Messages, Refunds {
    override suspend fun tell(customer: String, message: String) {
        network()
        println("$channel to $customer: $message")
    }

    override suspend fun refund(receipt: String, amount: Long) {
        network()
        println("the bank gives $amount back on receipt $receipt")
    }

    /** The bank, as the payment client of the journey. */
    @Provider(key = "payments")
    suspend fun bank(): Provided<Payments> = provide(Bank(thisYear = 2026))

    /** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
    @Provider(perAttempt = true, key = "carrier")
    suspend fun carriers(attempt: Attempt): Provided<Carrier> =
        if (attempt.isFirst) provide(MainCarrier()) else provide(BackupCarrier())

    /**
     * Gives the shipping the weight of the order's parcel, as the warehouse describes it. Every
     * other input of the shipping is read from the data bag.
     */
    @InputAdapter(steps = ["ship"])
    suspend fun parcels(@Key key: String, @FromWorkflow parcel: Parcel): Supplied =
        if (key == "weight") supply(parcel.weight) else fromDataBag()

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

    /** The order book, which has the orders completed before today. */
    @Provider(key = "orderBook")
    suspend fun ledger(): Provided<OrderBook> = provide(Ledger(listOf("A-13")))
}

```

Every other step and hook it names only adds `suspend`: the lookup and `AlreadyCompleted` are otherwise [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md)'s, the charge and the audit [chapter 20](https://itinera-dev.org/book/kotlin/20-an-optional-input.md)'s, `RenewCard` [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md)'s, `Outage` [chapter 17](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md)'s and `Notify` [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md)'s. The log's `detail` is [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md)'s, with the parts that page points to.

`main` runs three of the day's orders, Ann's, Gil's and Jo's, at the same time. `journey` makes each one's instance as [chapter 25](https://itinera-dev.org/book/kotlin/25-reading-the-result.md)'s `main` did, and runs it with an executor of its own, an `AsyncLocalExecutor`, from `org.itineradev.itinera.executor.async`. `runBlocking`, from kotlinx.coroutines, runs a coroutine on `main`'s own thread until it ends; inside it, `async` starts a coroutine for each journey, and `awaitAll` gives their results in order. The journeys take turns on that one thread, so the output is the same on every run. `NewOrder` is [chapter 25](https://itinera-dev.org/book/kotlin/25-reading-the-result.md)'s, and `Parcel` [chapter 21](https://itinera-dev.org/book/kotlin/21-deciding-where-a-steps-data-comes-from.md)'s:

Kotlin, from the program [`ch26_running_async_journeys_while_others_wait`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch26_running_async_journeys_while_others_wait.kt)

```kotlin
/** Runs an order's journey with an executor of its own. */
suspend fun journey(order: NewOrder): JourneyResult {
    val instance = Orders(channel = "email").instance().initialData(order).create()
    return AsyncLocalExecutor().run(instance)
}

fun main() {
    // Each order: its number, its customer, its price, its discount if it has one, its parcel, as
    // its weight in kg and its size in cm, and the card.
    val orders =
        listOf(
            NewOrder(
                "A-1",
                "Ann",
                price = 40,
                discount = 10,
                parcel = Parcel(weight = 2, size = listOf(30, 20, 10)),
                card = "ann-2028",
            ),
            NewOrder(
                "A-7",
                "Gil",
                price = 45,
                parcel = Parcel(weight = 60, size = listOf(120, 80, 60)),
                card = "gil-2027",
            ),
            NewOrder(
                "A-8",
                "Jo",
                price = 30,
                parcel = Parcel(weight = 1, size = listOf(20, 15, 5)),
                card = "jo-2024",
            ),
        )
    runBlocking {
        val results = orders.map { order -> async { journey(order) } }.awaitAll()
        for (result in results) {
            val ended = if (result.isSucceeded) "succeeded" else "failed"
            println("order ${result.journeyId} $ended")
        }
    }
}
```

It prints:

What `ch26_running_async_journeys_while_others_wait` prints, recorded in [`ch26_running_async_journeys_while_others_wait.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/expected/ch26_running_async_journeys_while_others_wait.txt)

```text
log orders A-1 #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 #2 attempt_started lookup, attempt 1
log orders A-1 #3 service_provided lookup gets orderBook from ledger, a ch26_running_async_journeys_while_others_wait.Ledger
the order book has no order A-1 yet
log orders A-1 #4 step_succeeded lookup
log orders A-1 #5 contribution_committed completed
log orders A-1 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 #7 attempt_started price, attempt 1
log orders A-1 #8 step_succeeded price
log orders A-1 #9 contribution_committed amount
log orders A-1 #10 attempt_started charge, attempt 1
log orders A-1 #11 service_provided charge gets payments from bank, a ch26_running_async_journeys_while_others_wait.Bank
log orders A-7 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-7 #2 attempt_started lookup, attempt 1
log orders A-7 #3 service_provided lookup gets orderBook from ledger, a ch26_running_async_journeys_while_others_wait.Ledger
the order book has no order A-7 yet
log orders A-7 #4 step_succeeded lookup
log orders A-7 #5 contribution_committed completed
log orders A-7 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-7 #7 attempt_started price, attempt 1
log orders A-7 #8 optional_input_absent discount
log orders A-7 #9 step_succeeded price
log orders A-7 #10 contribution_committed amount
log orders A-7 #11 attempt_started charge, attempt 1
log orders A-7 #12 service_provided charge gets payments from bank, a ch26_running_async_journeys_while_others_wait.Bank
log orders A-8 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 #2 attempt_started lookup, attempt 1
log orders A-8 #3 service_provided lookup gets orderBook from ledger, a ch26_running_async_journeys_while_others_wait.Ledger
the order book has no order A-8 yet
log orders A-8 #4 step_succeeded lookup
log orders A-8 #5 contribution_committed completed
log orders A-8 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 #7 attempt_started price, attempt 1
log orders A-8 #8 optional_input_absent discount
log orders A-8 #9 step_succeeded price
log orders A-8 #10 contribution_committed amount
log orders A-8 #11 attempt_started charge, attempt 1
log orders A-8 #12 service_provided charge gets payments from bank, a ch26_running_async_journeys_while_others_wait.Bank
the bank charges 30 for order A-1
log orders A-1 #12 step_succeeded charge
log orders A-1 #13 contribution_committed receipt
log orders A-1 #14 hook_called audit: on step success of charge
log orders A-1 #15 contribution_committed audit
log orders A-1 #16 attempt_started ship, attempt 1
log orders A-1 #17 input_adapter_supplied ship gets weight from parcels
log orders A-1 #18 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.MainCarrier
the bank charges 45 for order A-7
log orders A-7 #13 step_succeeded charge
log orders A-7 #14 contribution_committed receipt
log orders A-7 #15 hook_called audit: on step success of charge
log orders A-7 #16 contribution_committed audit
log orders A-7 #17 attempt_started ship, attempt 1
log orders A-7 #18 input_adapter_supplied ship gets weight from parcels
log orders A-7 #19 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.MainCarrier
the bank declines card jo-2024: it has expired
log orders A-8 #13 step_failed charge: card-expired
log orders A-8 #14 step_rescuing charge: failure, rescued by charge_rescue
log orders A-8 #15 attempt_started charge_rescue, attempt 1
the main carrier books order A-1
the main carrier books order A-7
the bank says card jo-2024 was replaced by jo-2029
log orders A-8 #16 step_succeeded charge_rescue
log orders A-8 #17 contribution_committed card
log orders A-8 #18 data_overwritten card
log orders A-8 #19 step_rescued charge by charge_rescue
log orders A-8 #20 attempt_started charge, attempt 2
log orders A-1 #19 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #20 step_succeeded ship
log orders A-1 #21 contribution_committed tracking
log orders A-1 #22 optional_input_absent code
log orders A-7 #20 step_failed ship: too-heavy
log orders A-7 #21 hook_called failedShipping: on step retry of ship
log orders A-7 #22 step_retrying ship
log orders A-7 #23 attempt_started ship, attempt 2
log orders A-7 #24 input_adapter_supplied ship gets weight from parcels
log orders A-7 #25 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.BackupCarrier
the bank charges 30 for order A-8
log orders A-8 #21 step_succeeded charge
log orders A-8 #22 contribution_committed receipt
log orders A-8 #23 hook_called audit: on step success of charge
log orders A-8 #24 contribution_committed audit
log orders A-8 #25 attempt_started ship, attempt 1
log orders A-8 #26 input_adapter_supplied ship gets weight from parcels
log orders A-8 #27 service_provided ship gets carrier from carriers, a ch26_running_async_journeys_while_others_wait.MainCarrier
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 #23 hook_called notify: on workflow success
log orders A-1 #24 journey_succeeded
the backup carrier books order A-7
the main carrier books order A-8
log orders A-7 #26 step_info ship: the parcel leaves with receipt R-A-7
log orders A-7 #27 step_succeeded ship
log orders A-7 #28 contribution_committed tracking
log orders A-7 #29 optional_input_absent code
log orders A-8 #28 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 #29 step_succeeded ship
log orders A-8 #30 contribution_committed tracking
log orders A-8 #31 optional_input_absent code
email to Gil: Order A-7 is on its way, tracking B-A-7.
log orders A-7 #30 hook_called notify: on workflow success
log orders A-7 #31 journey_succeeded
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 #32 hook_called notify: on workflow success
log orders A-8 #33 journey_succeeded
order A-1 succeeded
order A-7 succeeded
order A-8 succeeded
```

## How it works

1. **A workflow is in one execution mode, the one of the interface its class implements,** and so is every part of it: with `ItineraAsyncWorkflow`, every step, hook, provider, input adapter and reporter is `suspend`, even the pricing, which never waits. Only the ID generator is an ordinary function in both modes, since `create()`, an ordinary function, calls it.
2. **`AsyncLocalExecutor` runs asynchronous journeys,** as `LocalExecutor` runs synchronous ones, in the coroutine that calls its `run`. The journeys end as they did in chapter 25: Gil's parcel goes with the backup carrier, and Jo's card is renewed.
3. **A journey that waits lets the others go on.** Ann's journey runs until its charge waits for the bank. Then Gil's starts, and runs until it waits for the bank too, then Jo's. As each answer comes, its journey goes on from where it waited, so the log interleaves the three journeys, in the order the answers came. Each line names its journey, and each journey's events are still numbered from `#1`.
4. **The executor chooses no thread.** A journey runs in the coroutine that calls `run`, here `runBlocking`'s, on `main`'s thread. On `Dispatchers.Default`, which has several threads, the shop runs just the same, though the lines of different journeys may come in another order. A `suspend` function must not block its thread, so a part that calls a blocking library calls it inside `withContext(Dispatchers.IO)`.
5. **An executor runs one journey at a time,** as [chapter 24](https://itinera-dev.org/book/kotlin/24-running-many-journeys.md) showed, so each journey that runs at the same time as others gets an executor of its own.

Ann's, Gil's and Jo's journeys now go on together, each while the others wait. But the only way to know that the shop still gives the same answers after a change is to run every order again, against the bank and the carriers, and read the log.

## Outcomes

We have shown how the shop runs in the asynchronous execution mode, with journeys going on at the same time while others wait.

| The usual way                                                                                             | With Itinera                                                                                                                                                                            |
| --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Making code asynchronous often means changing every function between the request and the call that waits. | The parts of the workflow become `suspend` functions, and the workflow class implements `ItineraAsyncWorkflow`; the annotations that declare it, and what each part does, don't change. |
