# Declaring by hand

## What you want to do

The annotations have declared the shop's workflow, and the checker has checked it as the program was built. You want to see what the annotations stand for, and to write part of the shop that way yourself: for a declaration put together when the program starts, from the shop's configuration, or for a mistake you'd rather read as a value than as an error of the build.

## The code

### The shop by hand

The shop is the one [chapter 36](https://itinera-dev.org/book/kotlin/36-orders-refused-before-they-start.md) runs, declared in the **long form**: without the annotations, for its pricing step, its audit and its workflow. Each request is made once, by `Requests` from `org.itineradev.itinera.request`, such as `Requests.input("price", typeToken<Long>())`. The pricing is a plain class implementing `SyncStepRun`, and `pricing()` declares it: `StepDescriptor.builder("price")` takes what builds it afresh for each attempt, as in [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md), from `got`, the typed answers to the requests `request` lists:

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

```kotlin
val PRICE = Requests.input("price", typeToken<Long>())
val DISCOUNT = Requests.optionalInput("discount", typeToken<Long>())
val CONTRIBUTOR = Requests.contributor()

/**
 * Works out what an order costs, for one attempt: its price, less its discount if it has one, given
 * back as the amount to charge.
 */
class Price(
    private val price: Long,
    private val discount: Long?,
    private val contributor: Contributor,
) : SyncStepRun {
    override fun run(): Outcome {
        contributor.contribute("amount", price - (discount ?: 0L))
        return Outcome.success()
    }
}

/** Declares the pricing, built for each attempt from what it requests. */
fun pricing(): StepDescriptor<Sync> =
    StepDescriptor.builder("price") { got ->
            Price(got[PRICE], got[DISCOUNT], got[CONTRIBUTOR])
        }
        .request(PRICE)
        .request(DISCOUNT)
        .request(CONTRIBUTOR)
        .build()

```

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

```kotlin
val PRICE = Requests.input("price", typeToken<Long>())
val DISCOUNT = Requests.optionalInput("discount", typeToken<Long>())
val CONTRIBUTOR = Requests.contributor()

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

/** Declares the pricing, built for each attempt from what it requests. */
fun pricing(): StepDescriptor<Async> =
    asyncStep("price") { got ->
            Price(got[PRICE], got[DISCOUNT], got[CONTRIBUTOR])
        }
        .request(PRICE)
        .request(DISCOUNT)
        .request(CONTRIBUTOR)
        .build()

```

The audit is a plain class too. `StepPolicyDescriptor.builder` names it and makes it, and `onStepSuccess` takes its hook's requests, in order, and calls `charged` with their answers:

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

```kotlin
val JOURNEY = Requests.journeyId()
val STEP = Requests.stepName()
val ATTEMPT = Requests.attempt()
val AMOUNT = Requests.fromWorkflow("amount", typeToken<Long>())
val RECEIPT = Requests.fromStep("receipt", typeToken<String>())

/**
 * Writes an audit line for every step it is attached to that succeeds: the journey, the attempt
 * that took the money, the amount the order was charged, and the receipt the step gave back.
 */
class Audit {
    fun charged(
        journey: JourneyId,
        step: StepName,
        attempt: Attempt,
        amount: Long,
        receipt: String,
        contributor: Contributor,
    ): OnSuccess {
        contributor.contribute(
            "audit",
            "$journey: $step took $amount on attempt $attempt, receipt $receipt",
        )
        return OnSuccess.keepDefault()
    }
}

/** Declares the audit, its hook `charged` called with what it requests, in order. */
fun audit(): StepPolicyDescriptor<Audit, Sync> =
    StepPolicyDescriptor.builder("audit", PolicyFactory(::Audit))
        .onStepSuccess(listOf(JOURNEY, STEP, ATTEMPT, AMOUNT, RECEIPT, CONTRIBUTOR)) { audit, got ->
            audit.charged(
                got[JOURNEY],
                got[STEP],
                got[ATTEMPT],
                got[AMOUNT],
                got[RECEIPT],
                got[CONTRIBUTOR],
            )
        }
        .build()

```

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

```kotlin
val JOURNEY = Requests.journeyId()
val STEP = Requests.stepName()
val ATTEMPT = Requests.attempt()
val AMOUNT = Requests.fromWorkflow("amount", typeToken<Long>())
val RECEIPT = Requests.fromStep("receipt", typeToken<String>())

/**
 * Writes an audit line for every step it is attached to that succeeds: the journey, the attempt
 * that took the money, the amount the order was charged, and the receipt the step gave back.
 */
class Audit {
    suspend fun charged(
        journey: JourneyId,
        step: StepName,
        attempt: Attempt,
        amount: Long,
        receipt: String,
        contributor: Contributor,
    ): OnSuccess {
        contributor.contribute(
            "audit",
            "$journey: $step took $amount on attempt $attempt, receipt $receipt",
        )
        return OnSuccess.keepDefault()
    }
}

/** Declares the audit, its hook `charged` called with what it requests, in order. */
fun audit(): StepPolicyDescriptor<Audit, Async> =
    asyncStepPolicy("audit", PolicyFactory(::Audit))
        .onStepSuccess(listOf(JOURNEY, STEP, ATTEMPT, AMOUNT, RECEIPT, CONTRIBUTOR)) { audit, got ->
            audit.charged(
                got[JOURNEY],
                got[STEP],
                got[ATTEMPT],
                got[AMOUNT],
                got[RECEIPT],
                got[CONTRIBUTOR],
            )
        }
        .build()

```

`Orders` implements both roles but no longer `ItineraWorkflow`, so its ID generator, input adapter and providers are plain methods now, and build the `Supplied` and `Provided.Instance` that `supply`, `fromDataBag` and `provide` made before:

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

```kotlin
/**
 * The shop: it tells its customers through the channel it configures, and the bank gives refunds.
 * Its plain methods name each journey, describe each parcel and give the services.
 */
class Orders(private val channel: String) : Messages, Refunds {
    override fun tell(customer: String, message: String) {
        println("$channel to $customer: $message")
    }

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

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

    /**
     * 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.
     */
    fun parcels(key: String, parcel: Parcel): Supplied =
        if (key == "weight") Supplied.Value(parcel.weight) else Supplied.FromDataBag

    /** The order book, which has the orders completed before today. */
    fun ledger(): Provided<OrderBook> = Provided.Instance(Ledger(listOf("A-13")))

    /** The bank, as the payment client of the journey. */
    fun bank(): Provided<Payments> = Provided.Instance(Bank(thisYear = 2026))

    /** The bank's card registry in Europe. */
    fun cards(): Provided<Cards> = Provided.Instance(cardRegistry("eu"), "eu")

    /** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
    fun carriers(attempt: Attempt): Provided<Carrier> =
        if (attempt.isFirst) Provided.Instance(MainCarrier())
        else Provided.Instance(BackupCarrier())
}

```

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

```kotlin
/**
 * The shop: it tells its customers through the channel it configures, and the bank gives refunds.
 * Its plain methods name each journey, describe each parcel and give the services.
 */
class Orders(private val channel: String) : Messages, Refunds {
    override suspend fun tell(customer: String, message: String) {
        println("$channel to $customer: $message")
    }

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

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

    /**
     * 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.
     */
    suspend fun parcels(key: String, parcel: Parcel): Supplied =
        if (key == "weight") Supplied.Value(parcel.weight) else Supplied.FromDataBag

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

    /** The bank, as the payment client of the journey. */
    suspend fun bank(): Provided<Payments> = Provided.Instance(Bank(thisYear = 2026))

    /** The bank's card registry in Europe. */
    suspend fun cards(): Provided<Cards> = Provided.Instance(cardRegistry("eu"), "eu")

    /** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
    suspend fun carriers(attempt: Attempt): Provided<Carrier> =
        if (attempt.isFirst) Provided.Instance(MainCarrier())
        else Provided.Instance(BackupCarrier())
}

```

`Parcel` is [chapter 21](https://itinera-dev.org/book/kotlin/21-deciding-where-a-steps-data-comes-from.md)'s, `OrderBook` is [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md)'s, `Carrier` is [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md)'s, `Messages` [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md)'s, `Refunds` [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md)'s, and `Payments`, `Cards` and `cardRegistry` are [chapter 35](https://itinera-dev.org/book/kotlin/35-giving-the-rescue-step-a-service-of-its-own.md)'s.

And `WorkflowDescriptor.builder` puts the workflow together, part by part. The other steps and policies keep their annotations, and go in through `StepDescriptor.builder("lookup", Lookup::class.java)`, `StepPolicyDescriptor.of`, `RescueStepDescriptor.of` and `WorkflowPolicyDescriptor.of`, which read each class alone:

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

```kotlin
val KEY = Requests.key()
val PARCEL = Requests.fromWorkflow("parcel", typeToken<Parcel>())

/**
 * Declares the shop's workflow, part by part, and checks it. 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, its charge refunded if it is given up. Once a journey has ended, the customer is told.
 */
fun orders(): WorkflowDescriptor<Orders, Sync> {
    val parcels =
        InputAdapterDescriptor.builder<Orders>("parcels", "ship") { orders, got ->
                orders.parcels(got[KEY], got[PARCEL])
            }
            .request(KEY)
            .request(PARCEL)
            .build()
    val ledger =
        ProviderDescriptor.builder<Orders, OrderBook>(
                "ledger",
                "orderBook",
                OrderBook::class.java,
            ) { orders, _ ->
                orders.ledger()
            }
            .build()
    val bank =
        ProviderDescriptor.builder<Orders, Payments>("bank", "payments", Payments::class.java) {
                orders,
                _ ->
                orders.bank()
            }
            .build()
    val cards =
        ProviderDescriptor.builder<Orders, Cards>("cards", "cards", Cards::class.java) { orders, _
                ->
                orders.cards()
            }
            .step("charge_rescue")
            .build()
    val carriers =
        ProviderDescriptor.perAttempt<Orders, Carrier>(
                "carriers",
                "carrier",
                Carrier::class.java,
            ) { orders, got ->
                orders.carriers(got[ATTEMPT])
            }
            .request(ATTEMPT)
            .build()
    return WorkflowDescriptor.builder(Orders::class.java, "orders")
        .step(
            StepDescriptor.builder("lookup", Lookup::class.java)
                .policy(StepPolicyDescriptor.of(AlreadyCompleted::class.java))
                .build()
        )
        .step(pricing())
        .step(
            StepDescriptor.builder("charge", Charge::class.java)
                .rescue(RescueStepDescriptor.of(RenewCard::class.java))
                .policy(audit())
                .policy(StepPolicyDescriptor.of(Outage::class.java))
                .build()
        )
        .step(
            StepDescriptor.builder("ship", Ship::class.java)
                .retryBudget(1)
                .policy(StepPolicyDescriptor.of(FailedShipping::class.java))
                .build()
        )
        .role(Messages::class.java)
        .role(Refunds::class.java)
        .policy(WorkflowPolicyDescriptor.of(Notify::class.java))
        .reporter(ReporterFactory { Log() })
        .reporter(ReporterFactory { Desk() })
        .idGenerator { orders, data -> orders.orderNumber(data) }
        .inputAdapter(parcels)
        .provider(ledger)
        .provider(bank)
        .provider(cards)
        .provider(carriers)
        .build()
}

```

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

```kotlin
val KEY = Requests.key()
val PARCEL = Requests.fromWorkflow("parcel", typeToken<Parcel>())

/**
 * Declares the shop's workflow, part by part, and checks it. 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, its charge refunded if it is given up. Once a journey has ended, the customer is told.
 */
fun orders(): WorkflowDescriptor<Orders, Async> {
    val parcels =
        asyncInputAdapter<Orders>("parcels", "ship") { orders, got ->
                orders.parcels(got[KEY], got[PARCEL])
            }
            .request(KEY)
            .request(PARCEL)
            .build()
    val ledger =
        asyncProvider<Orders, OrderBook>(
                "ledger",
                "orderBook",
                OrderBook::class.java,
            ) { orders, _ ->
                orders.ledger()
            }
            .build()
    val bank =
        asyncProvider<Orders, Payments>("bank", "payments", Payments::class.java) { orders, _ ->
                orders.bank()
            }
            .build()
    val cards =
        asyncProvider<Orders, Cards>("cards", "cards", Cards::class.java) { orders, _ ->
                orders.cards()
            }
            .step("charge_rescue")
            .build()
    val carriers =
        asyncPerAttemptProvider<Orders, Carrier>(
                "carriers",
                "carrier",
                Carrier::class.java,
            ) { orders, got ->
                orders.carriers(got[ATTEMPT])
            }
            .request(ATTEMPT)
            .build()
    return asyncBuilder<Orders>("orders")
        .step(
            asyncStep("lookup", Lookup::class)
                .policy(asyncStepPolicyOf(AlreadyCompleted::class))
                .build()
        )
        .step(pricing())
        .step(
            asyncStep("charge", Charge::class)
                .rescue(asyncRescueStepOf(RenewCard::class))
                .policy(audit())
                .policy(asyncStepPolicyOf(Outage::class))
                .build()
        )
        .step(
            asyncStep("ship", Ship::class)
                .retryBudget(1)
                .policy(asyncStepPolicyOf(FailedShipping::class))
                .build()
        )
        .role(Messages::class.java)
        .role(Refunds::class.java)
        .policy(asyncWorkflowPolicyOf(Notify::class))
        .reporter(AsyncReporterFactory { Log() })
        .reporter(AsyncReporterFactory { Desk() })
        .idGenerator { orders, data -> orders.orderNumber(data) }
        .inputAdapter(parcels)
        .provider(ledger)
        .provider(bank)
        .provider(cards)
        .provider(carriers)
        .build()
}

```

The rest is as earlier chapters show it: the lookup and `AlreadyCompleted` in [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md), the charge in [chapter 33](https://itinera-dev.org/book/kotlin/33-giving-every-reporter-what-it-needs.md), `RenewCard` in [chapter 35](https://itinera-dev.org/book/kotlin/35-giving-the-rescue-step-a-service-of-its-own.md), the shipping in [chapter 17](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md), `Outage` in [chapter 34](https://itinera-dev.org/book/kotlin/34-saying-which-attempt-took-the-money.md), `FailedShipping` in [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md), `Notify` in [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md), the log in [chapter 33](https://itinera-dev.org/book/kotlin/33-giving-every-reporter-what-it-needs.md), [chapter 35](https://itinera-dev.org/book/kotlin/35-giving-the-rescue-step-a-service-of-its-own.md) and [chapter 36](https://itinera-dev.org/book/kotlin/36-orders-refused-before-they-start.md), and the desk in [chapter 11](https://itinera-dev.org/book/kotlin/11-naming-a-journey.md).

In the asynchronous form, the pricing implements `AsyncStepRun`, and every `suspend` part is declared with a function of `itinera-kotlin`, such as `asyncStep`, `asyncStepPolicy`, `asyncBuilder<Orders>("orders")` or `asyncStepPolicyOf(Outage::class)`.

`main` calls `orders()` once, and makes each order's instance with `instance`, from `org.itineradev.itinera.instance`:

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

```kotlin
val instance =
    orders
        .instance(Orders(channel = "email"))
        .reportersGlobalMetadata("customer", order.customer)
        .initialData(order)
        .create()
```

`followUp` is [chapter 34](https://itinera-dev.org/book/kotlin/34-saying-which-attempt-took-the-money.md)'s. In the asynchronous form, `instance` is from `org.itineradev.itinera.instance.async`, and each journey runs on an `AsyncLocalExecutor` inside `runBlocking`. `main` runs Ann's order and Jo's, and prints:

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

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

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

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

### A workflow put together wrongly

This small shop has steps and policies of its own, `parcelsFor` declares its adapter, and `detail` says what a violation is:

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

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

/** Ships an order of the weight it is given. */
@Step
class Ship(@Input private val weight: Long) : ItineraStep {
    fun run(): Outcome = succeed()
}

/** Audits a charge that succeeds. */
@StepPolicy(name = "audit")
class Audit : ItineraStepPolicy {
    @OnStepSuccess fun charged(): OnSuccess = keepDefault()
}

/** Keeps the receipt of a charge that succeeds. */
@StepPolicy(name = "receipts")
class Receipts : ItineraStepPolicy {
    @OnStepSuccess fun charged(): OnSuccess = keepDefault()
}

/** The shop whose orders the workflow takes. */
class Shop

val PARCEL = Requests.fromWorkflow("parcel", typeToken<Long>())

/** The parcels adapter, which gives the step it is attached to the parcel's weight. */
fun parcelsFor(step: String): InputAdapterDescriptor<Shop, Sync> =
    InputAdapterDescriptor.builder<Shop>("parcels", step) { _, got -> Supplied.Value(got[PARCEL]) }
        .request(PARCEL)
        .build()

/** The charge, with the policies given. */
fun charge(vararg policies: StepPolicyDescriptor<*, Sync>): StepDescriptor<Sync> =
    policies
        .fold(StepDescriptor.builder("charge", Charge::class.java)) { charge, policy ->
            charge.policy(policy)
        }
        .build()

/** The shipping. */
fun ship(): StepDescriptor<Sync> = StepDescriptor.builder("ship", Ship::class.java).build()

/** Starts the shop's workflow. */
fun shop(): WorkflowBuilder<Shop, Sync> = WorkflowDescriptor.builder(Shop::class.java, "shop")

/** Says what one violation is, by the name the specification gives it, and what it concerns. */
fun detail(violation: Violation): String =
    when (violation) {
        is Violation.DuplicateStepName -> "${violation.named}: ${violation.step}"
        is Violation.StepHookDefinedTwice ->
            "${violation.named}: ${violation.hook} on step ${violation.step}"
        is Violation.InputAdapterForUnknownStep ->
            "${violation.named}: ${violation.adapter} on ${violation.step}"
        else -> "${violation.named}"
    }

```

It is declared by hand with three mistakes: `ship` listed twice, two policies of the charge that both define `on step success`, and the parcels adapter attached to `shipping`, a step the workflow doesn't have:

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

```kotlin
val audit = StepPolicyDescriptor.of(Audit::class.java)
val receipts = StepPolicyDescriptor.of(Receipts::class.java)
shop()
    .step(charge(audit, receipts))
    .step(ship())
    .step(ship())
    .inputAdapter(parcelsFor("shipping"))
    .build()
```

The program builds: the checker reads a workflow only in a class that implements `ItineraWorkflow`, which `Shop` doesn't, and reads each step and policy alone, and each is right on its own. `build()` throws a `Violations`, from `org.itineradev.itinera.workflow`, and `main` reads it:

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

```kotlin
} catch (refused: Violations) {
    println("the workflow was refused:")
    for (violation in refused.violations) {
        println("  ${detail(violation)}")
    }
}
```

Fixed, it builds, and `main` prints its listing:

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

```kotlin
val fixed =
    shop()
        .step(charge(StepPolicyDescriptor.of(Audit::class.java)))
        .step(ship())
        .inputAdapter(parcelsFor("ship"))
        .build()
println("the fixed workflow was built:")
for (step in fixed.listing()) {
    println("  ${step.position}. ${step.step}")
}
```

It prints:

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

```text
the workflow was refused:
  duplicate step name: ship
  hook defined twice: on step success on step charge
  input adapter for unknown step: parcels on shipping
the fixed workflow was built:
  1. charge
  2. ship
```

## How it works

1. **Both forms make the same descriptors, and they mix.** A workflow is a **workflow descriptor**: its name, a step descriptor for each step in order, its policies, roles, reporters, ID generator, input adapters and providers. The annotations declare them, the long form writes them, and the executor runs either the same way.
2. **Each annotation stands for a builder's call.** `@WithStep` stands for `StepDescriptor.builder` and its `retryBudget`, `rescue` and `policy`, and each `@Input` of a step for a `request`. `@StepPolicy` and a hook's annotation stand for `StepPolicyDescriptor.builder` and its `onStepSuccess`, or another hook's method. `@Workflow` stands for `WorkflowDescriptor.builder`, `reporter` and `policy`, a role the workflow implements for `role`, and `@IdGenerator`, `@InputAdapter` and `@Provider` for the methods of their names. `ReporterFactory { Log() }` makes each journey's log, and `PolicyFactory(::Audit)` the audit for each attempt.
3. **`build()` checks the declaration, as admission.** It throws a `Violations` listing every violation, each a `Violation` named as the specification names it. The checker finds them in an annotated workflow as the program is built, as [chapter 37](https://itinera-dev.org/book/kotlin/37-mistakes-caught-before-a-journey.md) showed; how the parts are put together is left to `build()`.
4. **When you need the long form.** Beside the two needs this chapter started from, the long form also suits a class you can't annotate, such as one from a library. No option of itinera turns the annotations off: a program uses whichever form it needs.

What the book hasn't said is how to decide, for a new rule of the shop, which part it belongs in.

## Outcomes

We have shown what the annotations stand for, how to write it by hand, and how a workflow declared by hand reports its mistakes.

| The usual way                                                                   | With Itinera                                                                          |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| Wiring declared by a framework's annotations is often read by code nobody sees. | The annotations stand for public builders, which you can call yourself, part by part. |
| A wiring mistake found at start-up often stops at the first one.                | `build()` throws every violation at once, each a value.                               |
