# Bringing Itinera into existing code

## What you want to do

The shop's first checkout, [chapter 1](https://itinera-dev.org/book/kotlin/01-but-why-itinera.md)'s, still takes some of its orders, and it works. You want to bring it into Itinera without stopping it or rewriting it: one piece at a time, keeping the bank's client, the audit trail and the log it already has, with the checkout behaving as before after each move.

## The code

The program is [chapter 1](https://itinera-dev.org/book/kotlin/01-but-why-itinera.md)'s checkout. Its payment, which charged the card, renewed an expired one and audited the charge inside one function, is the piece moved first, into a workflow of its own, `payment`. The bank's client stays as it was: the steps ask for an interface, and a small class, `BankPayments`, implements it by calling the client's own methods:

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

```kotlin
/** What the payment's steps ask of the bank. */
interface Payments {
    fun charge(card: String, amount: Long): String

    fun renewedCard(card: String): String
}

/** The bank's client, as it was, behind the steps' interface. */
class BankPayments(private val bank: Bank) : Payments {
    override fun charge(card: String, amount: Long): String = bank.charge(card, amount)

    override fun renewedCard(card: String): String = bank.renewedCard(card)
}

```

Kotlin, the same in its asynchronous form, from the program [`ch41_bringing_itinera_into_existing_code_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch41_bringing_itinera_into_existing_code_async.kt)

```kotlin
/** What the payment's steps ask of the bank. */
interface Payments {
    suspend fun charge(card: String, amount: Long): String

    suspend fun renewedCard(card: String): String
}

/** The bank's client, as it was, behind the steps' interface. */
class BankPayments(private val bank: Bank) : Payments {
    override suspend fun charge(card: String, amount: Long): String = bank.charge(card, amount)

    override suspend fun renewedCard(card: String): String = bank.renewedCard(card)
}

```

The charge becomes a step, and the renewal its rescue step. The charge no longer renews anything: it says why it failed.

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

```kotlin
/** Charges the amount to the card, and gives back the receipt. */
@Step
class Charge(@Input private val card: String, @Input private val amount: Long) : ItineraStep {
    fun run(@Service payments: Payments, contributor: Contributor): Outcome =
        try {
            contributor.contribute("receipt", payments.charge(card, amount))
            succeed()
        } catch (declined: Declined) {
            when (declined.why) {
                Why.EXPIRED_CARD -> fail("card-expired")
                Why.REFUSED -> fail("declined")
            }
        }
}

/** Repairs a charge whose card had expired: it asks the bank for the card that replaced it. */
@RescueStep
class RenewCard(@Input private val card: String, private val reason: Reason) : ItineraRescueStep {
    fun run(@Service payments: Payments, contributor: Contributor): RescueOutcome {
        if (reason.code != "card-expired") return fail("not-repairable")
        contributor.contribute("card", payments.renewedCard(card))
        return succeed()
    }
}

```

Kotlin, the same in its asynchronous form, from the program [`ch41_bringing_itinera_into_existing_code_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch41_bringing_itinera_into_existing_code_async.kt)

```kotlin
/** Charges the amount to the card, and gives back the receipt. */
@Step
class Charge(@Input private val card: String, @Input private val amount: Long) : ItineraStep {
    suspend fun run(@Service payments: Payments, contributor: Contributor): Outcome =
        try {
            contributor.contribute("receipt", payments.charge(card, amount))
            succeed()
        } catch (declined: Declined) {
            when (declined.why) {
                Why.EXPIRED_CARD -> fail("card-expired")
                Why.REFUSED -> fail("declined")
            }
        }
}

/** Repairs a charge whose card had expired: it asks the bank for the card that replaced it. */
@RescueStep
class RenewCard(@Input private val card: String, private val reason: Reason) : ItineraRescueStep {
    suspend fun run(@Service payments: Payments, contributor: Contributor): RescueOutcome {
        if (reason.code != "card-expired") return fail("not-repairable")
        contributor.contribute("card", payments.renewedCard(card))
        return succeed()
    }
}

```

The audit becomes a policy, `AuditCharge`, which writes to the audit trail with the function the checkout already used:

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

```kotlin
/** Writes every successful charge to the shop's audit trail. */
@StepPolicy(name = "audit")
class AuditCharge : ItineraStepPolicy {
    @OnStepSuccess
    fun charged(@FromWorkflow amount: Long, @FromStep receipt: String): OnSuccess {
        Audit.record("charged $amount, receipt $receipt")
        return keepDefault()
    }
}

```

Kotlin, the same in its asynchronous form, from the program [`ch41_bringing_itinera_into_existing_code_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch41_bringing_itinera_into_existing_code_async.kt)

```kotlin
/** Writes every successful charge to the shop's audit trail. */
@StepPolicy(name = "audit")
class AuditCharge : ItineraStepPolicy {
    @OnStepSuccess
    suspend fun charged(@FromWorkflow amount: Long, @FromStep receipt: String): OnSuccess {
        Audit.record("charged $amount, receipt $receipt")
        return keepDefault()
    }
}

```

The log line the payment wrote becomes a reporter, `PaymentLog`, which writes with the shop's existing `Log.info`:

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

```kotlin
/** Writes to the shop's log when a step fails, and when a rescue step repairs it. */
class PaymentLog : Reporter {
    override fun report(event: Event) {
        when (event) {
            is StepFailed ->
                Log.info("payment ${event.journeyId}: ${event.step} failed, ${event.reason.code}")
            is StepRescued ->
                Log.info("payment ${event.journeyId}: ${event.step} repaired by ${event.rescue}")
            else -> {}
        }
    }
}

```

Kotlin, the same in its asynchronous form, from the program [`ch41_bringing_itinera_into_existing_code_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch41_bringing_itinera_into_existing_code_async.kt)

```kotlin
/** Writes to the shop's log when a step fails, and when a rescue step repairs it. */
class PaymentLog : AsyncReporter {
    override suspend fun report(event: Event) {
        when (event) {
            is StepFailed ->
                Log.info("payment ${event.journeyId}: ${event.step} failed, ${event.reason.code}")
            is StepRescued ->
                Log.info("payment ${event.journeyId}: ${event.step} repaired by ${event.rescue}")
            else -> {}
        }
    }
}

```

The workflow has one step, and its provider makes the bank's client as the checkout did:

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

```kotlin
/** Charges an order, renewing a card that has expired, and audits the charge. */
@Workflow(name = "payment", reporters = [PaymentLog::class])
@WithStep(
    Charge::class,
    name = "charge",
    rescue = RenewCard::class,
    policies = [AuditCharge::class],
)
class Payment : ItineraWorkflow {
    /** Names each journey after its order. */
    @IdGenerator
    fun orderNumber(data: DataBag): String =
        data.read<String>("order").orNull() ?: error("a payment without an order")

    /** The bank, as it is configured today. */
    @Provider(key = "payments")
    fun bank(): Provided<Payments> = provide(BankPayments(Bank(thisYear = 2026, limit = 1000)))
}

/** What a payment starts with. */
data class Due(val order: String, val card: String, val amount: Long)

/** What a payment gives back. */
data class Paid(val receipt: String)

```

Kotlin, the same in its asynchronous form, from the program [`ch41_bringing_itinera_into_existing_code_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch41_bringing_itinera_into_existing_code_async.kt)

```kotlin
/** Charges an order, renewing a card that has expired, and audits the charge. */
@Workflow(name = "payment", reporters = [PaymentLog::class])
@WithStep(
    Charge::class,
    name = "charge",
    rescue = RenewCard::class,
    policies = [AuditCharge::class],
)
class Payment : ItineraAsyncWorkflow {
    /** Names each journey after its order. */
    @IdGenerator
    fun orderNumber(data: DataBag): String =
        data.read<String>("order").orNull() ?: error("a payment without an order")

    /** The bank, as it is configured today. */
    @Provider(key = "payments")
    suspend fun bank(): Provided<Payments> =
        provide(BankPayments(Bank(thisYear = 2026, limit = 1000)))
}

/** What a payment starts with. */
data class Due(val order: String, val card: String, val amount: Long)

/** What a payment gives back. */
data class Paid(val receipt: String)

```

The rest of the checkout is chapter 1's, with three changes: `Shop` no longer holds the bank; a new exception, `PaymentNotRun`, says that the payment did not run; and the line that took the payment now calls `pay`:

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

```kotlin
/** An order, as the shop's website hands it over. */
data class Order(
    val order: String,
    val customer: String,
    val card: String,
    val price: Long,
    val discount: Long? = null,
    val weight: Long,
)

/** The payment workflow could not say how the payment went. */
class PaymentNotRun(why: String?) : Exception("the payment did not run: $why")

/** The shop, with everything it talks to. */
class Shop(
    private val warehouse: Warehouse,
    private val main: Carrier,
    private val backup: Carrier,
    private val messages: Messages,
) {
    /** Reserves, charges and ships an order, and tells the customer how it went. */
    fun checkout(order: Order): String {
        Log.info("checkout ${order.order}")
        try {
            val tracking = reserveChargeAndShip(order)
            messages.tell(order.customer, "order ${order.order} is on its way: $tracking")
            return tracking
        } catch (error: Exception) {
            Log.warn("checkout ${order.order} failed: ${error.message}")
            messages.tell(order.customer, "order ${order.order} could not be completed")
            throw error
        }
    }

    private fun reserveChargeAndShip(order: Order): String {
        warehouse.reserve(order.order)
        val amount = order.price - (order.discount ?: 0)
        pay(order.order, order.card, amount)
        return ship(main, backup, order.order, order.weight) ?: error("no carrier could take it")
    }

```

Kotlin, the same in its asynchronous form, from the program [`ch41_bringing_itinera_into_existing_code_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch41_bringing_itinera_into_existing_code_async.kt)

```kotlin
/** An order, as the shop's website hands it over. */
data class Order(
    val order: String,
    val customer: String,
    val card: String,
    val price: Long,
    val discount: Long? = null,
    val weight: Long,
)

/** The payment workflow could not say how the payment went. */
class PaymentNotRun(why: String?) : Exception("the payment did not run: $why")

/** The shop, with everything it talks to. */
class Shop(
    private val warehouse: Warehouse,
    private val main: Carrier,
    private val backup: Carrier,
    private val messages: Messages,
) {
    /** Reserves, charges and ships an order, and tells the customer how it went. */
    suspend fun checkout(order: Order): String {
        Log.info("checkout ${order.order}")
        try {
            val tracking = reserveChargeAndShip(order)
            messages.tell(order.customer, "order ${order.order} is on its way: $tracking")
            return tracking
        } catch (error: Exception) {
            Log.warn("checkout ${order.order} failed: ${error.message}")
            messages.tell(order.customer, "order ${order.order} could not be completed")
            throw error
        }
    }

    private suspend fun reserveChargeAndShip(order: Order): String {
        warehouse.reserve(order.order)
        val amount = order.price - (order.discount ?: 0)
        pay(order.order, order.card, amount)
        return ship(main, backup, order.order, order.weight) ?: error("no carrier could take it")
    }

```

`pay` runs the workflow, and turns how the journey ended back into the bank's `Declined`, as chapter 1's `takePayment` let it out:

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

```kotlin
/** Charges an order's card through the payment workflow, and gives back the receipt. */
private fun pay(order: String, card: String, amount: Long): String {
    val instance = Payment().instance().initialData(Due(order, card, amount)).create()
    val result =
        try {
            LocalExecutor().run(instance)
        } catch (refusal: Refusal) {
            throw PaymentNotRun(refusal.message)
        }
    return when (val status = result.status) {
        is JourneyStatus.Succeeded -> result.output<Paid>().receipt
        is JourneyStatus.Failed ->
            if (status.failure.reason?.code == "card-expired") throw Declined(Why.EXPIRED_CARD)
            else throw Declined(Why.REFUSED)
        is JourneyStatus.Aborted -> throw PaymentNotRun("${status.abort.reason}")
    }
}
```

Kotlin, the same in its asynchronous form, from the program [`ch41_bringing_itinera_into_existing_code_async`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch41_bringing_itinera_into_existing_code_async.kt)

```kotlin
/** Charges an order's card through the payment workflow, and gives back the receipt. */
private suspend fun pay(order: String, card: String, amount: Long): String {
    val instance = Payment().instance().initialData(Due(order, card, amount)).create()
    val result =
        try {
            AsyncLocalExecutor().run(instance)
        } catch (refusal: Refusal) {
            throw PaymentNotRun(refusal.message)
        }
    return when (val status = result.status) {
        is JourneyStatus.Succeeded -> result.output<Paid>().receipt
        is JourneyStatus.Failed ->
            if (status.failure.reason?.code == "card-expired") throw Declined(Why.EXPIRED_CARD)
            else throw Declined(Why.REFUSED)
        is JourneyStatus.Aborted -> throw PaymentNotRun("${status.abort.reason}")
    }
}
```

The asynchronous form starts from a checkout that was already asynchronous: the bank's client's methods, `checkout` and `pay` are `suspend` functions, and `main` runs inside `runBlocking`. `Payments` and `BankPayments`, the steps' `run`, the audit's hook and the provider are `suspend` functions too, the log is an `AsyncReporter`, `Payment` implements `ItineraAsyncWorkflow`, and `pay` runs the journey with an `AsyncLocalExecutor`, as in [chapter 26](https://itinera-dev.org/book/kotlin/26-running-async-journeys-while-others-wait.md). `main` is chapter 1's, with the same four orders, and both forms print:

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

```text
INFO checkout A-1
AUDIT charged 35, receipt R-ann-card-2028-35
to Ann: order A-1 is on its way: T-A-1
A-1: shipped, T-A-1

INFO checkout A-2
INFO payment A-2: charge failed, card-expired
INFO payment A-2: charge repaired by charge_rescue
AUDIT charged 25, receipt R-ben-card-2029-25
to Ben: order A-2 is on its way: T-A-2
A-2: shipped, T-A-2

INFO checkout A-3
AUDIT charged 30, receipt R-cat-card-2027-30
WARN Rapid cannot take A-3: 30 kg is over its 20 kg limit; trying Steady
to Cat: order A-3 is on its way: B-A-3
A-3: shipped, B-A-3

INFO checkout A-4
INFO payment A-4: charge failed, card-expired
INFO payment A-4: charge repaired by charge_rescue
INFO payment A-4: charge failed, declined
WARN checkout A-4 failed: payment declined
to Dan: order A-4 could not be completed
A-4: failed, payment declined
```

## How it works

1. **The rest of the program doesn't know.** `checkout` still returns the same tracking number and lets out the same exceptions, the shipping and the messages are untouched, and each order ends as it did in chapter 1. `pay` is the only seam: it creates an instance, runs its journey and reads how it ended.
2. **Existing code is kept, behind the workflow's parts.** The bank's client is a service through the interface `BankPayments` implements, the audit trail is called from a policy, and the log from a reporter. What moves into the workflow is the decisions: when to renew a card, and when to audit. The code that talks to the outside world stays where it was.
3. **The log now says what happened.** Chapter 1's payment logged that it was renewing a card, before it tried. Now the log follows the journey's events: Ben's charge failed with `card-expired` and the rescue step repaired it, and the audit trail shows the charge then went through. Dan's was repaired too, then failed again, `declined`, which chapter 1's log never said.
4. **One piece at a time.** The shipping, with its backup carrier, and the messages to the customer are still chapter 1's code, running beside the workflow. Each can move next: the shipping as a step with a retry budget and a provider for each attempt, the messages as a policy acting through a role. Move one piece, run the program, and compare what it prints with what it printed before.
5. **Where Itinera fits, and where it doesn't.** It fits a piece of business with decisions around it: whether to try again, how to repair, what to record and whom to tell. A single call with nothing to decide around it, such as reserving the goods here, gains nothing from a workflow of its own. It stays a call, or becomes a step of a workflow that has decisions to make.

The checkout's payment is now a workflow, and the shop has one way to charge a card. It also wants a second way to sell: customers collecting their orders at the shop's counter, paying at the counter's terminal, with nothing to ship.

## Outcomes

We have shown how to bring Itinera into code that already works, one piece at a time, keeping the code that talks to the outside world.

| The usual way                                                                              | With Itinera                                                                |
| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| Untangling a function often means rewriting it, and its callers, in one go.                | One piece becomes a workflow behind a function the callers already call.    |
| A client, a log or an audit trail written for the old code is often rewritten for the new. | Each stays, called from a service's implementation, a policy or a reporter. |
