# Workers events

On the `cloudflare` preset the Worker answers more than HTTP requests. Its default export has four handlers beside `fetch`: `scheduled` (a Cron Trigger), `queue` (a Queues batch), `email` (Email Routing) and `tail` (trace events of another Worker). Each one runs after the server plugins, with the runtime config and env resolved from that call's `env`, so a Worker woken by a cron reads its secrets as a request does.

A **platform event hook** is a server hook named `<platform>:<event>` that the entry calls with the platform's own argument object. A [server plugin](/server#plugins-and-hooks) listens to it with `server.hooks.hook`. Hamur adds no API per platform: the hook is how your code handles the event.

| Handler                           | Hook and its argument                                | What Hamur does itself                                                                                              | `.output/wrangler.json`                                                                       |
| --------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `scheduled(controller, env, ctx)` | `cloudflare:scheduled({ controller, env, context })` | runs every task of `scheduledTasks` whose Cloudflare form of the expression equals `controller.cron`, then the hook | `triggers.crons`: your own entries, then the Cloudflare forms, without duplicates             |
| `queue(batch, env, ctx)`          | `cloudflare:queue({ batch, env, context })`          | runs the messages of the task queue, below                                                                          | `queues.consumers`: `{ queue: tasks.queue.name }` unless your config already lists that queue |
| `email(message, env, ctx)`        | `cloudflare:email({ message, env, context })`        | nothing; with no listener it calls `message.setReject("No email handler")`                                          | none; routing rules live in the dashboard                                                     |
| `tail(events, env, ctx)`          | `cloudflare:tail({ events, env, context })`          | nothing                                                                                                             | none; the producer Worker's `tail_consumers` names this Worker                                |

The four handlers are always exported, because plugins register their listeners at run time and the build cannot know which are needed. The hook arguments are structural types in `hamur/server`, with no import of `@cloudflare/workers-types`; `Parameters<ServerHooks["cloudflare:queue"]>[0]` names one.

````ts [server/workers-events.ts]
import { definePlugin } from "hamur/server"

export const events = definePlugin((server) => {
  server.hooks.hook("cloudflare:scheduled", ({ controller }) => {
    server.log.info("cron fired", { cron: controller.cron, at: controller.scheduledTime })
  })

  server.hooks.hook("cloudflare:queue", ({ batch }) => {
    if (batch.queue !== "emails") return
    for (const message of batch.messages) {
      server.log.info("email job", { id: message.id, attempts: message.attempts })
      message.ack()
    }
  })

  server.hooks.hook("cloudflare:email", async ({ message }) => {
    if (message.to === "support@example.com") await message.forward("team@example.net")
    else message.setReject("No such mailbox")
  })
})
````

````jsonc [wrangler-events.jsonc]
{
  "name": "my-app",
  "queues": { "consumers": [{ "queue": "emails" }] },
  "triggers": { "crons": ["0 * * * *"] },
}
````

## Cron

`scheduledTasks` expressions are written to `triggers.crons` in the form Cloudflare reads, with weekday names (`0 9 * * 1` becomes `0 9 * * MON`), because Cloudflare reads `1` as Sunday and matches `controller.cron` to the configuration character for character. `scheduled` runs each task in table order and passes `controller.scheduledTime` to the task as `ctx.scheduledTime`. See [Tasks](/tasks#where-schedules-run).

## Queues

`tasks.queue: { name, binding? }` is the only queue key. `name` is the queue `enqueue` sends to and the queue the Worker consumes, so `queue` splits by `batch.queue`:

- **The task queue.** Each message body is `{ task, payload }`, what `enqueue` sends. The task runs, and `message.ack()` is called when it resolves and `message.retry()` when it throws, which reaches the `task:error` hook. A body of another shape is logged at `error` and retried; Cloudflare's retries and dead-letter queue then apply, so configure one. Then `cloudflare:queue` is called with the same batch, for information.
- **Any other queue.** Your own consumer, declared in your wrangler config: Hamur runs nothing and `cloudflare:queue` is the consumer, as in the sample. With no listener the handler throws `queue "<name>" has no cloudflare:queue hook`, so Cloudflare retries the batch and nothing is acknowledged silently.

If your wrangler config declares the producer of `tasks.queue.binding` itself, it must send to the queue `tasks.queue.name` names, or the build fails: `tasks.queue.name is "jobs", but the app's wrangler config sends the TASKS_QUEUE producer to queue "jobs-staging"; set tasks.queue.name to the same queue, or remove that producer`.

## Hook promises

The promise a hook returns goes to `ctx.waitUntil`, followed by the flush of logs and spans. Cloudflare fails a whole queue batch when a `waitUntil` promise rejects, so a rejecting `cloudflare:queue` listener makes Cloudflare retry the batch. A rejection in `cloudflare:scheduled` or `cloudflare:tail` is logged at `error`.

`email` is the exception: the handler awaits its listeners itself, because `setReject`, `forward` and `reply` must happen before the handler ends, and a listener that throws makes the handler throw, so a mail no listener handled is never accepted and dropped.

The hooks are in the [API reference](/api-reference/server#defineplugin-serverplugin-hamurserver-serverhooks-errorcontext-errorphase). `cloudflare-pages` has no Workers events: a Pages Function has no cron trigger, queue consumer or Durable Object, and the build fails for `scheduledTasks`, `tasks.queue` and Durable Objects there.
