> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Reactions

> Run a mutation on a clock, an inbound HTTP request or a change to a selection.

A **reaction** is a mutation with `on`: the host runs it for each firing of a
standing source. Nobody calls it, so it has no `allow` (a route reaction is the
one exception, below). It runs as the installation holding the `roles` it
declares, with `ctx.frame.on` carrying `{ kind: "source", source }`.

| Source | Fires | The handler's second argument |
| - | - | - |
| `every(duration)` | at a fixed interval, at least one second | `{ at }`, the instant it was due |
| `cron(expression, zone)` | on a five-field cron expression in an IANA time zone | `{ at }` |
| `route.post(path, verifier)`, `route.get`, `route.put`, `route.delete` | on an inbound HTTP request to the path | the `Request` |
| `selection.changes` | on each change to the selection's facts | the change: `{ key, before, after, version }` |

A target is never a source. To act on a task's result, name a continuation
with `then` when you [submit it](https://docs.bijection.com/functions/effects.md).

## Clocks

```ts bijection/digests.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { cron, every, label, mutation, role, t, table } from "@bijectionhq/bijection";

export const digests = table({ at: t.instant, sent: t.boolean }, { index: [["at"]] });
export const mailer = role({});

export const hourly = mutation({ on: every({ hours: 1 }), roles: [mailer] }, async (ctx, { at }) => {
  await ctx.insert(digests, { at, sent: false });
});

export const nightly = mutation({ on: cron("17 2 * * *", "Europe/Paris"), roles: [mailer] }, async (ctx, { at }) => {
  await ctx.insert(digests, { at, sent: false });
});
```

Each source takes `{ lateness, coalesce }`. `lateness` is how long after its
instant a firing may still run: the interval by default, at most one day.
Later, the firing is skipped. `coalesce: true`, the default, runs missed
firings once; `false` runs each in turn.

Keep a firing's work bounded. Work that takes more than one transaction is a
task the reaction [submits](https://docs.bijection.com/functions/effects.md).

## Routes

A route reaction receives the inbound request and its return value is the
reply.

A signed unsubscribe link carries a token issued for one email address.
Use a dedicated signing key and include `email` and an `exp` timestamp
in seconds when you issue the token with `signJwt`.

```ts bijection/unsubscribe.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, route, secret, t, table, verifier } from "@bijectionhq/bijection";
import { verifyJwt } from "@bijectionhq/library-keys";

export const unsubscribeKey = secret({ alg: "hmac-sha256", uses: ["mac", "equal"] });
export const optOuts = table({ email: t.string }, { key: ["email"] });

export const unsubscribe = mutation(
  { on: route.post("/unsubscribe", verifier.none()), refuses: { InvalidLink: null } },
  async (ctx, request) => {
    const token = request.query.token;
    if (typeof token !== "string" || !(await verifyJwt(ctx, unsubscribeKey, token)))
      return ctx.refuse("InvalidLink", "The unsubscribe link is invalid or expired.");

    let claims: { email?: unknown; exp?: unknown } | null;
    try {
      const payload = token.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/");
      const bytes = Uint8Array.from(atob(payload), (char) => char.charCodeAt(0));
      claims = JSON.parse(new TextDecoder().decode(bytes));
    } catch {
      return ctx.refuse("InvalidLink", "The unsubscribe link is invalid or expired.");
    }
    const { email, exp } = claims ?? {};
    if (typeof email !== "string" || typeof exp !== "number" ||
        !Number.isSafeInteger(exp) || exp <= 0 || exp > 8_640_000_000_000 ||
        !(ctx.frame.now.before(Temporal.Instant.fromEpochMilliseconds(exp * 1000))))
      return ctx.refuse("InvalidLink", "The unsubscribe link is invalid or expired.");

    await ctx.put(optOuts(email), { email });
    return { unsubscribed: true };
  },
);
```

The `Request` is `{ method, path, headers, query, body, file }`:

* `headers` are by lower-case name, without the `authorization` the host
  verified;
* `query` holds each name once, and a repeated name refuses `RepeatedQuery`;
* `body` is the JSON or form value, or `null`;
* `file` is an upload: a non-JSON body the host stored at ingress under the
  reaction's label. Keep the `File` point in a `t.file` field. It is
  `null` for a JSON body. See [Uploading files](https://docs.bijection.com/files/upload.md).

A route reaction declares no `args`: everything it receives is the request.

Its return value is a JSON `200` body, or a string as `text/plain`. To set the
status and headers, return exactly `{ status, headers, body }`: `status` is
200 to 599, `headers` at most 32 by lower-case name, and `body` a string or a
JSON value (empty for 204, 205 and 304):

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const feed = mutation({ on: route.get("/feed.xml", verifier.none()) }, async (ctx) => ({
  status: 200,
  headers: { "content-type": "application/rss+xml", "cache-control": "max-age=300" },
  body: await rss(ctx),
}));
```

The path is relative to the app that holds the reaction. A reaction with
`route.post("/operator/plan", verifier.session())` in an app mounted at `mail` serves
`/mail/operator/plan`; a root app's reaction serves its path as written.
`route.path(reaction)` from `@bijectionhq/bijection` answers the full
path, to build a public URL to an app's own route.

### Verify a route

Name the verifier as the second argument of every route. The SDK provides
these verifiers:

| Verifier | Admits |
| - | - |
| `verifier.session()` | A request with an application session. The reaction may then declare `allow: [roles]`, admitting only a caller who holds one. |
| `verifier.bearer(secret)` | A request whose `Authorization: Bearer` equals the [secret](https://docs.bijection.com/functions/secrets.md). |
| `verifier.none()` | Every request, stated explicitly. |

Webhook verifiers for particular senders come with the
[integrations](https://docs.bijection.com/integrations) that receive them. For Stripe, use
`route.post("/stripe", providerWebhooks.stripe(stripeSigning))` with
`providerWebhooks` from `@bijectionhq/library-connectors/webhooks`.

## Change sources

`.changes` on a table, a selection or a point is its change log, and as a
source it fires once per change:

```ts bijection/decisions.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const stamp = mutation({ on: shipmentDecisions.changes }, async (ctx, change) => {
  if (change.after !== null && change.after.version === null)
    await ctx.patch(shipmentDecisions(change.key), { version: change.version });
});
```

The change is `{ key, before, after, version }`: the fact before and after the
commit (`null` for an insert or a removal) and the version that committed it.
On a [family](https://docs.bijection.com/database/family-tables.md) table, one member's selection is
`t.of(family.of(key)).where({ … }).changes`.

## Authority

A reaction runs as the installation. `roles` are the roles it holds while it
runs: they decide what it clears and which guards see it (a guard sees
`a.offer.role` for the grant the act runs through). A reaction with no `roles` holds
none.

Each firing commits in its own transaction and is decided afresh: a
reaction's acts are checked against what its roles allow at that moment.

## Test reactions

The test kernel's clock runs what falls due: `k.advance({ hours: 1 })` fires
`every` and `cron` reactions, and committed changes run change reactions.
`k.route(reaction, { method, body, headers, query, as })` delivers a request to a
route as the host does once its verifier passed, and answers a `Result`. See
[Testing](https://docs.bijection.com/development/testing/test-library.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.