# Mistakes caught before a journey

## What you want to do

The shop's workflow is now put together from many parts: steps and their names, policies attached to them, an input adapter, services and their providers, a rescue step and roles. You want to see how it is put together without running an order, and to know that a mistake in putting it together is caught before any order runs.

## The code

### How the workflow is put together

The shop is the one [chapter 36](https://itinera-dev.org/book/kotlin/36-orders-refused-before-they-start.md) runs: `Orders` is the workflow [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md) declares, with [chapter 35](https://itinera-dev.org/book/kotlin/35-giving-the-rescue-step-a-service-of-its-own.md)'s provider for `cards`. `main` prints its **listing**, one entry for each step. `WorkflowDescriptor.of(Orders::class.java)`, from `org.itineradev.itinera.workflow`, reads the workflow's declaration from its annotations, and `listing()` lists it:

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

```kotlin
for (listed in WorkflowDescriptor.of(Orders::class.java).listing()) {
    println(entry(listed))
}
```

`entry` writes each step's line from what the listing says about it, and `services`, with `service` for each one, writes the services of a step or of its rescue step. The entries are `ListedStep`s, and their services `ListedService`s, both from the same package:

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

```kotlin
/** A service in the listing: its key, and the provider that serves it. */
fun service(listed: ListedService): String = "${listed.key} from ${listed.provider}"

/** The services of a listing's entry, separated by commas. */
fun services(listed: List<ListedService>): String = listed.joinToString(", ", transform = ::service)

/**
 * One entry of the listing: a step's position and name, its policies, its adapter, its services
 * with the provider that serves each, and its rescue step with its services.
 */
fun entry(listed: ListedStep): String = buildString {
    append("${listed.position}. ${listed.step}")
    if (listed.policies.isNotEmpty()) append(", with ${listed.policies.joinToString(", ")}")
    listed.adapter?.let { append("; adapted by $it") }
    if (listed.services.isNotEmpty()) append("; services: ${services(listed.services)}")
    listed.rescue?.let { append("; rescued by ${it.step}, services: ${services(it.services)}") }
}

```

It prints:

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

```text
1. lookup, with alreadyCompleted; services: orderBook from ledger
2. price
3. charge, with audit, outage; services: payments from bank; rescued by charge_rescue, services: cards from cards
4. ship, with failedShipping; adapted by parcels; services: carrier from carriers
```

### Mistakes that don't compile

Every program in this book is built with itinera's checker, `itinera-checker`, which checks each annotated workflow while the program is built. An application adds it through KSP: in Gradle's Kotlin DSL, the plugin `id("com.google.devtools.ksp") version "2.3.12"`, the release the checker is built against, then `ksp(platform("org.itinera-dev:itinera-bom:VERSION"))` and `ksp("org.itinera-dev:itinera-checker")` under `dependencies`.

Each program below is a small shop with one mistake, and none of them compiles. The shipping listed twice:

Kotlin, the program [`ch37_duplicate_step_name`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_duplicate_step_name.kt). **Does not compile**

```kotlin
// The shipping listed twice.

package ch37_duplicate_step_name

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.journey.Contributor
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.ItineraWorkflow
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow

/** Charges an order. */
@Step
class Charge : ItineraStep {
    fun run(contributor: Contributor): Outcome {
        contributor.contribute("receipt", "R-1")
        return succeed()
    }
}

/** Ships an order. */
@Step
class Ship : ItineraStep {
    fun run(): Outcome = succeed()
}

/** The shop's workflow, with the shipping listed twice under one name. */
@Workflow(name = "orders")
@WithStep(Charge::class, name = "charge")
@WithStep(Ship::class, name = "ship")
@WithStep(Ship::class, name = "ship")
class Orders : ItineraWorkflow

fun main() {
    val result = LocalExecutor().run(Orders().instance().create())
    println("the journey ${result.status}")
}
```

What the compiler says about `ch37_duplicate_step_name`, recorded in [`ch37_duplicate_step_name.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_duplicate_step_name.txt)

```text
e: [ksp] compile-errors/ch37_duplicate_step_name.kt:34: duplicate step name: two steps are named ship
```

Two policies of the charge that both define `on step success`:

Kotlin, the program [`ch37_hook_defined_twice`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_hook_defined_twice.kt). **Does not compile**

```kotlin
// Two policies of one step that both define `on step success`.

package ch37_hook_defined_twice

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.journey.Contributor
import org.itineradev.itinera.policy.FromStep
import org.itineradev.itinera.policy.ItineraStepPolicy
import org.itineradev.itinera.policy.OnStepSuccess
import org.itineradev.itinera.policy.OnSuccess
import org.itineradev.itinera.policy.StepPolicy
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.ItineraWorkflow
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow

/** Charges an order. */
@Step
class Charge : ItineraStep {
    fun run(contributor: Contributor): Outcome {
        contributor.contribute("charged", 40L)
        return succeed()
    }
}

/** Audits every successful charge. */
@StepPolicy(name = "audit")
class Audit : ItineraStepPolicy {
    @OnStepSuccess
    fun audited(@FromStep charged: Long): OnSuccess {
        println("audit: charged $charged")
        return keepDefault()
    }
}

/** Writes a receipt for every successful charge. */
@StepPolicy(name = "receipts")
class Receipts : ItineraStepPolicy {
    @OnStepSuccess
    fun written(@FromStep charged: Long): OnSuccess {
        println("receipt: R-$charged")
        return keepDefault()
    }
}

/** The shop's workflow, with both policies attached to the charge. */
@Workflow(name = "orders")
@WithStep(Charge::class, name = "charge", policies = [Audit::class, Receipts::class])
class Orders : ItineraWorkflow

fun main() {
    val result = LocalExecutor().run(Orders().instance().create())
    println("the journey ${result.status}")
}
```

What the compiler says about `ch37_hook_defined_twice`, recorded in [`ch37_hook_defined_twice.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_hook_defined_twice.txt)

```text
e: [ksp] compile-errors/ch37_hook_defined_twice.kt:51: hook defined twice: step policies audit, receipts of step charge all define on step success
```

A policy that tells the customer through the `Messages` [role](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md), on a workflow that doesn't implement it:

Kotlin, the program [`ch37_role_not_provided`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_role_not_provided.kt). **Does not compile**

```kotlin
// A policy that needs a role the workflow does not provide.

package ch37_role_not_provided

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.policy.FromWorkflow
import org.itineradev.itinera.policy.ItineraWorkflowPolicy
import org.itineradev.itinera.policy.OnWorkflowSuccess
import org.itineradev.itinera.policy.Role
import org.itineradev.itinera.policy.WorkflowPolicy
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.ItineraWorkflow
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow

/** Charges an order. */
@Step
class Charge : ItineraStep {
    fun run(): Outcome = succeed()
}

/** The shop's way of telling a customer something. */
@Role
interface Messages {
    fun tell(customer: String, message: String)
}

/** Tells the customer once the order is complete. */
@WorkflowPolicy(name = "notify")
class Notify : ItineraWorkflowPolicy {
    @OnWorkflowSuccess
    fun completed(@FromWorkflow customer: String, @Role messages: Messages) {
        messages.tell(customer, "your order is complete")
    }
}

/** The shop's workflow. It can tell a customer something, but does not implement the role. */
@Workflow(name = "orders", policies = [Notify::class])
@WithStep(Charge::class, name = "charge")
class Orders : ItineraWorkflow {
    fun tell(customer: String, message: String) {
        println("to $customer: $message")
    }
}

/** What the shop knows about an order when its journey starts. */
data class NewOrder(val customer: String)

fun main() {
    val instance = Orders().instance().initialData(NewOrder(customer = "Ann")).create()
    println("the journey ${LocalExecutor().run(instance).status}")
}
```

What the compiler says about `ch37_role_not_provided`, recorded in [`ch37_role_not_provided.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_role_not_provided.txt)

```text
e: [ksp] compile-errors/ch37_role_not_provided.kt:42: role not provided: policy notify requests role ch37_role_not_provided.Messages, which the workflow does not provide
```

An `on step failure` hook that tries to finish the journey as succeeded, which only `on step success` may do:

Kotlin, the program [`ch37_invalid_lifecycle`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_invalid_lifecycle.kt). **Does not compile**

```kotlin
// An `on step failure` hook that tries to finish the journey as succeeded.

package ch37_invalid_lifecycle

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.policy.ItineraStepPolicy
import org.itineradev.itinera.policy.OnFailure
import org.itineradev.itinera.policy.OnStepFailure
import org.itineradev.itinera.policy.StepPolicy
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.ItineraWorkflow
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow

/** Charges an order, and fails: the card was declined. */
@Step
class Charge : ItineraStep {
    fun run(): Outcome = fail("card-declined")
}

/** Tries to finish the journey as succeeded when the charge fails. */
@StepPolicy(name = "forgiving")
class Forgiving : ItineraStepPolicy {
    @OnStepFailure fun declined(): OnFailure = finishWorkflow()
}

/** The shop's workflow. */
@Workflow(name = "orders")
@WithStep(Charge::class, name = "charge", policies = [Forgiving::class])
class Orders : ItineraWorkflow

fun main() {
    val result = LocalExecutor().run(Orders().instance().create())
    println("the journey ${result.status}")
}
```

What the compiler says about `ch37_invalid_lifecycle`, recorded in [`ch37_invalid_lifecycle.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_invalid_lifecycle.txt)

```text
e: compile-errors/ch37_invalid_lifecycle.kt:26:48 Return type mismatch: expected 'OnFailure', actual 'Lifecycle.FinishWorkflow'.
```

The same hook, declared to return an `OnSuccess` so that `finishWorkflow()` fits:

Kotlin, the program [`ch37_hook_of_the_wrong_kind`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_hook_of_the_wrong_kind.kt). **Does not compile**

```kotlin
// An `on step failure` hook declared to return what only `on step success` returns.

package ch37_hook_of_the_wrong_kind

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.policy.ItineraStepPolicy
import org.itineradev.itinera.policy.OnStepFailure
import org.itineradev.itinera.policy.OnSuccess
import org.itineradev.itinera.policy.StepPolicy
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.ItineraWorkflow
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow

/** Charges an order, and fails: the card was declined. */
@Step
class Charge : ItineraStep {
    fun run(): Outcome = fail("card-declined")
}

/** Tries to finish the journey as succeeded when the charge fails. */
@StepPolicy(name = "forgiving")
class Forgiving : ItineraStepPolicy {
    @OnStepFailure fun declined(): OnSuccess = finishWorkflow()
}

/** The shop's workflow. */
@Workflow(name = "orders")
@WithStep(Charge::class, name = "charge", policies = [Forgiving::class])
class Orders : ItineraWorkflow

fun main() {
    val result = LocalExecutor().run(Orders().instance().create())
    println("the journey ${result.status}")
}
```

What the compiler says about `ch37_hook_of_the_wrong_kind`, recorded in [`ch37_hook_of_the_wrong_kind.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_hook_of_the_wrong_kind.txt)

```text
e: [ksp] compile-errors/ch37_hook_of_the_wrong_kind.kt:26: ch37_hook_of_the_wrong_kind.Forgiving.declined returns OnSuccess, not OnFailure
```

A rescue step that tries to skip the charge rather than repair it:

Kotlin, the program [`ch37_rescue_step_skips`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_rescue_step_skips.kt). **Does not compile**

```kotlin
// A rescue step that tries to skip the charge rather than repair it.

package ch37_rescue_step_skips

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.step.ItineraRescueStep
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.RescueOutcome
import org.itineradev.itinera.step.RescueStep
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.ItineraWorkflow
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow

/** Charges an order, and fails: the card has expired. */
@Step
class Charge : ItineraStep {
    fun run(): Outcome = fail("card-expired")
}

/** Gives up on the card, and tries to skip the charge. */
@RescueStep
class LetItGo : ItineraRescueStep {
    fun run(): RescueOutcome = skipBecause("card-expired")
}

/** The shop's workflow. */
@Workflow(name = "orders")
@WithStep(Charge::class, name = "charge", rescue = LetItGo::class)
class Orders : ItineraWorkflow

fun main() {
    val result = LocalExecutor().run(Orders().instance().create())
    println("the journey ${result.status}")
}
```

What the compiler says about `ch37_rescue_step_skips`, recorded in [`ch37_rescue_step_skips.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_rescue_step_skips.txt)

```text
e: compile-errors/ch37_rescue_step_skips.kt:25:32 Unresolved reference 'skipBecause'.
```

An input adapter that asks for its read access to the data bag, a `DataBagAccess` from `org.itineradev.itinera.journey`, and tries to write the weight into it:

Kotlin, the program [`ch37_adapter_writes_the_data_bag`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_adapter_writes_the_data_bag.kt). **Does not compile**

```kotlin
// An input adapter that asks for the data bag, and tries to write the weight into it.

package ch37_adapter_writes_the_data_bag

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.journey.DataBagAccess
import org.itineradev.itinera.policy.FromWorkflow
import org.itineradev.itinera.step.Input
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.InputAdapter
import org.itineradev.itinera.workflow.ItineraWorkflow
import org.itineradev.itinera.workflow.Key
import org.itineradev.itinera.workflow.Supplied
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow

/** Ships an order's parcel. */
@Step
class Ship(@Input private val weight: Long) : ItineraStep {
    fun run(): Outcome {
        println("shipping $weight kg")
        return succeed()
    }
}

/** How the warehouse describes an order's parcel: its weight in kg. */
data class Parcel(val weight: Long)

/** The shop's workflow. */
@Workflow(name = "orders")
@WithStep(Ship::class, name = "ship")
class Orders : ItineraWorkflow {
    /** Gives the shipping the parcel's weight, and tries to keep it in the data bag too. */
    @InputAdapter(steps = ["ship"])
    fun parcels(@Key key: String, @FromWorkflow parcel: Parcel, data: DataBagAccess): Supplied {
        data.write("weight", parcel.weight)
        return if (key == "weight") supply(parcel.weight) else fromDataBag()
    }
}

/** What the shop knows about an order when its journey starts. */
data class NewOrder(val parcel: Parcel)

fun main() {
    val instance = Orders().instance().initialData(NewOrder(parcel = Parcel(weight = 2))).create()
    println("the journey ${LocalExecutor().run(instance).status}")
}
```

What the compiler says about `ch37_adapter_writes_the_data_bag`, recorded in [`ch37_adapter_writes_the_data_bag.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_adapter_writes_the_data_bag.txt)

```text
e: compile-errors/ch37_adapter_writes_the_data_bag.kt:38:14 Unresolved reference 'write' on receiver of type 'DataBagAccess'.
```

An asynchronous workflow's instance given to a `LocalExecutor`:

Kotlin, the program [`ch37_asynchronous_instance_run_locally`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_asynchronous_instance_run_locally.kt). **Does not compile**

```kotlin
// An asynchronous workflow's instance given to the executor of synchronous ones.

package ch37_asynchronous_instance_run_locally

import org.itineradev.itinera.executor.LocalExecutor
import org.itineradev.itinera.step.ItineraStep
import org.itineradev.itinera.step.Outcome
import org.itineradev.itinera.step.Step
import org.itineradev.itinera.workflow.WithStep
import org.itineradev.itinera.workflow.Workflow
import org.itineradev.itinera.workflow.async.ItineraAsyncWorkflow

/** Charges an order, waiting for the bank. */
@Step
class Charge : ItineraStep {
    suspend fun run(): Outcome = succeed()
}

/** The shop's workflow, which runs asynchronously. */
@Workflow(name = "orders")
@WithStep(Charge::class, name = "charge")
class Orders : ItineraAsyncWorkflow

fun main() {
    val result = LocalExecutor().run(Orders().instance().create())
    println("the journey ${result.status}")
}
```

What the compiler says about `ch37_asynchronous_instance_run_locally`, recorded in [`ch37_asynchronous_instance_run_locally.txt`](https://github.com/itinera-dev/book/blob/main/kotlin/compile-errors/ch37_asynchronous_instance_run_locally.txt)

```text
e: compile-errors/ch37_asynchronous_instance_run_locally.kt:25:38 Argument type mismatch: actual type is 'WorkflowInstance<Async>', but 'WorkflowInstance<Sync>' was expected.
```

## How it works

1. **The listing says how the workflow is put together.** It lists each step in order, with its position, the policies attached to it, its input adapter, each service it asks for with the provider that serves it, and its rescue step with that step's own services. It is read from the declaration: nothing runs, and no provider is called. The listing alone shows, for example, that the card registry serves `charge_rescue` and nothing else.
2. **A mistake in putting a workflow together is a violation.** Checking how a workflow is put together, before any journey, is called **admission**, and the specification names each mistake it catches: `duplicate step name`, `hook defined twice`, `service not provided`, `rescued step retried` and a few more, all listed in [3.6, Configuration errors](https://github.com/itinera-dev/spec/blob/main/spec/03-workflow-definitions.md#36-configuration-errors). Every violation found is reported at once, not only the first.
3. **With the checker, a violation is a compile error.** The checker reads the annotations as KSP runs, and reports each violation as an error marked `[ksp]`, on the line of the class or method it concerns, so a workflow put together wrongly never runs.
4. **Some mistakes can't be written at all.** Each hook's return type lists only the [lifecycles](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md) its kind may return, and `finishWorkflow()` is an `OnSuccess`, as [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md) said, never an `OnFailure`. A hook declared with another kind's type still compiles as Kotlin, so the checker reports it instead. A [`RescueOutcome`](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md) is a success or a failure, never a skip, so a rescue step has no `skipBecause`. A `DataBagAccess` has methods that read and none that write, since an adapter reads and never writes, as [chapter 21](https://itinera-dev.org/book/kotlin/21-deciding-where-a-steps-data-comes-from.md) said. And an instance's type says its mode: `LocalExecutor` runs only a [`WorkflowInstance<Sync>`](https://itinera-dev.org/book/kotlin/29-testing-the-flow-with-scripted-steps.md), while an asynchronous workflow's instance goes to an `AsyncLocalExecutor`, as in [chapter 26](https://itinera-dev.org/book/kotlin/26-running-async-journeys-while-others-wait.md), whose `run` is a `suspend` function, so its result is always awaited.

Each of these is caught because the annotations declare the workflow for you, and the checker reads that declaration as the program is built. But you haven't seen what the annotations stand for.

## Outcomes

We have shown how the listing says how a workflow is put together, and how a mistake in putting it together is caught before any order runs.

| The usual way                                                                                                        | With Itinera                                                                              |
| -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Which hooks run after a step, or which client serves a repair, is often learned only by reading every module.        | The listing names each step's policies, its adapter, and the services of its rescue step. |
| A wiring mistake, such as two handlers for one event, often shows only when a request takes that path in production. | The program doesn't build, and the message names the mistake.                             |
