# Events and listeners

This page is the catalog, `ctx.emit`, `on`, a batch listener and an inbound webhook. The commands it teaches are `durable-sdk doctor --host` and `pnpm test`; the console's Facts view shows what landed.

## The catalog

A fact is a row of `src/events/catalog.ts`: a typed payload on the `EventPayloads` augmentation, and a descriptor with its key and the fields the key reads. `ctx.emit`, `ctx.waitFor` and `on` take the catalog's literal names, so a misspelled fact fails `tsc`.

```ts
import { defineEvents } from "@durable-sdk/core";

declare module "@durable-sdk/core" {
  interface EventPayloads {
    /** A checkout became an order, once per checkout and request. */
    "order.placed": { orderId: string; checkoutId: string; requestId: string };
    /** An abandoned checkout's reminder, keyed on its moment too: a later reminder is a new key. */
    "checkout.reminder.due": { checkoutId: string; dueAt: string };
  }
}

/** Spelled once, beside the emit and the cancel. */
export const reminderKey = (checkoutId: string, dueAt: string) =>
  `checkout.reminder.due:${checkoutId}:${dueAt}`;

export const EVENTS = defineEvents({
  "order.placed": {
    key: (p) => `order.placed:${p.checkoutId}:${p.requestId}`,
    parts: ["checkoutId", "requestId"],
  },
  "checkout.reminder.due": {
    key: (p) => reminderKey(p.checkoutId, p.dueAt),
    parts: ["checkoutId", "dueAt"],
    moments: {
      dueAt:
        "the checkout's last touch plus an hour, from its record; never a clock read at the emit",
    },
  },
});
```

The key is a pure function of the payload and the engine adds nothing to it: a fact is inserted-if-absent under it, so a resend collapses. Put the request id (or the attempt) in the key when a redrive of the same intent is a new fact, and leave it out when it is the same fact. A payload field that carries a moment says so under `moments`, with where the moment comes from. `durable.config.ts` hands `EVENTS` to `createDurable` as the catalog.

## Emit from a run

```ts
async run(ctx) {
  const { checkoutId, requestId } = ctx.input;
  const order = await ctx.step("order.create", () => orders.create(checkoutId), {
    undo: (_, out) => orders.cancel(out.orderId),
    effect: "provider",
  });
  ctx.emit("order.placed", { orderId: order.orderId, checkoutId, requestId });
  return order;
},
```

`ctx.emit` is not a step: the fact is written in the same transaction as the run's final status, so a fact of an attempt that threw is dropped and only `run.failed` is written, while a run that ended through `ctx.fail()` writes its facts with status `FAILED`. A delayed fact (`ctx.emit(name, payload, { deliverAt })`) fires at its moment, and one whose reason is gone is cancelled by key inside a step: `await ctx.cancelScheduled(reminderKey(checkoutId, dueAt))`. `emit()` outside a run (a webhook route) commits on its own and reports `collapsed: true` when the key stands already.

## The listener, one run per delivery

A listener lives in `src/listeners.ts`, the one module `durable.config.ts` names as its `listeners` loader; `on(` at the top level of any other file is refused by the doctor. It reacts with the value form and never spreads the context into a workflow's input:

```ts
import { describeResult, on } from "@durable-sdk/core";

on(
  "order.placed",
  "deliver-to-apps",
  async (e, ctx) => {
    const { appEventDeliver } = await import("./workflows/app-event-deliver");
    const subscribed = await ctx.step(
      "apps.read",
      () => apps.subscribed(e.name),
      {
        irreversible: "a read",
        id: "apps.read",
      },
    );
    for (const app of subscribed) {
      const result = await appEventDeliver.execute(
        {
          deliveryId: `${e.key}:${app.id}`,
          appId: app.id,
          orderId: e.payload.orderId,
        },
        { actor: ctx.actor },
      );
      if (result.status !== "completed")
        ctx.log.warn("deliver.not_completed", {
          app: app.id,
          result: describeResult(result),
        });
    }
  },
  {
    describe:
      "Delivers order.placed to every installed app, one run per app and fact.",
  },
);
```

Its run is `listener.deliver-to-apps`, keyed `listener.<name>:<outboxId>`, so a redelivery is harmless, and the fact's key and the app's id spell the delivery id it hands on, so each delivery is one run per fact and app (`app.event.deliver` keys on `deliveryId` alone). The workflow is imported lazily so no cycle closes through `on`. A listener reads the world through steps (the installed apps above: `ctx.step("<domain>.read", …, { irreversible: "a read", id })`), never in its own lines, and never calls `executeOrThrow`: its outcome is a value, and a throw is transport that backs off.

Delivery is bounded: at most eight transport attempts with backoff, then the row is parked; a reaction whose run fails parks the row on that first failure. A parked row is listed in the console's Facts view under its fact's delivery; a person's Reset re-arms it, Redrive re-runs the listener. A listener may carry its own policy: `retry: { maxReceiveCount, backoff, maxAge }`, `concurrency: { max, key }`, `debounce: { key, period }` (one run per key per window), `throttle: { limit, period }` (a token bucket, never a drop). Facts reach their listeners in partition order, never globally.

## A batch listener, in three lines

A listener that would rather see a burst than a fact declares a window: the body takes a slice of up to `maxSize` consecutive facts of one partition, or fewer once the oldest waited `maxWait`.

```ts
on(
  "order.placed",
  "index-orders",
  async (events, ctx) => {
    ctx.log.info("orders.batch", {
      orderIds: events.map((e) => e.payload.orderId),
    });
  },
  { batch: { maxSize: 100, maxWait: "5s" } },
);
```

Its run is keyed by the slice's head, so a slice re-formed from the same head finds the one run. The body's type follows the options: an array without `batch` fails to compile.

## An inbound webhook in five lines

The template ships `api/webhooks/[provider].ts` on `webhookRoute`: how to verify a delivery and which facts it is, here a sales channel's order recorded as the same `order.placed`. The binding does the rest in a fixed order: the method, `verify(request)`, `toFacts(context)`, each fact emitted under the catalog's key (a redelivery collapses), an empty 200.

```ts
import { durable, webhookRoute, type WebhookFact } from "../../src/durable";

import { verifyChannel, type ChannelOrder } from "../../src/webhooks/channel";

const toFacts = ({ id, orderId, checkoutId }: ChannelOrder): WebhookFact[] => [
  { name: "order.placed", payload: { orderId, checkoutId, requestId: id } },
];

export const POST = webhookRoute({ durable, verify: verifyChannel, toFacts });
```

`verify` answers `{ ok: true, context }` or `{ ok: false, status }`; a `Response` it throws is returned as it is. `toFacts` answers the facts, `[]` for nothing, or `{ ignored: reason }` to say why on the log. A throw of `toFacts` is not caught: nothing was written, so the provider redelivers.

## Check it

```bash
durable-sdk doctor --host
pnpm test
```

In a test, `t.emit(name, payload)` then `t.tick()` is the fact's path through the listener; `t.outbox({ undelivered: true })` must be empty at the end ([Testing](https://durablesdk.com/docs/guide/testing.md)). The outbox, the dispatcher's lanes, the relay to peer apps and every listener option are on the generated page [Workflows](https://durablesdk.com/docs/workflows.md).

---

Prompt for an agent:

```text
Read https://durablesdk.com/docs/guide/events-and-listeners.md, then add a fact to src/events/catalog.ts, emit it from a workflow and react to it in src/listeners.ts; run durable-sdk doctor --host before and after; a refused line is a refusal id: durable-sdk explain <id>
```
