# Giving every reporter what it needs

## What you want to do

The logging service files lines by customer, and the shop needs the bank's receipt to refund an order. You want every line of the log to name the customer, and the receipt once the bank has given it, even when the journey stops right after.

## The code

The shop is [chapter 31](https://itinera-dev.org/book/kotlin/31-stopping-a-journey-when-its-log-fails.md)'s, without chapter 32's `DebugReporter`. `main` gives each instance the customer's name with `reportersGlobalMetadata`, beside `initialData`, which makes it an entry of the journey's **global metadata**: data for its reporters, which no step reads:

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

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

`Orders` is the workflow [chapter 23](https://itinera-dev.org/book/kotlin/23-undoing-a-charge-when-the-shipping-fails.md) declares, and `order` is each of [chapter 31](https://itinera-dev.org/book/kotlin/31-stopping-a-journey-when-its-log-fails.md)'s orders, Ann's and Pat's. In the asynchronous form, the instance is made in [chapter 26](https://itinera-dev.org/book/kotlin/26-running-async-journeys-while-others-wait.md)'s `journey`.

The charge asks for its step reporter, as the shipping does since [chapter 9](https://itinera-dev.org/book/kotlin/09-saying-what-only-a-step-knows.md), and sets the receipt as an entry as soon as the bank gives it, before contributing it:

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

```kotlin
/**
 * Charges an order's amount to its card through the payment client, and gives back its receipt, and
 * the gift card's code when the order is a gift card. It gives every reporter the receipt as soon
 * as the bank gives it.
 */
@Step
class Charge(
    @Input private val order: String,
    @Input private val amount: Long,
    @Input private val card: String,
    @Input private val giftCard: Boolean,
) : ItineraStep {
    fun run(
        @Service payments: Payments,
        contributor: Contributor,
        reporter: StepReporter,
    ): Outcome {
        if (amount <= 0) return fail("nothing-to-charge")
        val receipt = payments.charge(order, card, amount) ?: return fail("card-expired")
        reporter.setGlobalMetadata("receipt", receipt)
        contributor.contribute("receipt", receipt)
        if (giftCard) contributor.contribute("code", "G-$order")
        return succeed()
    }
}

```

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

```kotlin
/**
 * Charges an order's amount to its card through the payment client, and gives back its receipt, and
 * the gift card's code when the order is a gift card. It gives every reporter the receipt as soon
 * as the bank gives it.
 */
@Step
class Charge(
    @Input private val order: String,
    @Input private val amount: Long,
    @Input private val card: String,
    @Input private val giftCard: Boolean,
) : ItineraStep {
    suspend fun run(
        @Service payments: Payments,
        contributor: Contributor,
        reporter: AsyncStepReporter,
    ): Outcome {
        if (amount <= 0) return fail("nothing-to-charge")
        val receipt = payments.charge(order, card, amount) ?: return fail("card-expired")
        reporter.setGlobalMetadata("receipt", receipt)
        contributor.contribute("receipt", receipt)
        if (giftCard) contributor.contribute("code", "G-$order")
        return succeed()
    }
}

```

The payment client it asks for is [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md)'s `Payments`, and its asynchronous form [chapter 26](https://itinera-dev.org/book/kotlin/26-running-async-journeys-while-others-wait.md)'s. In the asynchronous form, the step reporter is an `AsyncStepReporter`, whose `setGlobalMetadata` is a `suspend` function.

The log overrides `setGlobalMetadata`, a method of `Reporter` beside `report`, and keeps each entry it receives in a map. A value comes as an `Any?`, which the log reads with `as? String`. It starts each line with the customer's name and, once there is one, the receipt:

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

```kotlin
/**
 * The shop's log: it writes a line for every event of a journey to the logging service, starting
 * with the workflow's name, the journey's ID, the customer's name and, once the bank has given it,
 * the receipt. A line the service refuses fails the report.
 */
class Log : Reporter {
    private val service = LoggingService()
    private val metadata = mutableMapOf<String, Any?>()

    override fun setGlobalMetadata(key: String, value: Any?) {
        metadata[key] = value
    }

    override fun report(event: Event) {
        val line =
            "log ${event.workflow} ${event.journeyId} ${whose()} #${event.sequence} ${event.kind}"
        when (val detail = detail(event)) {
            null -> service.write(line)
            else -> service.write("$line $detail")
        }
    }

    /** The customer the journey is for and, once the bank has given it, the charge's receipt. */
    private fun whose(): String {
        val customer = metadata["customer"] as? String ?: "someone"
        return when (val receipt = metadata["receipt"] as? String) {
            null -> "for $customer"
            else -> "for $customer, receipt $receipt"
        }
    }
}

```

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

```kotlin
/**
 * The shop's log: it writes a line for every event of a journey to the logging service, starting
 * with the workflow's name, the journey's ID, the customer's name and, once the bank has given it,
 * the receipt. A line the service refuses fails the report.
 */
class Log : AsyncReporter {
    private val service = LoggingService()
    private val metadata = mutableMapOf<String, Any?>()

    override suspend fun setGlobalMetadata(key: String, value: Any?) {
        metadata[key] = value
    }

    override suspend fun report(event: Event) {
        val line =
            "log ${event.workflow} ${event.journeyId} ${whose()} #${event.sequence} ${event.kind}"
        when (val detail = detail(event)) {
            null -> service.write(line)
            else -> service.write("$line $detail")
        }
    }

    /** The customer the journey is for and, once the bank has given it, the charge's receipt. */
    private fun whose(): String {
        val customer = metadata["customer"] as? String ?: "someone"
        return when (val receipt = metadata["receipt"] as? String) {
            null -> "for $customer"
            else -> "for $customer, receipt $receipt"
        }
    }
}

```

The logging service is [chapter 31](https://itinera-dev.org/book/kotlin/31-stopping-a-journey-when-its-log-fails.md)'s. In the asynchronous form, `setGlobalMetadata` of `AsyncReporter` is a `suspend` function too. `detail`, [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md)'s with the parts that page points to, has one more branch, for a `GlobalMetadataSet`, from `org.itineradev.itinera.event`, which names its key:

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

```kotlin
is GlobalMetadataSet -> event.key
```

`main` runs Ann's and Pat's orders, as [chapter 31](https://itinera-dev.org/book/kotlin/31-stopping-a-journey-when-its-log-fails.md)'s does, and prints:

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

```text
Ann's order:
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 ch33_giving_every_reporter_what_it_needs.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 ch33_giving_every_reporter_what_it_needs.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 ch33_giving_every_reporter_what_it_needs.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: charge took 30, receipt R-A-1
Pat's order:
log orders A-15 for Pat #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-15 for Pat #2 attempt_started lookup, attempt 1
log orders A-15 for Pat #3 service_provided lookup gets orderBook from ledger, a ch33_giving_every_reporter_what_it_needs.Ledger
the order book has no order A-15 yet
log orders A-15 for Pat #4 step_succeeded lookup
log orders A-15 for Pat #5 contribution_committed completed
log orders A-15 for Pat #6 hook_called alreadyCompleted: on step success of lookup
log orders A-15 for Pat #7 attempt_started price, attempt 1
log orders A-15 for Pat #8 optional_input_absent discount
log orders A-15 for Pat #9 step_succeeded price
log orders A-15 for Pat #10 contribution_committed amount
log orders A-15 for Pat #11 attempt_started charge, attempt 1
log orders A-15 for Pat #12 service_provided charge gets payments from bank, a ch33_giving_every_reporter_what_it_needs.Bank
the bank charges 50 for order A-15
log orders A-15 for Pat, receipt R-A-15 #13 global_metadata_set receipt
the journey was aborted (reporter failed: the logging service is down)
```

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

```text
log orders A-1 for Ann #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-15 for Pat #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-1 for Ann #2 attempt_started lookup, attempt 1
log orders A-15 for Pat #2 attempt_started lookup, attempt 1
log orders A-1 for Ann #3 service_provided lookup gets orderBook from ledger, a ch33_giving_every_reporter_what_it_needs_async.Ledger
the order book has no order A-1 yet
log orders A-15 for Pat #3 service_provided lookup gets orderBook from ledger, a ch33_giving_every_reporter_what_it_needs_async.Ledger
the order book has no order A-15 yet
log orders A-1 for Ann #4 step_succeeded lookup
log orders A-15 for Pat #4 step_succeeded lookup
log orders A-1 for Ann #5 contribution_committed completed
log orders A-15 for Pat #5 contribution_committed completed
log orders A-1 for Ann #6 hook_called alreadyCompleted: on step success of lookup
log orders A-15 for Pat #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 for Ann #7 attempt_started price, attempt 1
log orders A-15 for Pat #7 attempt_started price, attempt 1
log orders A-1 for Ann #8 step_succeeded price
log orders A-15 for Pat #8 optional_input_absent discount
log orders A-1 for Ann #9 contribution_committed amount
log orders A-15 for Pat #9 step_succeeded price
log orders A-1 for Ann #10 attempt_started charge, attempt 1
log orders A-15 for Pat #10 contribution_committed amount
log orders A-1 for Ann #11 service_provided charge gets payments from bank, a ch33_giving_every_reporter_what_it_needs_async.Bank
log orders A-15 for Pat #11 attempt_started charge, attempt 1
the bank charges 30 for order A-1
log orders A-15 for Pat #12 service_provided charge gets payments from bank, a ch33_giving_every_reporter_what_it_needs_async.Bank
log orders A-1 for Ann, receipt R-A-1 #12 global_metadata_set receipt
the bank charges 50 for order A-15
log orders A-1 for Ann, receipt R-A-1 #13 step_succeeded charge
log orders A-15 for Pat, receipt R-A-15 #13 global_metadata_set receipt
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 ch33_giving_every_reporter_what_it_needs_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
order A-1:
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 30, receipt R-A-1
order A-15:
the journey was aborted (reporter failed: the logging service is down)
```

## How it works

1. **Global metadata is for the reporters.** Each entry is a key and a value, which every reporter of the journey receives. Steps and hooks never read it, so it changes no decision.
2. **The entries come before the first event.** The journey ID comes first, under the key `journey_id`, then the instance's entries, in the order they were set. So Pat's first line, `journey_started`, already names Pat. The key `journey_id` is the executor's own.
3. **A reporter does what it wants with an entry.** `setGlobalMetadata` does nothing unless a reporter overrides it, which is why [chapter 11](https://itinera-dev.org/book/kotlin/11-naming-a-journey.md)'s desk is unchanged. The log keeps the entries, and reads them back from its map, checking that a value is a `String` before it writes it.
4. **A step can set an entry while it runs.** Every reporter receives it, then the journey emits `global_metadata_set`, which names the key and who set it, but not the value, all before `setGlobalMetadata` returns. The log wrote that line with the receipt in it, event 13, before it failed on the charge's success.
5. **An entry stands whatever happens after.** Pat's receipt never reached the data bag, since the journey was aborted first, but the log had it. So the shop finds Pat's payment, `R-A-15`, in the log's last line, and can refund it.

Every line of the log now says whose order it is and, from the charge on, how it was paid. But the audit's line, which a hook writes, says neither which journey nor which attempt took the money.

## Outcomes

We have shown how a journey's reporters receive data of their own, from the instance and from the steps, as global metadata.

| The usual way                                                                                                                   | With Itinera                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| A value every log line needs, such as a customer's name, is often passed down through every call, or kept in a global variable. | The instance gives it once to every reporter, before the first event.                        |
| A value a log line needs, found halfway through a request, is often lost when the request crashes right after.                  | A step sets it for every reporter as soon as it has it, and it stands whatever happens next. |
