From 566b2bc3239f6e1e586900b06fad4d9ad50c035c Mon Sep 17 00:00:00 2001 From: Todos Date: Wed, 28 Oct 2026 20:00:35 +0800 Subject: [PATCH 1/2] feat(worker): add waker callback receiver and hourly tick claims Copy waker-client 2.0.0 verbatim into worker/src/waker, mount /_waker before the SPA fallback, and route both the native cron and the callback through runSchedulerTick with an atomic D1 hour claim. Adds schema_v3 (execution ledger + claim table), optional WAKER_SIGNING_KEY injection with a CI interlock, docs and 45 tests. Checkpoint: nLhckbvBTlUe_VBsQbdaN --- .github/workflows/deploy.yml | 37 ++- CLAUDE.md | 18 +- README.en.md | 46 +++ README.md | 46 +++ biome.json | 3 +- pnpm-lock.yaml | 10 +- worker/package.json | 2 +- worker/src/db/queries/scheduler-ticks.ts | 122 ++++++++ worker/src/db/schema.sql | 26 ++ worker/src/index.ts | 20 +- worker/src/lib/migrations.ts | 34 ++ worker/src/routes/waker.ts | 43 +++ worker/src/services/scheduler-tick.ts | 204 ++++++++++++ worker/src/services/waker-callback.ts | 75 +++++ worker/src/types.ts | 9 + worker/src/waker/README.md | 26 ++ worker/src/waker/client.ts | 322 +++++++++++++++++++ worker/src/waker/index.ts | 18 ++ worker/src/waker/ledger.ts | 236 ++++++++++++++ worker/src/waker/modes.ts | 61 ++++ worker/src/waker/protocol.ts | 137 ++++++++ worker/src/waker/receiver.ts | 331 ++++++++++++++++++++ worker/src/waker/verify.ts | 104 +++++++ worker/test/admin.test.ts | 2 + worker/test/ledger.test.ts | 55 +++- worker/test/migrations.test.ts | 7 +- worker/test/prefix.test.ts | 3 + worker/test/scheduled-entry.test.ts | 208 +++++++++++++ worker/test/scheduler-tick.test.ts | 378 +++++++++++++++++++++++ worker/test/setup.test.ts | 3 + worker/test/support/sqlite-d1.ts | 25 +- worker/test/waker-callback.test.ts | 367 ++++++++++++++++++++++ worker/test/waker-equivalence.test.ts | 272 ++++++++++++++++ 33 files changed, 3222 insertions(+), 28 deletions(-) create mode 100644 worker/src/db/queries/scheduler-ticks.ts create mode 100644 worker/src/routes/waker.ts create mode 100644 worker/src/services/scheduler-tick.ts create mode 100644 worker/src/services/waker-callback.ts create mode 100644 worker/src/waker/README.md create mode 100644 worker/src/waker/client.ts create mode 100644 worker/src/waker/index.ts create mode 100644 worker/src/waker/ledger.ts create mode 100644 worker/src/waker/modes.ts create mode 100644 worker/src/waker/protocol.ts create mode 100644 worker/src/waker/receiver.ts create mode 100644 worker/src/waker/verify.ts create mode 100644 worker/test/scheduled-entry.test.ts create mode 100644 worker/test/scheduler-tick.test.ts create mode 100644 worker/test/waker-callback.test.ts create mode 100644 worker/test/waker-equivalence.test.ts diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 6fb3f8c..e6d8af9 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -67,15 +67,44 @@ jobs: env: JWT_SECRET: ${{ secrets.JWT_SECRET }} SETUP_SECRET: ${{ secrets.SETUP_SECRET }} + WAKER_SIGNING_KEY: ${{ secrets.WAKER_SIGNING_KEY }} run: | node -e ' const fs = require("fs"); + const secrets = { + JWT_SECRET: process.env.JWT_SECRET, + SETUP_SECRET: process.env.SETUP_SECRET, + }; + + // Optional waker callback signing key — the only waker-related + // setting this project has. Only its presence is logged, never its + // value; the trimmed value is what the receiver verifies with. + // Same rule as the runtime gate (wakerSigningKey()): a trimmed value + // ending in _PLACEHOLDER is still a placeholder, i.e. unconfigured. + const wakerKey = (process.env.WAKER_SIGNING_KEY || "").trim(); + const wakerConfigured = + wakerKey.length > 0 && !wakerKey.endsWith("_PLACEHOLDER"); + if (wakerConfigured) { + secrets.WAKER_SIGNING_KEY = wakerKey; + console.log("WAKER_SIGNING_KEY: configured"); + } else { + console.log("WAKER_SIGNING_KEY: not configured (native cron only)"); + } + + // Interlock: once wrangler.toml has no [triggers], the waker task is + // the only schedule source. Losing the key as well would silently + // stop every hourly sweep, so fail the deploy instead. + const wranglerToml = fs.readFileSync("wrangler.toml", "utf8"); + if (!wakerConfigured && !/^\[triggers\]/m.test(wranglerToml)) { + console.error( + "neither [triggers] nor WAKER_SIGNING_KEY is configured: nothing would run", + ); + process.exit(1); + } + fs.writeFileSync( process.env.RUNNER_TEMP + "/secrets.json", - JSON.stringify({ - JWT_SECRET: process.env.JWT_SECRET, - SETUP_SECRET: process.env.SETUP_SECRET, - }), + JSON.stringify(secrets), { mode: 0o600 }, ); ' diff --git a/CLAUDE.md b/CLAUDE.md index f84cf76..4e7516a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,7 +41,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` ### Backend (`worker/`) -**Entry point**: `worker/src/index.ts` — registers all Hono routes and the scheduled handler. +**Entry point**: `worker/src/index.ts` — registers all Hono routes, the `/_waker` callback mount (before the SPA fallback) and the native scheduled handler. **Route structure** (`worker/src/routes/`): @@ -52,12 +52,13 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - `dashboard.ts` — spending stats, expiry summary - `admin.ts` — user management, system settings; also manages items per user at `/api/admin/users/:uid/items` - `notify.ts` — manual notification test trigger +- `waker.ts` — `/_waker` mount for the waker callback receiver (SDK paths, signature and idempotency only; mounted before `app.get("*")` so a callback can never be answered with 200 HTML) - `setup.ts` — one-time DB initialization via `SETUP_SECRET` (rate-limited, 3/10min per IP); also exposes `GET /api/setup/state` (public setup-page toggle) and `POST /api/admin/setup` (admin-only, no secret). Core setup/migration logic lives in `worker/src/lib/setup.ts`. `runSetup` is a three-branch state machine after the prefix guard: ledger present → apply unrecorded migrations; no ledger but business tables present → pre-ledger in-place transition (legacy patches → shape verification → stamp `schema_v1`); neither → fresh install through the ledger. **Database** (`worker/src/db/`): - Cloudflare D1 (SQLite). `worker/src/db/schema.sql` is the readable full schema (used by tests); the runtime source of truth is the migration list below. -- **Migrations are ledger-based.** The ordered list lives in `worker/src/lib/migrations.ts` (`getMigrations(prefix)`, currently a single collapsed `schema_v1` = the whole schema); `worker/src/lib/migrations-runner.ts` applies the not-yet-recorded ones in order and records each name in the ledger, throwing on the first failure (a migration is recorded only after all of its statements succeeded). Append new migrations only at the END of the list as `schema_vN`; never rename, edit or reorder a merged migration; migrations must be additive (`CREATE TABLE/INDEX IF NOT EXISTS`, `ADD COLUMN`, `INSERT OR IGNORE` — no `DROP`/`RENAME`/data rewrites); migration SQL string literals must not contain `;` (the runner splits on `;` and runs the statements one by one). +- **Migrations are ledger-based.** The ordered list lives in `worker/src/lib/migrations.ts` (`getMigrations(prefix)`: `schema_v1` = the whole schema at ledger introduction, `schema_v2` = notification-history `trigger_source`, `schema_v3` = `{prefix}waker_executions` + `{prefix}scheduler_tick_claims`); `worker/src/lib/migrations-runner.ts` applies the not-yet-recorded ones in order and records each name in the ledger, throwing on the first failure (a migration is recorded only after all of its statements succeeded). Append new migrations only at the END of the list as `schema_vN`; never rename, edit or reorder a merged migration; migrations must be additive (`CREATE TABLE/INDEX IF NOT EXISTS`, `ADD COLUMN`, `INSERT OR IGNORE` — no `DROP`/`RENAME`/data rewrites); migration SQL string literals must not contain `;` (the runner splits on `;` and runs the statements one by one). - The ledger table name is built only by `migrationsTable()`: `_` + prefix core (trailing `_` stripped, case preserved) + `_schema_migrations`, i.e. `_enotify_schema_migrations` for the default prefix and `_schema_migrations` with no prefix. Ledger tables are not part of the eNotify table family and are ignored by `detectTablePrefixes()` (other projects' ledgers coexist in a shared D1). - Transitioning a pre-ledger database, production cutover and rollback: `docs/migration-ledger-cutover-runbook.md`. - All table names use a `{prefix}` placeholder at definition time, resolved at runtime via `TABLE_PREFIX` env var and the `getTablePrefix()` helper in `types.ts` (the ONLY resolution point). Three states: unset/null → default `enotify` (`enotify_`); custom non-empty value → verbatim with trailing `_`; explicit `""` → no prefix. `runSetup` in `worker/src/lib/setup.ts` detects existing initialized schemas under other prefixes via `detectTablePrefixes()` and aborts with 409 `PREFIX_CONFLICT` instead of silently re-initializing; CI maps unset/empty vars to `enotify` and the reserved word `none` to `""`. @@ -72,18 +73,27 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` **Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Slack, Feishu, Discord, WeChatBot) is a separate file. `index.ts` sends to selected enabled channels via the `channels` parameter, or only to the user's default channel when no channels are selected. -**Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly via Cloudflare Cron Trigger (`0 * * * *`). For each active user it: +**Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly. For each active user it: 1. Checks their allowed notification hours (per-timezone). 2. Auto-renews expired items (with KV deduplication). 3. Sends reminders for items expiring within the user's configured threshold (with per-hour KV deduplication). If an item has specific channels configured (`channels` column), only those channels are used; otherwise only the user's default channel receives the notification. +`services/scheduler.ts` is the single business implementation. Both schedule entries go through `services/scheduler-tick.ts` `runSchedulerTick(env, { source, scheduledFor })`: + +- **native entry**: `scheduled()` in `index.ts`, `source: "cron"`, `scheduledFor: event.scheduledTime` (awaited, not `waitUntil`); +- **waker entry**: `services/waker-callback.ts`, job `hourly-reminder-sweep`, `source: "waker"`, `scheduledFor: ctx.scheduledFor`; mounted at `/_waker` by `routes/waker.ts` using the verbatim SDK copy in `worker/src/waker/` (waker-client 2.0.0 — never hand-edit that directory). + +The guard in front of the business pass is one atomic D1 claim per UTC hour (`{prefix}scheduler_tick_claims`, `INSERT … ON CONFLICT(tick_key) DO NOTHING` + `meta.changes`), so cron and waker can never sweep the same hour twice; the SDK's own `{prefix}waker_executions` ledger dedupes executionId retries. Failure semantics: cron keeps the claim on failure (no re-run that could double-send), waker releases it and rethrows so the platform retry (same executionId) completes the hour. Claims are pruned after 7 days. + +Waker is optional and the **only** setting is `WAKER_SIGNING_KEY` (GitHub Secret → `wrangler deploy --secrets-file`): unset/blank/`*_PLACEHOLDER` means native cron only. The gate is `wakerSigningKey()` in `services/scheduler-tick.ts`; the receiver stays mounted and fails closed with 500 JSON `signing_key_missing`. Do not reintroduce `WAKER_MODE`/`WAKER_URL`/project tokens — the SDK's `mountWakerReceiver`, `createWakerClient*`, `syncManifest` and `resolveWakerMode` must stay uncalled. + **Cloudflare bindings**: - `DB` — D1 database - `KV` — KV namespace (used for scheduler deduplication and status) - `ASSETS` — static file serving -- Secrets: `JWT_SECRET`, `SETUP_SECRET` +- Secrets: `JWT_SECRET`, `SETUP_SECRET`, and optional `WAKER_SIGNING_KEY` (empty ⇒ native cron only) - Env var: `TABLE_PREFIX` (three states: unset → default `enotify`, tables like `enotify_users`; custom value → verbatim with trailing `_`; explicit `""`/CI `none` → no prefix; allows shared DB with prefix isolation) ### Frontend (`web/`) diff --git a/README.en.md b/README.en.md index 059c9b4..64b9d87 100644 --- a/README.en.md +++ b/README.en.md @@ -60,6 +60,7 @@ In your repository Settings → Secrets and variables → Actions, add: | `CLOUDFLARE_API_TOKEN` | Cloudflare API Token (needs Workers and D1 permissions) | | `JWT_SECRET` | Any random 64-char string — e.g. `openssl rand -hex 32` | | `SETUP_SECRET` | Any random string — e.g. `openssl rand -hex 16` | +| `WAKER_SIGNING_KEY` | **Optional** waker callback signing key; leave unset to stay on native cron (see "Waker Scheduling") | In Settings → Secrets and variables → Actions → Variables, add: @@ -185,6 +186,51 @@ CI deployment convention (`.github/workflows/deploy.yml`): a GitHub Variables `T | `JWT_SECRET` | JWT signing secret, any random 64-char string | | `SETUP_SECRET` | Database initialization route secret, any random string | | `TABLE_PREFIX` | Table prefix, three states: unset → default `enotify` (tables like `enotify_users`); explicit empty string / CI `none` → no prefix; custom value → verbatim with trailing `_` | +| `WAKER_SIGNING_KEY` | Optional. Waker callback signing key; missing / blank / `*_PLACEHOLDER` means unconfigured → native cron only | + +## Waker Scheduling (optional) + +By default the hourly reminder sweep runs on the native Cloudflare Cron Trigger (`[triggers]` in `worker/wrangler.toml`, `0 * * * *` UTC). It can also be driven by the [waker](https://github.com/WorkerHub/waker) platform: **the only setting is `WAKER_SIGNING_KEY`** — leave it unset and the default cron keeps running; set it and both entries coexist, arbitrated by an hourly claim, so nothing is sent twice. + +> Signature verification, the timestamp window and executionId idempotency come from the official SDK source copy (`worker/src/waker/`, `@workerhub/waker-client` 2.0.0). That directory must not be edited by hand. + +### 1. Configure the signing key (optional) + +Add the GitHub Secret `WAKER_SIGNING_KEY` (value = the signing key the waker console shows **once** when the project is created; keep a copy in your password manager first). At deploy time it is only written to `$RUNNER_TEMP/secrets.json` (0600) and uploaded via `wrangler deploy --secrets-file`; CI logs only `configured` / `not configured`, **never the value**. + +Empty, whitespace-only, `undefined` and `*_PLACEHOLDER` values are all treated as "not configured". In that state the receiver is still mounted but fails closed: a real callback gets **500 JSON `signing_key_missing`**, a request without signature headers gets 400, and `GET /_waker/execute` gets 404 — it **never falls through to the SPA's 200 HTML**, never queries the DB, writes the ledger or runs business code. Deploying without the key always succeeds. + +### 2. Create the job in the waker console + +Create a project `eNotify` (callback URL = your production domain; the platform appends `/_waker/execute`), then one declarative job: + +| Field | Value | +| --- | --- | +| Job name | `hourly-reminder-sweep` (must match `WAKER_JOB_NAME` in the code verbatim, otherwise the callback gets 404 `unknown_job`) | +| Kind | cron | +| Cron | `0 * * * *` | +| Timezone | `UTC` | +| Payload | `{}` | +| Misfire | `fire_once` | +| Concurrency | `forbid` | +| maxRetries | `2` | +| backoffSeconds | `30` | +| timeoutSeconds | `300` | +| jitterSeconds | `0` | +| enabled | `true` | + +There is no registration client, project token, dynamic registration/cancellation or self-renewal in this repo: the job is maintained in the console only. The handler **awaits the business pass** before answering 2xx; failures are retried by the platform and the same executionId never runs twice. + +### 3. Database migration + +`schema_v3` adds two tables under the configured table prefix (default `enotify_waker_executions`, `enotify_scheduler_tick_claims`): the SDK's executionId idempotency ledger and the hourly claim table. After upgrading, call `POST /api/setup` once (or use "check and upgrade database" in the admin UI); migrations are additive and re-runnable. If the key is configured while the claim table does not exist yet, **both** entries stop safely (no double-send wins), so migrate before configuring the key. + +### 4. Dual run, cutover and disabling + +- **Dual run**: while `[triggers]` stays, both entries exist. Each UTC hour exactly one of them wins the D1 claim and runs the sweep; the other one skips (the waker side answers `duplicate_tick`), so no notification or renewal happens twice. Claim rows are kept for 7 days for troubleshooting. +- **Cut over to waker only**: first confirm exactly one claim row per hour (`SELECT tick_key, source, claimed_at FROM enotify_scheduler_tick_claims ORDER BY claimed_at DESC LIMIT 6`), then delete `[triggers]` from `worker/wrangler.toml` and deploy. CI interlocks: deploying with no `[triggers]` and no `WAKER_SIGNING_KEY` fails outright (otherwise nothing would run at the top of the hour). +- **Disable callbacks**: `wrangler deploy --secrets-file` is additive (omitting a key does not delete the old value). Restore `[triggers]`, deploy, and explicitly run `npx wrangler secret delete WAKER_SIGNING_KEY`. Even if you forget, the hourly claim still prevents duplicate runs. +- **Rotate the key**: rotate in the waker console → the old key stops working immediately → update the GitHub Secret `WAKER_SIGNING_KEY` → redeploy. Callbacks during the window are rejected (401) and retried by the platform. ## License diff --git a/README.md b/README.md index 5893255..20d036f 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ npx wrangler kv namespace create ENOTIFY_KV | `CLOUDFLARE_API_TOKEN` | Cloudflare API Token(需 Workers 和 D1 权限) | | `JWT_SECRET` | 任意 64 位随机字符串,例如 `openssl rand -hex 32` | | `SETUP_SECRET` | 任意随机字符串,例如 `openssl rand -hex 16` | +| `WAKER_SIGNING_KEY` | **可选**,waker 回调验签密钥;不配则只用原生 cron(见「定时调度与 waker」) | 在 Settings → Secrets and variables → Actions → Variables 中添加: @@ -190,6 +191,51 @@ CI 部署约定(`.github/workflows/deploy.yml`):GitHub Variables 中的 `T | `JWT_SECRET` | JWT 签名密钥,任意 64 位随机字符串 | | `SETUP_SECRET` | 数据库初始化路由密钥,任意随机字符串 | | `TABLE_PREFIX` | 数据库表前缀,三态:未设置 → 默认 `enotify`(表名如 `enotify_users`);显式空串/CI `none` → 无前缀;自定义值 → 原样补尾 `_` | +| `WAKER_SIGNING_KEY` | 可选。waker 回调验签密钥;缺失/空白/`*_PLACEHOLDER` = 未配置,只走原生 cron | + +## 定时调度与 waker(可选) + +默认用 Cloudflare 原生 Cron Trigger(`worker/wrangler.toml` 的 `[triggers]`,`0 * * * *` UTC)跑每小时提醒扫描。也可以改由 [waker](https://github.com/WorkerHub/waker) 平台调度:**唯一需要配置的只有 `WAKER_SIGNING_KEY`**——不配就走默认 cron,配了则两个入口并存、按整点认领互斥,不会重复推送。 + +> 回调的验签、时间窗与 executionId 幂等由官方 SDK 源码拷贝(`worker/src/waker/`,`@workerhub/waker-client` 2.0.0)负责,本仓不自己实现协议;该目录不得手改。 + +### 1. 配置签名密钥(可选) + +在仓库 Settings → Secrets and variables → Actions 增加 Secret `WAKER_SIGNING_KEY`(值 = waker 控制台建项目时**一次性展示**的 signing key,先在密码管理器留底)。部署时它只写入 `$RUNNER_TEMP/secrets.json`(0600)再经 `wrangler deploy --secrets-file` 上传;CI 只打印 `configured` / `not configured` 状态,**永不打印值**。 + +空值、纯空白、`undefined` 与以 `_PLACEHOLDER` 结尾的值一律视为「未配置」。未配置时 receiver 仍然挂载、但 fail closed:真回调返回 **500 JSON `signing_key_missing`**,缺签名头返回 400,`GET /_waker/execute` 返回 404——**绝不会落到 SPA 的 200 HTML**,也不会查库、写账本或触发业务。未配 key 的部署必然成功。 + +### 2. 在 waker 控制台建任务 + +新建项目 `eNotify`(回调地址填本站生产域名,平台自动补 `/_waker/execute`),再建一个声明式任务: + +| 字段 | 值 | +| --- | --- | +| 任务名 | `hourly-reminder-sweep`(必须与代码里的 `WAKER_JOB_NAME` 逐字一致,否则回调 404 `unknown_job`) | +| 类型 | cron | +| cron | `0 * * * *` | +| 时区 | `UTC` | +| payload | `{}` | +| misfire | `fire_once` | +| concurrency | `forbid` | +| maxRetries | `2` | +| backoffSeconds | `30` | +| timeoutSeconds | `300` | +| jitterSeconds | `0` | +| enabled | `true` | + +本仓不提供注册客户端、不存放项目令牌、不做动态注册/取消/自续:任务只在控制台手工维护。回调 handler 会**同步等业务跑完**才回 2xx,失败由平台按策略重试(同一 executionId 重试不会重复执行)。 + +### 3. 数据库迁移 + +`schema_v3` 在项目的表前缀下新建两张表(默认 `enotify_waker_executions`、`enotify_scheduler_tick_claims`):前者是 SDK 的 executionId 幂等账本,后者是整点认领表。升级部署后照常调一次 `POST /api/setup`(或管理面「检查并升级数据库」)即可;迁移只增不改、幂等可重跑。键已配但认领表还没建时,两个入口都会安全停跑(不重复发送优先),所以**先迁移再配 key**。 + +### 4. 双跑、切换与停用 + +- **双跑**:`[triggers]` 保留期间两个入口并存。每个 UTC 整点只有一个入口在 D1 里认领成功并真正跑扫描,另一侧直接跳过(waker 侧响应 `duplicate_tick`),所以不会重复推送/重复续期;认领行保留 7 天用于排障。 +- **切换成 waker 独占**:先确认认领表每小时恰好一行(`SELECT tick_key, source, claimed_at FROM enotify_scheduler_tick_claims ORDER BY claimed_at DESC LIMIT 6`),再删除 `worker/wrangler.toml` 的 `[triggers]` 并部署。CI 有互锁:`[triggers]` 不存在且 `WAKER_SIGNING_KEY` 为空时部署直接失败(否则整点将没有任何调度入口)。 +- **停用回调**:`wrangler deploy --secrets-file` 是增量语义(省略某个键不会删除旧值),所以要恢复 `[triggers]` 部署,并显式执行 `npx wrangler secret delete WAKER_SIGNING_KEY`。即使忘记删,整点认领也保证不会重复执行。 +- **轮换 key**:在 waker 控制台轮换 → 旧 key 立即失效 → 更新 GitHub Secret `WAKER_SIGNING_KEY` → 重新部署。轮换窗口内的回调会因验签失败被拒(401),平台按策略重试。 ## 许可证 diff --git a/biome.json b/biome.json index f3899e3..807eba0 100644 --- a/biome.json +++ b/biome.json @@ -8,7 +8,8 @@ "!**/.wrangler", "!**/web/public", "!**/web/dist", - "!**/worker/.wrangler" + "!**/worker/.wrangler", + "!**/worker/src/waker" ] }, "formatter": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 42c8477..b84feb0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -291,8 +291,8 @@ importers: specifier: ^14.0.0 version: 14.0.3 hono: - specifier: ^4.7.9 - version: 4.13.13 + specifier: ^4.13.14 + version: 4.13.14 otpauth: specifier: ^9.4.2 version: 9.5.2 @@ -2804,8 +2804,8 @@ packages: resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} engines: {node: '>= 0.4'} - hono@4.13.13: - resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==} + hono@4.13.14: + resolution: {integrity: sha512-yhRLQ21U6qa9Hsu2N7Qcbh8tE+WKEcoErjIo56LeSGiGXGp9sA7UpE86Ui9uexb61KakiGwuHMn2QdV7w6i6kQ==} engines: {node: '>=16.9.0'} html-parse-stringify@4.0.1: @@ -6373,7 +6373,7 @@ snapshots: dependencies: function-bind: 1.1.2 - hono@4.13.13: {} + hono@4.13.14: {} html-parse-stringify@4.0.1: {} diff --git a/worker/package.json b/worker/package.json index 2321f5a..d17aecf 100644 --- a/worker/package.json +++ b/worker/package.json @@ -12,7 +12,7 @@ "dependencies": { "@hexagon/base64": "^2.0.2", "@simplewebauthn/server": "^14.0.0", - "hono": "^4.7.9", + "hono": "^4.13.14", "otpauth": "^9.4.2" }, "devDependencies": { diff --git a/worker/src/db/queries/scheduler-ticks.ts b/worker/src/db/queries/scheduler-ticks.ts new file mode 100644 index 0000000..613f42e --- /dev/null +++ b/worker/src/db/queries/scheduler-ticks.ts @@ -0,0 +1,122 @@ +/** + * Cross-entry scheduler tick claims + waker execution-ledger table names. + * + * Why this table exists: while the native Cloudflare cron trigger and a waker + * declarative job both fire at the same hour, only one of them may run the + * hourly scan. D1/SQLite gives us a single-statement atomic claim + * (`INSERT ... ON CONFLICT(tick_key) DO NOTHING` + `meta.changes`), which is the + * same primitive the waker SDK ledger already uses for executionId idempotency + * — no hand-rolled distributed lock, no read-then-write window. + * + * Table names are always built here and resolved through `getTablePrefix(env)` + * by the caller; the prefix is never hard-coded. + */ + +/** Suffix of the SDK executionId idempotency ledger (created by `schema_v3`). */ +export const WAKER_EXECUTIONS_TABLE = "waker_executions"; + +/** Suffix of the per-hour cross-entry claim table (created by `schema_v3`). */ +export const SCHEDULER_TICK_CLAIMS_TABLE = "scheduler_tick_claims"; + +/** Which entry point claimed the hour; observability only, never used for routing. */ +export type SchedulerTickSource = "cron" | "waker"; + +/** `{prefix}waker_executions`. */ +export function wakerExecutionsTable(prefix: string): string { + return `${prefix}${WAKER_EXECUTIONS_TABLE}`; +} + +/** `{prefix}scheduler_tick_claims`. */ +export function schedulerTickClaimsTable(prefix: string): string { + return `${prefix}${SCHEDULER_TICK_CLAIMS_TABLE}`; +} + +/** + * Nominal hour slot of a trigger, as the claim key: `"hour:"`. + * + * Both entry points round their *nominal* scheduled time (cron + * `event.scheduledTime`, waker `ctx.scheduledFor`) to the hour, so a waker + * misfire replay still maps onto the same slot as the cron firing it is + * competing with. Hours do not depend on the process timezone: the epoch value + * is UTC-based. + */ +export function schedulerTickKey(scheduledFor: number): string { + const slot = Math.floor(scheduledFor / 3_600_000) * 3_600_000; + return `hour:${slot}`; +} + +export interface SchedulerTickClaimRow { + tick_key: string; + source: string; + claimed_at: number; +} + +/** + * Try to win one hour slot. Returns `true` when this caller inserted the row + * (`meta.changes > 0`), `false` when the slot is already claimed. + */ +export async function claimSchedulerTick( + db: D1Database, + prefix: string, + tickKey: string, + source: SchedulerTickSource, + now: number, +): Promise { + const result = await db + .prepare( + `INSERT INTO ${schedulerTickClaimsTable(prefix)} (tick_key, source, claimed_at) + VALUES (?, ?, ?) + ON CONFLICT(tick_key) DO NOTHING`, + ) + .bind(tickKey, source, now) + .run(); + return (result.meta?.changes ?? 0) > 0; +} + +/** Read the claim of one hour slot (only used to report who won it). */ +export async function getSchedulerTickClaim( + db: D1Database, + prefix: string, + tickKey: string, +): Promise { + return db + .prepare( + `SELECT tick_key, source, claimed_at FROM ${schedulerTickClaimsTable(prefix)} + WHERE tick_key = ?`, + ) + .bind(tickKey) + .first(); +} + +/** + * Drop a claim this source made, so a waker retry (same executionId) can claim + * the hour again. Scoped by `source` so it can never release the other entry's + * claim. + */ +export async function releaseSchedulerTick( + db: D1Database, + prefix: string, + tickKey: string, + source: SchedulerTickSource, +): Promise { + await db + .prepare( + `DELETE FROM ${schedulerTickClaimsTable(prefix)} WHERE tick_key = ? AND source = ?`, + ) + .bind(tickKey, source) + .run(); +} + +/** Delete claims older than `beforeEpochMs` (7-day retention, keeps the table small). */ +export async function pruneSchedulerTicks( + db: D1Database, + prefix: string, + beforeEpochMs: number, +): Promise { + await db + .prepare( + `DELETE FROM ${schedulerTickClaimsTable(prefix)} WHERE claimed_at < ?`, + ) + .bind(beforeEpochMs) + .run(); +} diff --git a/worker/src/db/schema.sql b/worker/src/db/schema.sql index 531b229..49f5636 100644 --- a/worker/src/db/schema.sql +++ b/worker/src/db/schema.sql @@ -112,3 +112,29 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_history ( CREATE INDEX IF NOT EXISTS idx_{prefix}notification_history_user_id ON {prefix}notification_history(user_id, created_at); + +-- Waker executionId idempotency ledger (SDK `createD1ExecutionLedger`). +-- The eight columns are frozen verbatim from waker-client 2.0.0 +-- `executionLedgerDdl()` — schema_v3 creates the same table at runtime. +-- (Keep semicolons out of these comment lines: tests split this file on them.) +CREATE TABLE IF NOT EXISTS {prefix}waker_executions ( + execution_id TEXT PRIMARY KEY, + job_id TEXT NOT NULL, + job_name TEXT NOT NULL, + scheduled_for INTEGER NOT NULL, + status TEXT NOT NULL, + response_json TEXT, + claimed_at INTEGER NOT NULL, + completed_at INTEGER +); + +-- Cross-entry hourly tick claim: one row per claimed UTC hour, written by both +-- the native cron and the waker callback (schema_v3). +CREATE TABLE IF NOT EXISTS {prefix}scheduler_tick_claims ( + tick_key TEXT PRIMARY KEY, + source TEXT NOT NULL, + claimed_at INTEGER NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_{prefix}scheduler_tick_claims_claimed_at + ON {prefix}scheduler_tick_claims(claimed_at); diff --git a/worker/src/index.ts b/worker/src/index.ts index 6e65ae5..d0ec057 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -13,7 +13,9 @@ import { adminRoutes } from "./routes/admin"; import { adminBackupRoutes, meBackupRoutes } from "./routes/backup"; import { notifyRoutes } from "./routes/notify"; import { setupRoutes } from "./routes/setup"; -import { handleScheduled } from "./services/scheduler"; +import { wakerRoutes } from "./routes/waker"; +import { CALLBACK_MOUNT_PATH } from "./waker"; +import { runSchedulerTick } from "./services/scheduler-tick"; import { getAllSettings } from "./db/queries/settings"; import { isEmailConfigured } from "./services/email"; @@ -99,6 +101,12 @@ app.get("/api/system/info", async (c) => { } }); +// waker callback entry: the platform synchronously POSTs `/_waker/execute`. +// Registered **before** the SPA fallback so a callback can never be answered +// with 200 HTML; paths, signature checks, idempotency and error codes are the +// SDK's (an unconfigured key fails closed there with 500/400/404 JSON). +app.route(CALLBACK_MOUNT_PATH, wakerRoutes()); + // SPA fallback: serve static assets, fall back to index.html for client-side routing app.get("*", async (c) => { const res = await c.env.ASSETS.fetch(c.req.raw); @@ -108,7 +116,13 @@ app.get("*", async (c) => { export default { fetch: app.fetch, - async scheduled(_event: ScheduledEvent, env: Env, ctx: ExecutionContext) { - ctx.waitUntil(handleScheduled(env)); + // Native cron entry. Both entries share `runSchedulerTick` so one UTC hour is + // never swept twice (see services/scheduler-tick.ts); the business pass is + // still the unchanged `handleScheduled(env)`, awaited to completion. + async scheduled(event: ScheduledEvent, env: Env) { + await runSchedulerTick(env, { + source: "cron", + scheduledFor: event.scheduledTime, + }); }, }; diff --git a/worker/src/lib/migrations.ts b/worker/src/lib/migrations.ts index 5cb2c5c..860bb8e 100644 --- a/worker/src/lib/migrations.ts +++ b/worker/src/lib/migrations.ts @@ -145,6 +145,36 @@ const SCHEMA_V2 = `ALTER TABLE {prefix}notification_history ADD COLUMN trigger_s CREATE INDEX IF NOT EXISTS idx_{prefix}notification_history_filter ON {prefix}notification_history(user_id, channel, success, created_at)`; +/** + * schema_v3 — waker migration: the SDK executionId idempotency ledger and the + * cross-entry hourly tick claim. + * + * `waker_executions`: the eight columns are frozen verbatim from the SDK's + * `executionLedgerDdl()` (waker-client 2.0.0). It is inlined as literal SQL on + * purpose — a merged migration is never edited again, not even if the SDK DDL + * changes later. + * + * `scheduler_tick_claims`: one row per claimed UTC hour; both the native cron + * and the waker callback claim here first, so an hour is never swept twice. + */ +const SCHEMA_V3 = `CREATE TABLE IF NOT EXISTS {prefix}waker_executions ( + execution_id TEXT PRIMARY KEY, + job_id TEXT NOT NULL, + job_name TEXT NOT NULL, + scheduled_for INTEGER NOT NULL, + status TEXT NOT NULL, + response_json TEXT, + claimed_at INTEGER NOT NULL, + completed_at INTEGER +); +CREATE TABLE IF NOT EXISTS {prefix}scheduler_tick_claims ( + tick_key TEXT PRIMARY KEY, + source TEXT NOT NULL, + claimed_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_{prefix}scheduler_tick_claims_claimed_at + ON {prefix}scheduler_tick_claims(claimed_at)`; + export function getMigrations(prefix: string): Migration[] { return [ { @@ -155,5 +185,9 @@ export function getMigrations(prefix: string): Migration[] { name: "schema_v2", sql: SCHEMA_V2.replace(/\{prefix\}/g, prefix), }, + { + name: "schema_v3", + sql: SCHEMA_V3.replace(/\{prefix\}/g, prefix), + }, ]; } diff --git a/worker/src/routes/waker.ts b/worker/src/routes/waker.ts new file mode 100644 index 0000000..eeadab4 --- /dev/null +++ b/worker/src/routes/waker.ts @@ -0,0 +1,43 @@ +/** + * `/_waker` mount: hand the request to the SDK receiver. + * + * Mounted in `index.ts` **before** the SPA fallback (`app.get("*")`), so the + * fallback can never answer a callback with 200 HTML. Paths, signature + * verification, idempotency and error codes all come from the SDK; this file + * copies none of the protocol. + * + * Why per request: `env` (signing key secret, D1 binding, table prefix) is only + * visible per request, and the receiver resolves both the key and the ledger + * table from it. Building the receiver is object construction only — no IO. + */ + +import { Hono } from "hono"; +import type { HonoEnv } from "../types"; +import { createWakerCallbackReceiver } from "../services/waker-callback"; +import { CALLBACK_MOUNT_PATH } from "../waker"; + +/** + * The receiver registers its route relative to the mount prefix (`POST + * /execute`), so it must be attached through `app.route(prefix, receiver)`. + * A throwaway Hono host does exactly that (path stripping and the 404 for + * undeclared paths stay Hono's / the SDK's decisions — no hand-written + * forwarding logic). + */ +function forwardToReceiver( + request: Request, + env: HonoEnv["Bindings"], +): Response | Promise { + const host = new Hono(); + host.route( + CALLBACK_MOUNT_PATH, + createWakerCallbackReceiver(env) as unknown as Hono, + ); + return host.fetch(request, env); +} + +/** `/_waker` sub-app (`app.route(CALLBACK_MOUNT_PATH, wakerRoutes())` in index.ts). */ +export function wakerRoutes(): Hono { + const routes = new Hono(); + routes.all("*", (c) => forwardToReceiver(c.req.raw, c.env)); + return routes; +} diff --git a/worker/src/services/scheduler-tick.ts b/worker/src/services/scheduler-tick.ts new file mode 100644 index 0000000..bb2d6ee --- /dev/null +++ b/worker/src/services/scheduler-tick.ts @@ -0,0 +1,204 @@ +/** + * The single entry point both schedulers go through: native cron + * (`scheduled()` in `index.ts`) and the waker callback + * (`services/waker-callback.ts`). + * + * Business logic is untouched: `handleScheduled(env)` from + * `services/scheduler.ts` is still the only scan/push implementation. This + * module only adds the cross-entry guard in front of it: + * + * 1. claim the nominal hour slot (atomic D1 INSERT … ON CONFLICT DO NOTHING) + * 2. await the unchanged business pass + * 3. prune claims older than 7 days + * + * Failure semantics (frozen in the migration plan): + * + * | situation | cron | waker | + * |------------------------------------|---------------------------------|--------------------------| + * | claim statement fails, no key | log + run anyway (only one entry)| n/a | + * | claim statement fails, key present | log + do not run (safe) | throw → platform retries | + * | slot already claimed | do not run (debug log) | 2xx duplicate_tick | + * | business throws | keep claim, log, no re-run | release claim + throw | + * | business succeeds | keep claim | keep claim | + * + * The asymmetry is deliberate: cron has no retry, so re-running a failed hour + * would re-notify users it already handled; waker retries carry the same + * executionId, so releasing the claim resumes rather than duplicates. + */ + +import { getTablePrefix } from "../types"; +import type { Env } from "../types"; +import { + claimSchedulerTick, + getSchedulerTickClaim, + pruneSchedulerTicks, + releaseSchedulerTick, + schedulerTickClaimsTable, + schedulerTickKey, + wakerExecutionsTable, + type SchedulerTickSource, +} from "../db/queries/scheduler-ticks"; +import { handleScheduled } from "./scheduler"; + +export { schedulerTickClaimsTable, schedulerTickKey, wakerExecutionsTable }; +export type { SchedulerTickSource }; + +/** How long a claim row is kept; only needed to arbitrate near-live hours. */ +const CLAIM_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; + +/** + * The waker signing key, or `null` when the waker receiver is not configured. + * + * This is the **only** gate: `WAKER_SIGNING_KEY` present and usable ⇒ the waker + * entry exists; absent/blank/placeholder ⇒ native cron only. Empty values must + * never be mistaken for "configured", so `""`, whitespace, `undefined` and the + * `*_PLACEHOLDER` convention (same as `JWT_SECRET`) all mean "not configured". + * + * The trimmed value is what the receiver verifies with — gate and verification + * always see the same string. + */ +export function wakerSigningKey( + env: Pick, +): string | null { + const raw = env.WAKER_SIGNING_KEY; + if (typeof raw !== "string") return null; + const key = raw.trim(); + if (key.length === 0) return null; + if (key.endsWith("_PLACEHOLDER")) return null; + return key; +} + +export interface SchedulerTickOptions { + source: SchedulerTickSource; + /** Nominal scheduled time (epoch ms): cron `event.scheduledTime` / waker `ctx.scheduledFor`. */ + scheduledFor: number; +} + +export type SchedulerTickReason = + | "executed" + | "duplicate_tick" + | "claim_unavailable" + | "job_failed"; + +export interface SchedulerTickResult { + /** `true` only when this call ran the business pass to completion. */ + executed: boolean; + reason: SchedulerTickReason; + tickKey: string; + /** Which entry point claimed the hour (`duplicate_tick` only). */ + claimedBy?: string; + durationMs: number; +} + +/** Best-effort read of the winning claim, for the `claimedBy` field. */ +async function readClaimedBy( + env: Env, + prefix: string, + tickKey: string, +): Promise { + try { + const row = await getSchedulerTickClaim(env.DB, prefix, tickKey); + return row?.source; + } catch { + return undefined; + } +} + +export async function runSchedulerTick( + env: Env, + options: SchedulerTickOptions, +): Promise { + const startedAt = Date.now(); + const prefix = getTablePrefix(env); + const tickKey = schedulerTickKey(options.scheduledFor); + const source = options.source; + const wakerConfigured = wakerSigningKey(env) !== null; + + // 1) Claim the nominal hour slot. With only one entry point a claim failure + // must not break the existing schedule (e.g. migration not applied yet); + // with two possible entry points, running unclaimed could double-notify. + let claimed: boolean; + try { + claimed = await claimSchedulerTick( + env.DB, + prefix, + tickKey, + source, + startedAt, + ); + } catch (err) { + console.error( + `scheduler_tick_claim_unavailable (${source}, ${tickKey}):`, + err, + ); + if (wakerConfigured) { + if (source === "waker") throw err; + return { + executed: false, + reason: "claim_unavailable", + tickKey, + durationMs: Date.now() - startedAt, + }; + } + claimed = true; + } + + if (!claimed) { + const claimedBy = await readClaimedBy(env, prefix, tickKey); + console.debug( + `scheduler tick ${tickKey} already claimed by ${claimedBy ?? "another entry"}`, + ); + return { + executed: false, + reason: "duplicate_tick", + tickKey, + claimedBy, + durationMs: Date.now() - startedAt, + }; + } + + // 2) The unchanged business pass. Both entries await it to completion, so the + // waker callback only answers 2xx once notifications have actually gone out. + try { + await handleScheduled(env); + } catch (err) { + if (source === "waker") { + // Release the hour so the platform retry (same executionId) can re-claim. + try { + await releaseSchedulerTick(env.DB, prefix, tickKey, source); + } catch (releaseErr) { + console.error( + `scheduler_tick_release_failed (${tickKey}):`, + releaseErr, + ); + } + throw err; + } + console.error( + `scheduled run failed for ${tickKey}; keeping the claim for this hour:`, + err, + ); + return { + executed: false, + reason: "job_failed", + tickKey, + durationMs: Date.now() - startedAt, + }; + } + + // 3) Housekeeping: never let pruning failures affect the tick result. + try { + await pruneSchedulerTicks(env.DB, prefix, Date.now() - CLAIM_RETENTION_MS); + } catch (err) { + console.error(`scheduler_tick_prune_failed (${prefix}):`, err); + } + + const result: SchedulerTickResult = { + executed: true, + reason: "executed", + tickKey, + durationMs: Date.now() - startedAt, + }; + console.info("scheduler tick:", { source, ...result }); + return result; +} diff --git a/worker/src/services/waker-callback.ts b/worker/src/services/waker-callback.ts new file mode 100644 index 0000000..15f7e9c --- /dev/null +++ b/worker/src/services/waker-callback.ts @@ -0,0 +1,75 @@ +/** + * Waker callback business side: platform POST `/_waker/execute` → one hourly + * sweep → JSON result. + * + * Frozen contract (migration plan §10): + * - **synchronous**: the handler awaits `runSchedulerTick` and only then + * returns, so the SDK answers 2xx after the business pass finished. Never + * `waitUntil` + immediate OK. + * - **signature**: HMAC-SHA256 over `timestamp + executionId + jobId + rawBody` + * with a 300s window — entirely inside the SDK (`../waker`, a verbatim copy + * of waker-client 2.0.0). This file never touches signatures. + * - **idempotency**: executionId is deduplicated by the SDK's D1 ledger + * (`{prefix}waker_executions`, created by `schema_v3`). The cross-entry + * hour claim in `runSchedulerTick` is the second, independent guard so the + * native cron and this callback can never both sweep the same hour. + * - payload / misfire / attempt are ignored for business purposes: a misfire + * replay is semantically identical to a normal run and dedupes on the + * nominal hour slot. + */ + +import { getTablePrefix } from "../types"; +import type { Env } from "../types"; +import { createD1ExecutionLedger, createWakerReceiver } from "../waker"; +import { + runSchedulerTick, + wakerExecutionsTable, + wakerSigningKey, +} from "./scheduler-tick"; + +/** + * Job name registered in the waker console. Must match the platform job name + * **verbatim** — the receiver dispatches on it and answers 404 `unknown_job` + * otherwise. Task creation is done by the user in the waker console; eNotify + * ships no registration client and holds no project token. + */ +export const WAKER_JOB_NAME = "hourly-reminder-sweep"; + +/** + * Build a receiver bound to this request's env. + * + * The signing key is resolved once here: the same resolved value gates + * "configured or not" and is what the SDK verifies signatures with. When it is + * `null` the receiver still mounts and fails closed by itself (500 + * `signing_key_missing` for a real callback, 400 for missing headers, 404 for + * GET) without touching the DB or the business code. + */ +export function createWakerCallbackReceiver(env: Env) { + const signingKey = wakerSigningKey(env); + const prefix = getTablePrefix(env); + const table = wakerExecutionsTable(prefix); + + return createWakerReceiver({ + jobs: { + [WAKER_JOB_NAME]: async (context) => { + // `scheduledFor` is the platform's nominal slot (not the dispatch time), + // which is what maps a waker misfire replay onto the native cron slot. + const result = await runSchedulerTick(env, { + source: "waker", + scheduledFor: context.scheduledFor, + }); + return { ...result }; + }, + }, + // Gate and verification share one value; null → SDK fail-closed path. + signingKey: () => signingKey, + ledger: createD1ExecutionLedger(env.DB, { table }), + onJobError: (error, context) => { + // Only identifiers and the message: never the payload, headers or key. + console.error( + `waker job ${context.jobName} (execution ${context.executionId}, attempt ${context.attempt}) failed:`, + error instanceof Error ? error.message : String(error), + ); + }, + }); +} diff --git a/worker/src/types.ts b/worker/src/types.ts index af70165..3684480 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -3,6 +3,15 @@ export interface Env { KV: KVNamespace; JWT_SECRET: string; SETUP_SECRET: string; + /** + * Waker callback signing key. Injected only from GitHub Secrets through + * `wrangler deploy --secrets-file`. + * + * Missing / blank / whitespace-only / `*_PLACEHOLDER` all mean "not + * configured" → native cron only; the receiver stays mounted but fails closed. + * See `wakerSigningKey()` in `services/scheduler-tick.ts` (the only gate). + */ + WAKER_SIGNING_KEY?: string; /** * Table prefix, three states: * - undefined/null (unset) → DEFAULT_TABLE_PREFIX ("enotify"), normalized to "enotify_" diff --git a/worker/src/waker/README.md b/worker/src/waker/README.md new file mode 100644 index 0000000..2b17081 --- /dev/null +++ b/worker/src/waker/README.md @@ -0,0 +1,26 @@ +# worker/src/waker —— waker 客户端 SDK(**外部源码拷贝,勿改**) + +本目录是 waker 官方客户端 SDK 的**逐字拷贝**,不是 eNotify 自己的实现: + +| 项 | 值 | +|---|---| +| 来源 | https://github.com/WorkerHub/waker 的 `client/src/` | +| 版本 | `@workerhub/waker-client` 2.0.0(commit `2b1eb68`,2026-10-27) | +| 接入方式 | SDK README 指定的「把 `client/src` 拷进下游项目(如 `src/waker/`)」 | +| 依赖 | 唯一 peer 是 `hono`(`^4.13.14`),不 import waker 平台内部任何模块 | + +七个文件与上游一一对应:`protocol.ts` / `verify.ts` / `ledger.ts` / `receiver.ts` / `client.ts` / `modes.ts` / `index.ts`。 + +**规则** + +1. 本目录内任何文件都**不得手改**:需要修 SDK 就回 waker 仓库改、发版,再整目录重新拷贝 + (`cp client/src/*.ts enotify/worker/src/waker/`),并把上面表格的版本与 commit 一起更新。 +2. 升级时必须对照 waker 的冻结契约测试(`tests/client.test.ts` 断言 SDK 与平台逐项一致)确认版本; + 协议常量(签名规范串、头名、时间窗、`/_waker` 路径)漂移会让回调静默失败。 +3. eNotify 侧**只用** receiver(`createWakerReceiver`)、D1 幂等账本(`createD1ExecutionLedger`) + 与路径常量(`CALLBACK_MOUNT_PATH` / `CALLBACK_PATH`);`executionLedgerDdl()` 仅作建表参照。 + 业务接线在 `worker/src/services/waker-callback.ts`,挂载在 `worker/src/routes/waker.ts`。 +4. **永不调用**:`mountWakerReceiver`(被已废弃的 `WAKER_MODE` 门控,且缺 key 时模块初始化即抛错)、 + `createWakerClient*` / `syncManifest` / `createOneShot` / `cancelJob`(不配项目令牌、不做动态注册/ + 取消/自续)、`resolveWakerMode` / `isWakerEnabled`(模式判定已废弃:开关只看 `WAKER_SIGNING_KEY` + 在不在,见 `wakerSigningKey()`)。这些文件随目录拷入只为保持逐字一致。 diff --git a/worker/src/waker/client.ts b/worker/src/waker/client.ts new file mode 100644 index 0000000..bdc455e --- /dev/null +++ b/worker/src/waker/client.ts @@ -0,0 +1,322 @@ +import { + WAKER_TOKEN_ENV, + WAKER_URL_ENV, + isWakerEnabled, + readEnvString, + type WakerEnvLike, +} from './modes' +import type { JsonValue } from './protocol' +import { CALLBACK_PROTOCOL_VERSION } from './protocol' + +/** + * 注册客户端:调 B4 冻结的注册 API(`/v1/*`,项目令牌鉴权)。 + * + * 覆盖下游真正需要的五件事: + * - `whoami()` 令牌自检(CI / 启动期 sanity check) + * - `syncManifest()` 部署期声明式任务同步 + 对账(幂等) + * - `createOneShot()` 运行时创建一次性任务(`runAt` 毫秒 / ISO / Date) + * - `cancelJob()` 取消 one-shot(幂等) + * - `listJobs()` 本项目任务列表(分页游标同平台契约) + * + * 传输层全部用原生:`fetch` + `AbortSignal.timeout`,不自研重试/超时。平台不可达时的重试 + * 交给调用方(部署期 CI 重跑、运行时业务自己兜底),客户端不隐藏失败。 + * + * 项目身份**只来自令牌**:请求体里不带 `projectId`(平台也会拒绝不一致的写法)。 + */ + +export type WakerJobKind = 'cron' | 'one_shot' +export type WakerJobStatus = 'active' | 'paused' | 'cancelled' | 'completed' +export type WakerMisfirePolicy = 'fire_once' | 'skip' | 'fire_all' +export type WakerConcurrencyPolicy = 'forbid' | 'allow' + +/** 任务策略字段(与平台 `JobPolicies` 一致;未传字段取平台默认值)。 */ +export interface WakerJobPolicies { + misfire: WakerMisfirePolicy + concurrency: WakerConcurrencyPolicy + maxRetries: number + backoffSeconds: number + timeoutSeconds: number + jitterSeconds: number +} + +/** 任务视图(与平台 `JobView` 一致)。 */ +export interface WakerJobView { + id: string + projectId: string + name: string + kind: WakerJobKind + cron: string | null + cronNormalized: string | null + timezone: string + runAt: number | null + payload: JsonValue + policies: WakerJobPolicies + status: WakerJobStatus + nextRunAt: number | null + lastRunAt: number | null + createdAt: number + updatedAt: number +} + +/** 创建任务入参(= `CreateJobInput` 去掉 `projectId`:项目由令牌决定)。 */ +export interface CreateWakerJobInput { + name: string + kind: WakerJobKind + /** `kind: 'cron'` 必填:CF 官方方言 5 字段表达式。 */ + cron?: string + /** `kind: 'one_shot'` 必填:epoch ms 或 ISO 8601 字符串。 */ + runAt?: number | string + timezone?: string + payload?: JsonValue + policies?: Partial + enabled?: boolean +} + +/** 运行时创建一次性任务:`runAt` 额外接受 `Date`(内部转 epoch ms)。 */ +export interface CreateOneShotInput { + name: string + runAt: number | string | Date + timezone?: string + payload?: JsonValue + policies?: Partial + /** false = 创建后先暂停。默认 true。 */ + enabled?: boolean +} + +/** 声明式清单里的一条任务(与平台 `ManifestJobInput` 一致,只支持 cron)。 */ +export interface WakerManifestJob { + name: string + cron: string + timezone?: string + payload?: JsonValue + policies?: Partial + enabled?: boolean +} + +/** 清单对账结果(与平台 `SyncManifestResult` 一致)。 */ +export interface WakerManifestSyncResult { + projectId: string + created: string[] + updated: string[] + unchanged: string[] + paused: string[] + jobs: WakerJobView[] +} + +export interface WakerJobListResult { + jobs: WakerJobView[] + nextCursor: string | null +} + +export interface WakerJobListQuery { + status?: WakerJobStatus + kind?: WakerJobKind + limit?: number + cursor?: string | null +} + +export interface WakerProjectIdentity { + id: string + name: string +} + +/** + * 平台返回的错误(`{ error: { code, message, details? } }`)。 + * + * `code` 是冻结契约里的稳定错误码(`unauthorized` / `invalid_cron` / `job_not_found` / …), + * 调用方按 `code` 分支,不解析文案、不按状态码猜原因。 + */ +export class WakerApiError extends Error { + readonly status: number + readonly code: string + readonly details: unknown + + constructor(input: { status: number; code: string; message: string; details?: unknown }) { + super(`[${input.status} ${input.code}] ${input.message}`) + this.name = 'WakerApiError' + this.status = input.status + this.code = input.code + this.details = input.details ?? null + } +} + +export interface WakerClientOptions { + /** 平台根地址,如 `https://waker.oneboy.app`(不带 `/v1`)。 */ + baseUrl: string + /** 项目令牌(`Authorization: Bearer <项目令牌>`)。只从 secrets 注入。 */ + token: string + /** 注入 fetch(测试 / 特殊运行时)。 */ + fetch?: typeof fetch + /** 单次请求超时(毫秒),默认 10s。 */ + timeoutMs?: number +} + +export interface WakerClient { + whoami(): Promise + listJobs(query?: WakerJobListQuery): Promise + createJob(input: CreateWakerJobInput): Promise + createOneShot(input: CreateOneShotInput): Promise + cancelJob(name: string): Promise + syncManifest(jobs: WakerManifestJob[]): Promise +} + +interface ErrorEnvelope { + error?: { code?: unknown; message?: unknown; details?: unknown } +} + +function normalizeRunAt(runAt: number | string | Date): number | string { + return runAt instanceof Date ? runAt.getTime() : runAt +} + +function safeJson(text: string): unknown { + try { + return JSON.parse(text) + } catch { + return null + } +} + +/** + * 建一个注册客户端。 + * + * ```ts + * const waker = createWakerClient({ baseUrl: env.WAKER_URL, token: env.WAKER_TOKEN }) + * await waker.createOneShot({ name: `letter-${letter.id}`, runAt: deliverAt, payload: { letterId } }) + * ``` + */ +export function createWakerClient(options: WakerClientOptions): WakerClient { + const baseUrl = options.baseUrl.trim().replace(/\/+$/, '') + if (baseUrl.length === 0) throw new Error('createWakerClient: baseUrl 不能为空') + if (options.token.trim().length === 0) throw new Error('createWakerClient: token 不能为空') + + const fetchImpl = options.fetch ?? fetch + const timeoutMs = options.timeoutMs ?? 10_000 + + async function request( + path: string, + init: { method?: string; body?: unknown } = {}, + ): Promise { + const headers: Record = { + authorization: `Bearer ${options.token}`, + accept: 'application/json', + 'user-agent': `waker-sdk/${CALLBACK_PROTOCOL_VERSION}`, + } + if (init.body !== undefined) headers['content-type'] = 'application/json' + + const response = await fetchImpl(`${baseUrl}${path}`, { + method: init.method ?? 'GET', + headers, + ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }), + signal: AbortSignal.timeout(Math.max(1, timeoutMs)), + }) + + const text = await response.text() + const payload: unknown = text.length === 0 ? null : safeJson(text) + + if (!response.ok) { + const envelope = (payload ?? {}) as ErrorEnvelope + throw new WakerApiError({ + status: response.status, + code: typeof envelope.error?.code === 'string' ? envelope.error.code : `http_${response.status}`, + message: typeof envelope.error?.message === 'string' ? envelope.error.message : text.slice(0, 500), + details: envelope.error?.details, + }) + } + + return payload as T + } + + return { + async whoami() { + const result = await request<{ project: WakerProjectIdentity }>('/v1/whoami') + return result.project + }, + + async listJobs(query = {}) { + const search = new URLSearchParams() + if (query.status !== undefined) search.set('status', query.status) + if (query.kind !== undefined) search.set('kind', query.kind) + if (query.limit !== undefined) search.set('limit', String(query.limit)) + if (query.cursor !== undefined && query.cursor !== null) search.set('cursor', query.cursor) + const suffix = search.size === 0 ? '' : `?${search.toString()}` + return request(`/v1/jobs${suffix}`) + }, + + async createJob(input) { + const result = await request<{ job: WakerJobView }>('/v1/jobs', { + method: 'POST', + body: input, + }) + return result.job + }, + + async createOneShot(input) { + const body: CreateWakerJobInput = { + name: input.name, + kind: 'one_shot', + runAt: normalizeRunAt(input.runAt), + ...(input.timezone === undefined ? {} : { timezone: input.timezone }), + ...(input.payload === undefined ? {} : { payload: input.payload }), + ...(input.policies === undefined ? {} : { policies: input.policies }), + ...(input.enabled === undefined ? {} : { enabled: input.enabled }), + } + const result = await request<{ job: WakerJobView }>('/v1/jobs', { method: 'POST', body }) + return result.job + }, + + async cancelJob(name) { + const result = await request<{ job: WakerJobView }>( + `/v1/jobs/${encodeURIComponent(name)}`, + { method: 'DELETE' }, + ) + return result.job + }, + + async syncManifest(jobs) { + return request('/v1/manifest', { + method: 'PUT', + body: { jobs }, + }) + }, + } +} + +export interface CreateWakerClientFromEnvOptions { + fetch?: typeof fetch + timeoutMs?: number + /** `true` = 已启用 waker 但 `WAKER_URL` / `WAKER_TOKEN` 缺失时抛错(部署期 fail fast)。 */ + required?: boolean +} + +/** + * 可选接入的客户端入口:**只有 `WAKER_MODE=waker` 时才构造客户端**。 + * + * - 原生模式(缺省):返回 `null` —— 不构造、不读令牌、不发请求; + * - waker 模式但 `WAKER_URL` / `WAKER_TOKEN` 缺失:默认也返回 `null`(等同未启用), + * 传 `required: true` 则抛错,用于部署期自检。 + */ +export function createWakerClientFromEnv( + env: WakerEnvLike, + options: CreateWakerClientFromEnvOptions = {}, +): WakerClient | null { + if (!isWakerEnabled(env)) return null + + const baseUrl = readEnvString(env, WAKER_URL_ENV) + const token = readEnvString(env, WAKER_TOKEN_ENV) + if (baseUrl === null || token === null) { + if (options.required === true) { + throw new Error( + `WAKER_MODE=waker 但 ${WAKER_URL_ENV} / ${WAKER_TOKEN_ENV} 未配置:` + + '请把平台根地址写进 [vars]、项目令牌用 `wrangler secret put` 注入。', + ) + } + return null + } + + return createWakerClient({ + baseUrl, + token, + ...(options.fetch === undefined ? {} : { fetch: options.fetch }), + ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }), + }) +} diff --git a/worker/src/waker/index.ts b/worker/src/waker/index.ts new file mode 100644 index 0000000..928d304 --- /dev/null +++ b/worker/src/waker/index.ts @@ -0,0 +1,18 @@ +/** + * waker 客户端 SDK 出口。 + * + * 对齐三份冻结契约: + * - 回调协议 v2(B3)→ `./protocol` / `./verify` / `./receiver` + * - 注册 API(B4)→ `./client` + * - CF Cron Triggers 方言(B2)→ 声明式任务的 `cron` 字符串原样透传(SDK 不自行解析, + * 校验由平台侧同一份方言解析器负责;SDK 只保证逐字不改地送达) + * + * 可选接入(双模式):`./modes` 提供模式判定,receiver 与注册客户端都只在 + * `WAKER_MODE=waker` 时接线;原生 `scheduled()` 路径 SDK 从不接管。 + */ +export * from './protocol' +export * from './verify' +export * from './ledger' +export * from './receiver' +export * from './client' +export * from './modes' diff --git a/worker/src/waker/ledger.ts b/worker/src/waker/ledger.ts new file mode 100644 index 0000000..44cfdd1 --- /dev/null +++ b/worker/src/waker/ledger.ts @@ -0,0 +1,236 @@ +/** + * executionId 幂等落表 helper(对齐 B3 冻结契约的「`executionId` 随回调下发,下游落表去重」)。 + * + * 语义: + * - 平台重试同一次执行时带**同一个** `executionId`,下游必须只跑一次业务; + * - 首次投递 → `claim` 成功 → 跑业务 → `complete`; + * - 业务失败 → `release`(把占位删掉,让平台的重试能真正重跑); + * - 重复投递 → `claim` 失败 → 直接回 2xx(幂等成功),必要时带上首次的响应体 + * (这样自续的 `nextRunAt` 在重试时也不会丢)。 + * + * 存储用原生能力表达,不自研分布式锁: + * - D1:`INSERT ... ON CONFLICT(execution_id) DO NOTHING` + `meta.changes` 判定,原子且无竞争; + * - 内存:单 isolate 的 `Map`(只用于本地开发 / 测试,Worker 多 isolate 下不保证跨实例去重)。 + */ + +/** 下游本地记录的一条执行。 */ +export interface ExecutionLedgerEntry { + executionId: string + jobId: string + jobName: string + /** 名义到期时刻(epoch ms)。 */ + scheduledFor: number + status: 'claimed' | 'succeeded' + /** 首次成功时的响应体(重复投递时原样回放,保住 `nextRunAt`)。 */ + response: Record | null + claimedAt: number + completedAt: number | null +} + +/** 认领结果:`claimed` = 本次真的跑;`claimed: false` = 已经处理过(幂等命中)。 */ +export interface ExecutionLedgerClaim { + claimed: boolean + /** 已存在的记录(`claimed: false` 时非空;`claimed: true` 时为 null)。 */ + existing: ExecutionLedgerEntry | null +} + +export interface ExecutionLedger { + /** 认领一次执行(原子「插入或忽略」)。 */ + claim(input: { + executionId: string + jobId: string + jobName: string + scheduledFor: number + }): Promise + /** 标记成功并保存响应体(重复投递时回放)。 */ + complete(executionId: string, response: Record | null): Promise + /** 释放占位(业务失败时调用,让重试能重跑)。 */ + release(executionId: string): Promise + /** 读一条记录(幂等命中时回放响应 / 排查用)。 */ + get(executionId: string): Promise +} + +export interface ExecutionLedgerOptions { + /** 过期占位的接管时限(秒):超过它就认为上次执行已崩溃,允许重新认领。默认 600s。 */ + staleClaimSeconds?: number + /** 注入时钟(测试可替换),默认 `Date.now`。 */ + now?: () => number +} + +const DEFAULT_STALE_CLAIM_SECONDS = 600 + +/** D1 的最小结构接口:只用 `prepare().bind().run()/first()`,不引入 `@cloudflare/workers-types`。 */ +export interface D1RunResult { + success?: boolean + meta?: { changes?: number; last_row_id?: number; changed_db?: boolean } +} + +export interface D1StatementLike { + bind(...values: unknown[]): D1StatementLike + run(): Promise + first(): Promise +} + +export interface D1DatabaseLike { + prepare(sql: string): D1StatementLike +} + +/** 幂等表 DDL(下游自己跑一次迁移;表名可用 `table` 选项改写)。 */ +export function executionLedgerDdl(table = 'waker_executions'): string { + return `CREATE TABLE IF NOT EXISTS ${table} ( + execution_id TEXT PRIMARY KEY, + job_id TEXT NOT NULL, + job_name TEXT NOT NULL, + scheduled_for INTEGER NOT NULL, + status TEXT NOT NULL, + response_json TEXT, + claimed_at INTEGER NOT NULL, + completed_at INTEGER +);` +} + +/** 内存实现:本地开发 / 测试用(单 isolate 有效)。 */ +export function createMemoryExecutionLedger( + options: ExecutionLedgerOptions = {}, +): ExecutionLedger { + const now = options.now ?? Date.now + const staleMs = (options.staleClaimSeconds ?? DEFAULT_STALE_CLAIM_SECONDS) * 1000 + const entries = new Map() + + return { + async claim(input) { + const existing = entries.get(input.executionId) + if (existing === undefined) { + entries.set(input.executionId, { + ...input, + status: 'claimed', + response: null, + claimedAt: now(), + completedAt: null, + }) + return { claimed: true, existing: null } + } + // 上次认领后进程崩了(占位一直没释放):超时允许接管,避免这条执行永远被当成「已处理」。 + if (existing.status === 'claimed' && now() - existing.claimedAt > staleMs) { + entries.set(input.executionId, { ...existing, claimedAt: now() }) + return { claimed: true, existing: null } + } + return { claimed: false, existing: { ...existing } } + }, + async complete(executionId, response) { + const existing = entries.get(executionId) + if (existing === undefined) return + entries.set(executionId, { + ...existing, + status: 'succeeded', + response, + completedAt: now(), + }) + }, + async release(executionId) { + const existing = entries.get(executionId) + if (existing !== undefined && existing.status === 'claimed') entries.delete(executionId) + }, + async get(executionId) { + const existing = entries.get(executionId) + return existing === undefined ? null : { ...existing } + }, + } +} + +interface LedgerRow { + execution_id: string + job_id: string + job_name: string + scheduled_for: number + status: string + response_json: string | null + claimed_at: number + completed_at: number | null +} + +function rowToEntry(row: LedgerRow): ExecutionLedgerEntry { + return { + executionId: row.execution_id, + jobId: row.job_id, + jobName: row.job_name, + scheduledFor: row.scheduled_for, + status: row.status === 'succeeded' ? 'succeeded' : 'claimed', + response: row.response_json === null ? null : (JSON.parse(row.response_json) as Record), + claimedAt: row.claimed_at, + completedAt: row.completed_at, + } +} + +/** + * D1 实现(下游项目自己的库,与平台的 WakerDO SQLite 无关)。 + * + * 认领的原子性交给 SQLite 的 `ON CONFLICT DO NOTHING` + `meta.changes`,不做「先查后写」。 + */ +export function createD1ExecutionLedger( + db: D1DatabaseLike, + options: ExecutionLedgerOptions & { table?: string } = {}, +): ExecutionLedger { + const now = options.now ?? Date.now + const table = options.table ?? 'waker_executions' + const staleMs = (options.staleClaimSeconds ?? DEFAULT_STALE_CLAIM_SECONDS) * 1000 + + async function readEntry(executionId: string): Promise { + const row = await db + .prepare(`SELECT * FROM ${table} WHERE execution_id = ?`) + .bind(executionId) + .first() + return row === null ? null : rowToEntry(row) + } + + return { + async claim(input) { + const claimedAt = now() + const insert = await db + .prepare( + `INSERT INTO ${table} (execution_id, job_id, job_name, scheduled_for, status, response_json, claimed_at, completed_at) + VALUES (?, ?, ?, ?, 'claimed', NULL, ?, NULL) + ON CONFLICT(execution_id) DO NOTHING`, + ) + .bind( + input.executionId, + input.jobId, + input.jobName, + input.scheduledFor, + claimedAt, + ) + .run() + + if ((insert.meta?.changes ?? 0) > 0) return { claimed: true, existing: null } + + // 已有记录:succeeded = 真正的重复投递;claimed 且超时 = 上次执行崩了,接管。 + const existing = await readEntry(input.executionId) + if (existing !== null && existing.status === 'claimed' && claimedAt - existing.claimedAt > staleMs) { + const takeover = await db + .prepare( + `UPDATE ${table} SET claimed_at = ? WHERE execution_id = ? AND status = 'claimed' AND claimed_at = ?`, + ) + .bind(claimedAt, input.executionId, existing.claimedAt) + .run() + if ((takeover.meta?.changes ?? 0) > 0) return { claimed: true, existing: null } + } + + return { claimed: false, existing } + }, + async complete(executionId, response) { + await db + .prepare( + `UPDATE ${table} SET status = 'succeeded', response_json = ?, completed_at = ? WHERE execution_id = ?`, + ) + .bind(response === null ? null : JSON.stringify(response), now(), executionId) + .run() + }, + async release(executionId) { + await db + .prepare(`DELETE FROM ${table} WHERE execution_id = ? AND status = 'claimed'`) + .bind(executionId) + .run() + }, + get: readEntry, + } +} diff --git a/worker/src/waker/modes.ts b/worker/src/waker/modes.ts new file mode 100644 index 0000000..1723295 --- /dev/null +++ b/worker/src/waker/modes.ts @@ -0,0 +1,61 @@ +/** + * 双模式(可选接入)—— 父单规格补充二(2026-10-26,SPEC §0/§5/§9)。 + * + * 下游项目默认走**原生 CF Cron Trigger**(`WAKER_MODE=cron`,缺省值), + * 想改用平台调度时把它切成 `WAKER_MODE=waker` 并注入 `WAKER_URL` + 项目令牌 + signing key。 + * + * 「可选接入」在 SDK 层面落到三件事上: + * 1. **默认关闭**:`WAKER_MODE` 缺失 / 取值不认识 → 一律按 `cron`(原生模式)处理, + * 下游不需要为了「不启用」写任何额外代码; + * 2. **不加载**:`cron` 模式下 receiver 不挂载、注册客户端不构造(见 + * {@link mountWakerReceiver} / `createWakerClientFromEnv` 返回 null), + * 参考示例进一步用动态 `import()` 保证 SDK 模块在原生模式下**连求值都不发生**; + * 3. **原生 scheduled() 不受影响**:模式只影响 HTTP 侧的接线,`scheduled()` 是下游自己的 + * 代码路径,SDK 从不接管它。 + */ + +/** 两种模式:原生 CF Cron Trigger(默认) / waker 回调。 */ +export type WakerMode = 'cron' | 'waker' + +/** 模式开关的环境变量名(部署期由 wrangler `[vars]` 或 secrets 注入)。 */ +export const WAKER_MODE_ENV = 'WAKER_MODE' + +/** 平台地址(waker 模式下 SDK 调注册 API 用)。 */ +export const WAKER_URL_ENV = 'WAKER_URL' + +/** 项目令牌(注册 API 鉴权用;只从 secrets 注入,绝不进仓库)。 */ +export const WAKER_TOKEN_ENV = 'WAKER_TOKEN' + +/** 项目 signing key(回调验签用;只从 secrets 注入)。 */ +export const WAKER_SIGNING_KEY_ENV = 'WAKER_SIGNING_KEY' + +export const WAKER_MODE_CRON: WakerMode = 'cron' +export const WAKER_MODE_WAKER: WakerMode = 'waker' + +/** 最小 env 外形:只要可读的键值表,不绑定任何框架泛型。 */ +export type WakerEnvLike = Record | null | undefined + +/** + * 解析当前模式。 + * + * 未知取值按 `cron` 处理(**不是**抛错也不是猜成 waker):可选接入的默认必须是「不动下游」, + * 部署期写错变量最多是「没启用」,不会出现「悄悄改成回调模式却没配密钥」的半死状态。 + */ +export function resolveWakerMode(env: WakerEnvLike): WakerMode { + const raw = env?.[WAKER_MODE_ENV] + if (typeof raw !== 'string') return WAKER_MODE_CRON + return raw.trim().toLowerCase() === WAKER_MODE_WAKER ? WAKER_MODE_WAKER : WAKER_MODE_CRON +} + +/** 是否启用 waker(= 模式为 `waker`)。 */ +export function isWakerEnabled(env: WakerEnvLike): boolean { + return resolveWakerMode(env) === WAKER_MODE_WAKER +} + +/** 从 env 里取一个非空字符串(缺失 / 空白 → null)。 */ +export function readEnvString(env: WakerEnvLike, key: string): string | null { + const raw = env?.[key] + if (typeof raw !== 'string') return null + const trimmed = raw.trim() + return trimmed.length === 0 ? null : trimmed +} diff --git a/worker/src/waker/protocol.ts b/worker/src/waker/protocol.ts new file mode 100644 index 0000000..a2f31b0 --- /dev/null +++ b/worker/src/waker/protocol.ts @@ -0,0 +1,137 @@ +/** + * 回调协议 v2 —— **SDK 侧副本**,与平台 `src/callback/protocol.ts` 逐字对齐。 + * + * 为什么是副本而不是 `import '../../src/callback/protocol'`:SDK 要能被下游项目**整目录拷走** + * (下游仓库看不到本仓的 `src/`),因此 client 只依赖 `hono` + Workers 运行时原生能力, + * 不 import 平台内部任何模块。副本与冻结契约的一致性由 `tests/client-contract.test.ts` + * 逐项断言(常量 / 头名 / 签名规范串 / 请求响应结构都对比),漂移会直接测试失败。 + * + * 协议语义见父单 SPEC §4(B3 冻结): + * - 下游以 Hono 路由挂载 `/_waker`,平台同步 POST `/_waker/execute`; + * - handler 必须 await 到业务完成才回 2xx(平台以 2xx 判成功,非 2xx 走重试/死信); + * - 每项目独立 signing key,HMAC-SHA256 覆盖 `timestamp + executionId + jobId + body`,带时间窗防重放; + * - `executionId` 随回调下发,下游落表去重; + * - one-shot 执行的回调响应可携带 `nextRunAt` 自续。 + */ + +/** 协议版本号:写进请求体的 `protocolVersion`,也是签名头的前缀(`v2=`)。 */ +export const CALLBACK_PROTOCOL_VERSION = 2 + +/** 下游挂载前缀:`app.route('/_waker', createWakerReceiver({ jobs }))`。 */ +export const CALLBACK_MOUNT_PATH = '/_waker' + +/** 回调 endpoint:平台投递的完整路径(= 挂载前缀 + `/execute`)。 */ +export const CALLBACK_PATH = '/_waker/execute' + +/** 回调签名算法(写进契约,便于日后轮换)。 */ +export const CALLBACK_SIGNATURE_ALGORITHM = 'HMAC-SHA256' + +/** 时间窗(秒):`|now - X-Waker-Timestamp| > 300` 视为重放/过期请求,下游必须拒收。 */ +export const CALLBACK_TIMESTAMP_TOLERANCE_SECONDS = 300 + +/** 自续上限(毫秒):`nextRunAt` 最远只能落在「本次执行时刻 + 366 天」之内。 */ +export const MAX_SELF_RENEWAL_HORIZON_MS = 366 * 24 * 60 * 60 * 1000 + +/** HTTP 头名(冻结):下游按这些名字取签名材料。 */ +export const CALLBACK_HEADERS = { + /** epoch **秒**(十进制字符串),参与签名。 */ + timestamp: 'X-Waker-Timestamp', + /** 本次执行 id(= 下游幂等键),参与签名。 */ + executionId: 'X-Waker-Execution-Id', + /** 任务 id,参与签名。 */ + jobId: 'X-Waker-Job-Id', + /** 项目 id,便于下游快速路由/排查;不参与签名(已在 body 里)。 */ + projectId: 'X-Waker-Project-Id', + /** 第几次投递(0 = 首次),便于排查;不参与签名(已在 body 里)。 */ + attempt: 'X-Waker-Attempt', + /** `v2=<小写 hex>`,参与签名校验。 */ + signature: 'X-Waker-Signature', + /** 协议版本,便于下游做灰度。 */ + protocolVersion: 'X-Waker-Protocol-Version', +} as const + +/** 签名头前缀:`v2=`。 */ +export const CALLBACK_SIGNATURE_PREFIX = `v${CALLBACK_PROTOCOL_VERSION}=` + +/** 任务两类型(与平台 `JobKind` 一致)。 */ +export type JobKind = 'cron' | 'one_shot' + +/** 触发来源(与平台 `ExecutionTrigger` 一致)。 */ +export type ExecutionTrigger = 'schedule' | 'manual' + +/** 不透明载荷(平台不解析,原样透传)。 */ +export type JsonValue = + | string + | number + | boolean + | null + | JsonValue[] + | { [key: string]: JsonValue } + +/** + * 签名规范串(**冻结**,逐字节照此拼接): + * + * ``` + * \n\n\n + * ``` + * + * - `timestamp` = `X-Waker-Timestamp` 头里的原始十进制字符串(不做数值归一); + * - `rawBody` = 请求体**原始字节按 UTF-8 解码后的字符串**(必须用未解析的 body, + * `JSON.stringify(JSON.parse(body))` 会改键序/空白,签名必然不匹配)。 + */ +export function buildSignaturePayload(input: { + timestamp: string + executionId: string + jobId: string + body: string +}): string { + return `${input.timestamp}\n${input.executionId}\n${input.jobId}\n${input.body}` +} + +/** 回调请求体(冻结结构):平台 POST 给下游 `/_waker/execute` 的 JSON。 */ +export interface CallbackRequestBody { + /** 协议版本,恒为 2。 */ + protocolVersion: typeof CALLBACK_PROTOCOL_VERSION + /** 执行 id:下游幂等键(同一次执行的重试会带同一个 executionId)。 */ + executionId: string + /** 任务 id(同一 job 的多次执行共享,自续后仍是同一个 job id)。 */ + jobId: string + projectId: string + /** 任务名(= 下游 jobs 表里的 key,下游据此分发到业务 handler)。 */ + jobName: string + kind: JobKind + trigger: ExecutionTrigger + /** 是否补跑(错过窗口后按 misfirePolicy 补的那一次)。 */ + misfire: boolean + /** 第几次投递,0 = 首次。 */ + attempt: number + /** 名义到期时刻(epoch ms)。 */ + scheduledFor: number + /** 本次实际上报时刻(epoch ms,含抖动)。 */ + dispatchedAt: number + /** 平台侧超时(秒):下游应在此之前返回,否则请求会被 abort 并按失败重试。 */ + timeoutSeconds: number + /** 任务载荷(不透明 JSON,平台不解析,原样透传)。 */ + payload: JsonValue +} + +/** 自续时刻:epoch 毫秒数字或 ISO 8601 字符串。 */ +export type NextRunAt = number | string + +/** 回调响应体(冻结):2xx + JSON 即视为成功执行;只有 one-shot 会看 `nextRunAt`。 */ +export interface CallbackResponseBody { + /** + * 自续的下一次执行时刻。平台校验(合法时间戳 / 严格晚于本次执行时刻 / 不超过 366 天上限) + * 通过后以同一 job 系列续期;校验失败不影响本次执行成功,只在执行记录里留 `renewal_error`。 + */ + nextRunAt?: NextRunAt | null + /** 平台忽略的其它字段(下游可自由返回业务信息)。 */ + [key: string]: unknown +} + +/** 把项目根地址规范化为完整回调地址(平台侧同款实现:契约在这里是对称的)。 */ +export function resolveCallbackUrl(baseUrl: string): string { + const trimmed = baseUrl.trim().replace(/\/+$/, '') + if (trimmed.endsWith(CALLBACK_PATH)) return trimmed + return `${trimmed}${CALLBACK_PATH}` +} diff --git a/worker/src/waker/receiver.ts b/worker/src/waker/receiver.ts new file mode 100644 index 0000000..bec53f6 --- /dev/null +++ b/worker/src/waker/receiver.ts @@ -0,0 +1,331 @@ +import { Hono } from 'hono' +import type { Context, Env } from 'hono' + +import type { ExecutionLedger } from './ledger' +import { + CALLBACK_HEADERS, + CALLBACK_MOUNT_PATH, + CALLBACK_PROTOCOL_VERSION, + CALLBACK_TIMESTAMP_TOLERANCE_SECONDS, + type CallbackRequestBody, + type ExecutionTrigger, + type JobKind, + type JsonValue, + type NextRunAt, +} from './protocol' +import { + WAKER_MODE_WAKER, + WAKER_SIGNING_KEY_ENV, + readEnvString, + resolveWakerMode, + type WakerEnvLike, + type WakerMode, +} from './modes' +import { verifyWakerSignature } from './verify' + +/** + * 下游 receiver:`app.route('/_waker', createWakerReceiver({ jobs }))`。 + * + * 设计要点(对齐 B3 回调协议 v2): + * - **不劫持整个 fetch**:只是一个 `/_waker/execute` 路由,下游其它路由完全不受影响; + * - **同步语义**:handler 返回(或 await 完成)后才回 2xx,失败回 5xx 让平台重试, + * 绝不 `waitUntil + 立即 OK`; + * - **验签在前**:body 用未解析的原始字符串验签,时间窗默认 300s; + * - **幂等**:可选 `ledger`(`client/src/ledger.ts`)。重复投递直接回 2xx + 首次响应体回放, + * 业务失败则释放占位,让平台的重试真的重跑; + * - **自续**:handler 返回 `{ nextRunAt }` 即透传给平台(平台自己再校验上限与时序)。 + */ + +/** receiver 内可用的上下文:只给业务需要的字段,不外泄平台内部结构。 */ +export interface WakerJobContext { + /** 任务名(= `jobs` 表的 key)。 */ + jobName: string + /** 执行 id:**下游幂等键**(同一次执行的重试共享)。 */ + executionId: string + /** 任务 id(自续后仍是同一个 job 系列)。 */ + jobId: string + projectId: string + kind: JobKind + trigger: ExecutionTrigger + misfire: boolean + /** 第几次投递,0 = 首次。 */ + attempt: number + /** 名义到期时刻(epoch ms)。 */ + scheduledFor: number + /** 平台投递时刻(epoch ms)。 */ + dispatchedAt: number + /** 平台侧超时(秒):业务应在此之前返回。 */ + timeoutSeconds: number + /** 任务载荷(原样透传,平台不解析)。 */ + payload: JsonValue +} + +/** + * handler 返回值:可以什么都不返回(= 任务完结),也可以带上 `nextRunAt` 自续。 + * 其它字段会原样回给平台(平台忽略),方便下游在响应里带业务信息排障。 + */ +export interface WakerJobOutcome { + /** 自续时刻:epoch ms 或 ISO 8601;不提供 = 任务完结(只对 one-shot 生效)。 */ + nextRunAt?: NextRunAt | null + [key: string]: unknown +} + +export type WakerJobHandler = ( + context: WakerJobContext, +) => WakerJobOutcome | void | Promise + +/** 任务名 → handler。名字与平台里注册的任务名逐字一致(manifest 里声明的同一份名字)。 */ +export type WakerJobHandlers = Record + +/** + * 任务名解析器:one-shot 的任务名常常按业务 id 动态生成(`letter-` / `reminder-tick-`), + * 静态 map 装不下,所以也允许传「名字 → handler」的函数(返回 `null` = 未声明该任务)。 + */ +export type WakerJobResolver = (jobName: string) => WakerJobHandler | null | undefined + +/** `jobs`:静态 map,或名字解析函数。 */ +export type WakerJobs = WakerJobHandlers | WakerJobResolver + +/** 与下游 env 无耦合的最小 Hono 绑定类型。 */ +export interface WakerReceiverEnv { + Bindings: Record +} + +export interface WakerReceiverOptions { + /** 任务名 → handler(静态 map 或解析函数)。 */ + jobs: WakerJobs + /** + * 项目 signing key:静态字符串,或从 env 解析的函数。 + * 缺省从 `env[signingKeyEnv]`(默认 `WAKER_SIGNING_KEY`)读取——只从 secrets 注入。 + */ + signingKey?: string | ((env: WakerEnvLike) => string | null) + /** 从 env 读 signing key 的变量名,默认 `WAKER_SIGNING_KEY`。 */ + signingKeyEnv?: string + /** 幂等账本(可选:不传 = 不做去重,平台的重试会重跑业务)。 */ + ledger?: ExecutionLedger + /** 注入时钟(epoch ms),测试可替换。 */ + now?: () => number + /** 验签时间窗(秒),默认 {@link CALLBACK_TIMESTAMP_TOLERANCE_SECONDS}。 */ + toleranceSeconds?: number + /** 业务 handler 抛错时的回调(打日志/告警用;不回给平台,平台只看状态码)。 */ + onJobError?: (error: unknown, context: WakerJobContext) => void +} + +/** 错误响应体(与平台侧错误体同构:`{ error: { code, message } }`,另加 `ok: false`)。 */ +export interface WakerReceiverErrorBody { + ok: false + error: { code: string; message: string } +} + +function errorBody(code: string, message: string): WakerReceiverErrorBody { + return { ok: false, error: { code, message } } +} + +/** 规范化 `nextRunAt`:只认有限数字与非空字符串,其它一律丢弃(平台校验上限与时序)。 */ +function normalizeNextRunAt(value: unknown): NextRunAt | null { + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim().length > 0) return value.trim() + return null +} + +function resolveSigningKey(options: WakerReceiverOptions, env: WakerEnvLike): string | null { + if (typeof options.signingKey === 'string') { + return options.signingKey.trim().length === 0 ? null : options.signingKey.trim() + } + if (typeof options.signingKey === 'function') return options.signingKey(env) + return readEnvString(env, options.signingKeyEnv ?? WAKER_SIGNING_KEY_ENV) +} + +function readBodyFields(body: CallbackRequestBody): boolean { + return ( + typeof body.executionId === 'string' && + body.executionId.length > 0 && + typeof body.jobId === 'string' && + body.jobId.length > 0 && + typeof body.jobName === 'string' && + body.jobName.length > 0 && + typeof body.scheduledFor === 'number' + ) +} + +/** + * 建一个只负责 `POST /execute` 的子应用。 + * + * 挂载方式(下游):`app.route('/_waker', createWakerReceiver({ jobs }))`, + * 或直接用 {@link mountWakerReceiver} 走「可选接入」判定。 + */ +export function createWakerReceiver(options: WakerReceiverOptions): Hono { + const receiver = new Hono() + const now = options.now ?? Date.now + + receiver.post('/execute', async (c: Context) => { + // 1) 原始 body 必须先拿到:验签用的是未解析的字节串。 + const rawBody = await c.req.text() + + const timestamp = c.req.header(CALLBACK_HEADERS.timestamp) ?? '' + const executionIdHeader = c.req.header(CALLBACK_HEADERS.executionId) ?? '' + const jobIdHeader = c.req.header(CALLBACK_HEADERS.jobId) ?? '' + const signature = c.req.header(CALLBACK_HEADERS.signature) ?? '' + + if ( + timestamp.length === 0 || + executionIdHeader.length === 0 || + jobIdHeader.length === 0 || + signature.length === 0 + ) { + return c.json(errorBody('invalid_request', '缺少签名头(X-Waker-Timestamp / X-Waker-Execution-Id / X-Waker-Job-Id / X-Waker-Signature)'), 400) + } + + // 2) 验签:时间窗之外的请求一律拒收(防重放)。 + const env = c.env as WakerEnvLike + const secret = resolveSigningKey(options, env) + if (secret === null) { + // fail closed:没有 signing key 就绝不「看起来正常地」放行。 + return c.json(errorBody('signing_key_missing', '服务端未配置 WAKER_SIGNING_KEY,无法验签'), 500) + } + + const verification = await verifyWakerSignature({ + secret, + signature, + timestamp, + executionId: executionIdHeader, + jobId: jobIdHeader, + body: rawBody, + now: now(), + toleranceSeconds: options.toleranceSeconds ?? CALLBACK_TIMESTAMP_TOLERANCE_SECONDS, + }) + if (!verification.ok) { + const stale = verification.reason === 'stale_timestamp' + return c.json( + errorBody( + stale ? 'stale_timestamp' : 'invalid_signature', + stale ? '请求时间戳超出允许窗口(可能是重放)' : `签名校验失败(${verification.reason})`, + ), + 401, + ) + } + + // 3) 解析并校验请求体(签名已覆盖 body,这里只做结构断言,不做信任边界判定)。 + let parsed: unknown + try { + parsed = JSON.parse(rawBody) + } catch { + return c.json(errorBody('invalid_request', '请求体不是合法 JSON'), 400) + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return c.json(errorBody('invalid_request', '请求体必须是 JSON 对象'), 400) + } + const body = parsed as CallbackRequestBody + if (body.protocolVersion !== CALLBACK_PROTOCOL_VERSION) { + return c.json( + errorBody('unsupported_protocol', `不支持的协议版本:${String(body.protocolVersion)}(期望 ${CALLBACK_PROTOCOL_VERSION})`), + 400, + ) + } + if (!readBodyFields(body)) { + return c.json(errorBody('invalid_request', '请求体缺少 executionId / jobId / jobName / scheduledFor'), 400) + } + if (body.executionId !== executionIdHeader || body.jobId !== jobIdHeader) { + return c.json(errorBody('invalid_request', '请求体 id 与签名头不一致'), 400) + } + + // 4) 分发到业务 handler:名字必须与注册时一致,未知名字是部署期错误,明确回 404。 + const handler = + typeof options.jobs === 'function' + ? options.jobs(body.jobName) ?? undefined + : options.jobs[body.jobName] + if (handler === undefined) { + return c.json( + errorBody('unknown_job', `未声明的任务名:${body.jobName}(receiver 的 jobs 里没有这个 key)`), + 404, + ) + } + + const context: WakerJobContext = { + jobName: body.jobName, + executionId: body.executionId, + jobId: body.jobId, + projectId: body.projectId, + kind: body.kind, + trigger: body.trigger, + misfire: body.misfire === true, + attempt: typeof body.attempt === 'number' ? body.attempt : 0, + scheduledFor: body.scheduledFor, + dispatchedAt: body.dispatchedAt, + timeoutSeconds: body.timeoutSeconds, + payload: body.payload, + } + + // 5) 幂等:同一次执行的重试直接回放首次结果(不重跑业务,也不丢 nextRunAt)。 + if (options.ledger !== undefined) { + const claim = await options.ledger.claim({ + executionId: context.executionId, + jobId: context.jobId, + jobName: context.jobName, + scheduledFor: context.scheduledFor, + }) + if (!claim.claimed) { + return c.json({ + ...(claim.existing?.response ?? {}), + ok: true, + duplicate: true, + }) + } + } + + // 6) 跑业务:异常 → 释放占位 + 5xx,让平台重试(重试仍是同一个 executionId)。 + try { + const outcome = await handler(context) + const nextRunAt = normalizeNextRunAt(outcome?.nextRunAt) + // 业务字段原样回给平台(平台只认 nextRunAt,其它字段留着排障),`ok` 由 SDK 兜底置真。 + const response: Record = { ...(outcome ?? {}), ok: true } + if (nextRunAt === null) delete response.nextRunAt + else response.nextRunAt = nextRunAt + + await options.ledger?.complete(context.executionId, response) + return c.json(response) + } catch (error) { + await options.ledger?.release(context.executionId) + options.onJobError?.(error, context) + return c.json(errorBody('job_failed', '任务执行失败,平台将按策略重试'), 500) + } + }) + + return receiver +} + +export interface MountWakerReceiverOptions extends WakerReceiverOptions { + /** 显式模式(优先于 `env`)。 */ + mode?: WakerMode + /** 模式来源:`WAKER_MODE` 从这里读,缺省按 `cron`。 */ + env?: WakerEnvLike +} + +/** + * 可选接入的挂载入口:**只在 `WAKER_MODE=waker` 时**把 receiver 挂到 `/_waker`。 + * + * 返回 `true` = 已挂载(waker 模式);`false` = 原生模式,一条路由都没加。 + * 原生模式下 SDK 只做了一次 env 判定,不构造 receiver、不发任何网络请求。 + * + * waker 模式下若 signing key 缺失会**立刻抛错**(部署期 fail fast), + * 而不是等到第一次回调才发现验不了签。 + */ +export function mountWakerReceiver( + app: Hono, + options: MountWakerReceiverOptions, +): boolean { + const mode = options.mode ?? resolveWakerMode(options.env) + if (mode !== WAKER_MODE_WAKER) return false + + const key = resolveSigningKey(options, options.env ?? null) + if (key === null) { + throw new Error( + `WAKER_MODE=waker 但缺少 signing key(${options.signingKeyEnv ?? WAKER_SIGNING_KEY_ENV}):` + + '请用 `wrangler secret put` 注入建项目时一次性展示的那把 key。', + ) + } + + const receiver = createWakerReceiver(options) + app.route(CALLBACK_MOUNT_PATH, receiver as unknown as Hono) + return true +} diff --git a/worker/src/waker/verify.ts b/worker/src/waker/verify.ts new file mode 100644 index 0000000..c9259de --- /dev/null +++ b/worker/src/waker/verify.ts @@ -0,0 +1,104 @@ +import { + CALLBACK_SIGNATURE_PREFIX, + CALLBACK_TIMESTAMP_TOLERANCE_SECONDS, + buildSignaturePayload, +} from './protocol' + +/** + * HMAC 验签 helper(对齐 B3 冻结契约)。 + * + * 全部用 Workers / Node 都自带的 WebCrypto:`crypto.subtle.importKey` / `crypto.subtle.verify`。 + * **不手搓 HMAC,也不用 `===` 比较签名**——`crypto.subtle.verify` 是原生常量时间实现, + * 自己逐字节比会是计时侧信道。 + */ + +const encoder = new TextEncoder() + +/** 验签失败原因(下游可据此分支:过期 vs 伪造 vs 没带签名)。 */ +export type SignatureFailureReason = + | 'missing_signature' + | 'malformed_signature' + | 'missing_signed_field' + | 'stale_timestamp' + | 'bad_signature' + +export type SignatureVerification = + | { ok: true } + | { ok: false; reason: SignatureFailureReason } + +export interface VerifySignatureInput { + /** 项目 signing key 明文(平台建项目时一次性展示的那把)。 */ + secret: string + /** `X-Waker-Signature` 头原值(`v2=`)。 */ + signature: string + /** `X-Waker-Timestamp` 头原值(epoch 秒的十进制字符串)。 */ + timestamp: string + /** `X-Waker-Execution-Id`。 */ + executionId: string + /** `X-Waker-Job-Id`。 */ + jobId: string + /** 未解析的原始请求体字符串。 */ + body: string + /** 收到请求的时刻(epoch ms),默认 `Date.now()`;测试可注入。 */ + now?: number + /** 时间窗(秒),默认 {@link CALLBACK_TIMESTAMP_TOLERANCE_SECONDS}。 */ + toleranceSeconds?: number +} + +function hexToBytes(hex: string): Uint8Array | null { + if (hex.length === 0 || hex.length % 2 !== 0) return null + const bytes = new Uint8Array(hex.length / 2) + for (let index = 0; index < bytes.length; index += 1) { + const byte = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16) + if (Number.isNaN(byte)) return null + bytes[index] = byte + } + return bytes +} + +/** + * 验签:材料齐全 → 签名格式 → 时间窗(防重放)→ HMAC 常量时间比对。 + * + * 该函数不抛错,所有失败折成 `{ ok: false, reason }`,便于下游直接映射 HTTP 状态码。 + */ +export async function verifyWakerSignature( + input: VerifySignatureInput, +): Promise { + if (input.signature.length === 0) return { ok: false, reason: 'missing_signature' } + if (input.executionId.length === 0 || input.jobId.length === 0 || input.timestamp.length === 0) { + return { ok: false, reason: 'missing_signed_field' } + } + + if (!input.signature.startsWith(CALLBACK_SIGNATURE_PREFIX)) { + return { ok: false, reason: 'malformed_signature' } + } + const provided = hexToBytes(input.signature.slice(CALLBACK_SIGNATURE_PREFIX.length)) + if (provided === null || provided.length !== 32) { + return { ok: false, reason: 'malformed_signature' } + } + + const timestampSeconds = Number(input.timestamp) + if (!Number.isFinite(timestampSeconds)) return { ok: false, reason: 'malformed_signature' } + + const now = input.now ?? Date.now() + const tolerance = input.toleranceSeconds ?? CALLBACK_TIMESTAMP_TOLERANCE_SECONDS + if (Math.abs(now / 1000 - timestampSeconds) > tolerance) { + return { ok: false, reason: 'stale_timestamp' } + } + + const key = await crypto.subtle.importKey( + 'raw', + encoder.encode(input.secret), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['verify'], + ) + + const valid = await crypto.subtle.verify( + 'HMAC', + key, + provided, + encoder.encode(buildSignaturePayload(input)), + ) + return valid ? { ok: true } : { ok: false, reason: 'bad_signature' } +} diff --git a/worker/test/admin.test.ts b/worker/test/admin.test.ts index 91c5ed6..0ceefb5 100644 --- a/worker/test/admin.test.ts +++ b/worker/test/admin.test.ts @@ -30,6 +30,7 @@ describe("POST /api/admin/setup", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -118,6 +119,7 @@ describe("POST /api/admin/setup", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); }); diff --git a/worker/test/ledger.test.ts b/worker/test/ledger.test.ts index b2bbe98..ce779de 100644 --- a/worker/test/ledger.test.ts +++ b/worker/test/ledger.test.ts @@ -280,9 +280,13 @@ describe("migrationsTable name formula", () => { }); describe("migration list", () => { - it("keeps schema_v1 as the base and appends schema_v2", () => { + it("keeps schema_v1 as the base and appends schema_v2 / schema_v3", () => { const migrations = getMigrations("enotify_"); - expect(migrations.map((m) => m.name)).toEqual(["schema_v1", "schema_v2"]); + expect(migrations.map((m) => m.name)).toEqual([ + "schema_v1", + "schema_v2", + "schema_v3", + ]); // `{prefix}` is resolved for the caller, the DDL itself carries no placeholder. expect(migrations[0].sql).toContain( "CREATE TABLE IF NOT EXISTS enotify_users", @@ -292,6 +296,16 @@ describe("migration list", () => { "ALTER TABLE enotify_notification_history ADD COLUMN trigger_source TEXT", ); expect(migrations[1].sql).not.toContain("{prefix}"); + expect(migrations[2].sql).toContain( + "CREATE TABLE IF NOT EXISTS enotify_waker_executions", + ); + expect(migrations[2].sql).toContain( + "CREATE TABLE IF NOT EXISTS enotify_scheduler_tick_claims", + ); + expect(migrations[2].sql).toContain( + "CREATE INDEX IF NOT EXISTS idx_enotify_scheduler_tick_claims_claimed_at", + ); + expect(migrations[2].sql).not.toContain("{prefix}"); }); it("migration SQL contains no ';' inside string literals", () => { @@ -309,7 +323,7 @@ describe("migration list", () => { // ─── fresh install ──────────────────────────────────────────────────────────── describe("fresh install through the ledger", () => { - it("creates the 7 tables, the ledger and the default settings", async () => { + it("creates the 7 business tables, the 2 waker tables, the ledger and the default settings", async () => { const d1 = new SqliteD1(); const result = await runSetup(makeEnv(d1, "enotify")); @@ -320,6 +334,7 @@ describe("fresh install through the ledger", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -332,6 +347,8 @@ describe("fresh install through the ledger", () => { "notification_configs", "system_settings", "notification_history", + "waker_executions", + "scheduler_tick_claims", ]) { expect(tables).toContain(`enotify_${table}`); } @@ -339,6 +356,22 @@ describe("fresh install through the ledger", () => { expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ { name: "schema_v1" }, { name: "schema_v2" }, + { name: "schema_v3" }, + ]); + expect( + indexesOf(d1, "enotify_scheduler_tick_claims").map((i) => i.name), + ).toContain("idx_enotify_scheduler_tick_claims_claimed_at"); + expect( + columnsOf(d1, "enotify_waker_executions").map((c) => c.name), + ).toEqual([ + "execution_id", + "job_id", + "job_name", + "scheduled_for", + "status", + "response_json", + "claimed_at", + "completed_at", ]); expect( columnsOf(d1, "enotify_notification_history").map((c) => c.name), @@ -375,6 +408,7 @@ describe("fresh install through the ledger", () => { migrations: [ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, ], }); expect(snapshot(d1)).toEqual(before); @@ -555,6 +589,7 @@ describe("legacy database transition", () => { migrations: [ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -567,6 +602,7 @@ describe("legacy database transition", () => { migrations: [ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, ], }); expect(snapshot(d1)).toEqual(afterSecond); @@ -699,11 +735,13 @@ describe("ledger consistency check", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); expect(ledgerRows(d1, "_schema_migrations")).toEqual([ { name: "schema_v1" }, { name: "schema_v2" }, + { name: "schema_v3" }, ]); expect(exists(d1, "users")).toBe(true); }); @@ -721,8 +759,11 @@ describe("prefix variants", () => { expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ { name: "schema_v1" }, { name: "schema_v2" }, + { name: "schema_v3" }, ]); expect(exists(d1, "enotify_users")).toBe(true); + expect(exists(d1, "enotify_waker_executions")).toBe(true); + expect(exists(d1, "enotify_scheduler_tick_claims")).toBe(true); }); it("uses _schema_migrations for an explicit empty prefix", async () => { @@ -733,8 +774,11 @@ describe("prefix variants", () => { expect(ledgerRows(d1, "_schema_migrations")).toEqual([ { name: "schema_v1" }, { name: "schema_v2" }, + { name: "schema_v3" }, ]); expect(exists(d1, "users")).toBe(true); + expect(exists(d1, "waker_executions")).toBe(true); + expect(exists(d1, "scheduler_tick_claims")).toBe(true); }); it("uses _X_schema_migrations for a custom prefix X", async () => { @@ -745,8 +789,11 @@ describe("prefix variants", () => { expect(ledgerRows(d1, "_X_schema_migrations")).toEqual([ { name: "schema_v1" }, { name: "schema_v2" }, + { name: "schema_v3" }, ]); expect(exists(d1, "X_users")).toBe(true); + expect(exists(d1, "X_waker_executions")).toBe(true); + expect(exists(d1, "X_scheduler_tick_claims")).toBe(true); }); it("leaves another prefix's tables and ledger untouched when two coexist", async () => { @@ -814,6 +861,7 @@ describe("prefix conflict guard with the ledger", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); // The foreign ledger is neither read nor written. @@ -821,6 +869,7 @@ describe("prefix conflict guard with the ledger", () => { expect(ledgerRows(d1, "_enotify_schema_migrations")).toEqual([ { name: "schema_v1" }, { name: "schema_v2" }, + { name: "schema_v3" }, ]); }); diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index d6c4ee2..89f16e8 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -234,6 +234,7 @@ describe("notification_configs slack_config migration", () => { migrations: [ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -241,6 +242,7 @@ describe("notification_configs slack_config migration", () => { expect(third.migrations).toEqual([ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, ]); const rows = d1.db @@ -416,6 +418,7 @@ describe("retired channel cleanup migration", () => { migrations: [ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -423,6 +426,7 @@ describe("retired channel cleanup migration", () => { expect(third.migrations).toEqual([ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, ]); expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); @@ -436,7 +440,7 @@ describe("retired channel cleanup migration", () => { const d1 = new SqliteD1(); seedLegacyChannels(d1); // First setup stamps schema_v1 on a pre-ledger database; the second one - // applies the migrations appended after it (schema_v2). + // applies the migrations appended after it (schema_v2 / schema_v3). await runSetup(makeEnv(d1)); await runSetup(makeEnv(d1)); @@ -482,6 +486,7 @@ describe("fresh install schema", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); diff --git a/worker/test/prefix.test.ts b/worker/test/prefix.test.ts index 97c3524..0ffebbc 100644 --- a/worker/test/prefix.test.ts +++ b/worker/test/prefix.test.ts @@ -238,6 +238,7 @@ describe("runSetup anti-silent-switch guard", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -265,6 +266,7 @@ describe("runSetup anti-silent-switch guard", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -312,6 +314,7 @@ describe("admin setup route surfaces prefix conflicts", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); }); diff --git a/worker/test/scheduled-entry.test.ts b/worker/test/scheduled-entry.test.ts new file mode 100644 index 0000000..53bf675 --- /dev/null +++ b/worker/test/scheduled-entry.test.ts @@ -0,0 +1,208 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import worker from "../src/index"; +import { getMigrations } from "../src/lib/migrations"; +import type { Env } from "../src/types"; +import { schedulerTickKey } from "../src/db/queries/scheduler-ticks"; +import { MockKV, TEST_JWT_SECRET, TEST_SETUP_SECRET } from "./helpers"; +import { SqliteD1 } from "./support/sqlite-d1"; + +const handleScheduledMock = vi.hoisted(() => vi.fn(async () => {})); +vi.mock("../src/services/scheduler", () => ({ + handleScheduled: handleScheduledMock, +})); + +const T0 = Date.UTC(2026, 9, 28, 10, 0, 0); +const HOUR_MS = 3_600_000; +const TEST_WAKER_KEY = "test-waker-signing-key"; + +/** The SPA fallback in front of every route would answer this with 200 HTML. */ +function htmlAssets(): { fetch: () => Promise } { + return { + fetch: async () => + new Response("spa", { + status: 200, + headers: { "content-type": "text/html; charset=utf-8" }, + }), + }; +} + +function applySchemaV3(d1: SqliteD1, prefix: string): void { + const migration = getMigrations(prefix).find((m) => m.name === "schema_v3"); + if (!migration) throw new Error("schema_v3 missing"); + for (const statement of migration.sql + .split(";") + .map((s) => s.trim()) + .filter((s) => s.length > 0)) { + d1.db.exec(statement); + } +} + +function makeEnv(d1: SqliteD1, overrides: Record = {}): Env { + return { + DB: d1, + KV: new MockKV(), + JWT_SECRET: TEST_JWT_SECRET, + SETUP_SECRET: TEST_SETUP_SECRET, + TABLE_PREFIX: "", + ASSETS: htmlAssets(), + ...overrides, + } as unknown as Env; +} + +function scheduledEvent(scheduledTime: number): ScheduledEvent { + return { + scheduledTime, + cron: "0 * * * *", + noRetry: () => {}, + waitUntil: () => {}, + } as unknown as ScheduledEvent; +} + +function claimRows(d1: SqliteD1): { tick_key: string; source: string }[] { + return d1.db + .prepare("SELECT tick_key, source FROM scheduler_tick_claims") + .all() as { tick_key: string; source: string }[]; +} + +beforeEach(() => { + handleScheduledMock.mockReset(); + handleScheduledMock.mockImplementation(async () => {}); +}); + +describe("native scheduled() entry", () => { + it("claims the hour of event.scheduledTime as source cron", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + + await worker.scheduled(scheduledEvent(T0), env); + + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + expect(claimRows(d1)).toEqual([ + { tick_key: schedulerTickKey(T0), source: "cron" }, + ]); + }); + + it("does not sweep the same hour twice", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + + await worker.scheduled(scheduledEvent(T0), env); + await worker.scheduled(scheduledEvent(T0), env); + + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + }); + + it("waits for the business pass before resolving (no waitUntil + early return)", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + let finished = false; + handleScheduledMock.mockImplementationOnce(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + finished = true; + }); + + await worker.scheduled(scheduledEvent(T0), env); + + expect(finished).toBe(true); + }); + + it("still runs when the claim table is missing and no waker key is set", async () => { + const d1 = new SqliteD1(); // migration not applied + const env = makeEnv(d1); + const errorMock = vi.spyOn(console, "error").mockImplementation(() => {}); + + await worker.scheduled(scheduledEvent(T0), env); + + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + errorMock.mockRestore(); + }); + + it("skips the sweep when the claim table is missing and a waker key is set", async () => { + const d1 = new SqliteD1(); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + const errorMock = vi.spyOn(console, "error").mockImplementation(() => {}); + + await worker.scheduled(scheduledEvent(T0), env); + + expect(handleScheduledMock).not.toHaveBeenCalled(); + expect( + errorMock.mock.calls.some(([line]) => + String(line).includes("scheduler_tick_claim_unavailable"), + ), + ).toBe(true); + errorMock.mockRestore(); + }); + + it("runs every distinct hour", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + + await worker.scheduled(scheduledEvent(T0), env); + await worker.scheduled(scheduledEvent(T0 + HOUR_MS), env); + + expect(handleScheduledMock).toHaveBeenCalledTimes(2); + expect(claimRows(d1).map((r) => r.tick_key)).toEqual([ + schedulerTickKey(T0), + schedulerTickKey(T0 + HOUR_MS), + ]); + }); +}); + +describe("/_waker is mounted before the SPA fallback", () => { + it("answers an unsigned POST with 400 JSON, never the 200 HTML fallback", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + + const res = await worker.fetch( + new Request("https://notify.example.com/_waker/execute", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "{}", + }), + env, + {} as ExecutionContext, + ); + const text = await res.text(); + + expect(res.status).toBe(400); + expect(res.headers.get("content-type") ?? "").toContain("application/json"); + expect(text).not.toContain(" { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + + const res = await worker.fetch( + new Request("https://notify.example.com/_waker/execute"), + env, + {} as ExecutionContext, + ); + const text = await res.text(); + + expect(res.status).toBe(404); + expect(res.headers.get("content-type") ?? "").not.toContain("text/html"); + expect(text).not.toContain(" { + const d1 = new SqliteD1(); + const env = makeEnv(d1); + + const res = await worker.fetch( + new Request("https://notify.example.com/items/123"), + env, + {} as ExecutionContext, + ); + + expect(res.status).toBe(200); + expect(res.headers.get("content-type") ?? "").toContain("text/html"); + }); +}); diff --git a/worker/test/scheduler-tick.test.ts b/worker/test/scheduler-tick.test.ts new file mode 100644 index 0000000..17f5e45 --- /dev/null +++ b/worker/test/scheduler-tick.test.ts @@ -0,0 +1,378 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getMigrations } from "../src/lib/migrations"; +import type { Env } from "../src/types"; +import { + claimSchedulerTick, + getSchedulerTickClaim, + releaseSchedulerTick, + schedulerTickClaimsTable, + schedulerTickKey, +} from "../src/db/queries/scheduler-ticks"; +import { + runSchedulerTick, + wakerExecutionsTable, + wakerSigningKey, +} from "../src/services/scheduler-tick"; +import { MockKV, TEST_JWT_SECRET, TEST_SETUP_SECRET } from "./helpers"; +import { SqliteD1 } from "./support/sqlite-d1"; + +// The business pass is the one thing this suite must not re-implement: it is +// mocked so the tests can count "did the hourly scan run" exactly. +const handleScheduledMock = vi.hoisted(() => vi.fn(async () => {})); +vi.mock("../src/services/scheduler", () => ({ + handleScheduled: handleScheduledMock, +})); + +const HOUR_MS = 3_600_000; +/** Fixed nominal hour: 2026-10-28 10:00:00 UTC. */ +const T0 = Date.UTC(2026, 9, 28, 10, 0, 0); +const TEST_WAKER_KEY = "test-waker-signing-key"; + +/** Apply the real schema_v3 DDL for a resolved prefix. */ +function applySchemaV3(d1: SqliteD1, prefix: string): void { + const migration = getMigrations(prefix).find((m) => m.name === "schema_v3"); + if (!migration) throw new Error("schema_v3 missing"); + for (const statement of migration.sql + .split(";") + .map((s) => s.trim()) + .filter((s) => s.length > 0)) { + d1.db.exec(statement); + } +} + +function makeTickEnv( + d1: SqliteD1, + overrides: Record = {}, +): Env { + return { + DB: d1, + KV: new MockKV(), + JWT_SECRET: TEST_JWT_SECRET, + SETUP_SECRET: TEST_SETUP_SECRET, + TABLE_PREFIX: "", + ASSETS: {}, + ...overrides, + } as unknown as Env; +} + +function countRows(d1: SqliteD1, table: string): number { + const row = d1.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { + n: number; + }; + return Number(row.n); +} + +beforeEach(() => { + handleScheduledMock.mockReset(); + handleScheduledMock.mockImplementation(async () => {}); +}); + +describe("schedulerTickKey", () => { + it("rounds to the UTC hour slot", () => { + expect(schedulerTickKey(T0)).toBe(`hour:${T0}`); + expect(schedulerTickKey(T0 + 59 * 60 * 1000 + 59_999)).toBe(`hour:${T0}`); + expect(schedulerTickKey(T0 + HOUR_MS)).toBe(`hour:${T0 + HOUR_MS}`); + }); + + it("keeps adjacent hour boundaries distinct", () => { + const lastMs = T0 - 1; // 09:59:59.999 + expect(schedulerTickKey(lastMs)).not.toBe(schedulerTickKey(T0)); + expect(schedulerTickKey(lastMs)).toBe(`hour:${T0 - HOUR_MS}`); + }); +}); + +describe("wakerSigningKey gate", () => { + it.each([ + ["missing", undefined], + ["empty", ""], + ["whitespace", " \t "], + ["placeholder", "some-value_PLACEHOLDER"], + ])("treats %s as not configured", (_name, value) => { + expect(wakerSigningKey({ WAKER_SIGNING_KEY: value } as never)).toBeNull(); + }); + + it("returns the trimmed value when configured", () => { + expect( + wakerSigningKey({ WAKER_SIGNING_KEY: ` ${TEST_WAKER_KEY} ` } as never), + ).toBe(TEST_WAKER_KEY); + }); +}); + +describe("claimSchedulerTick", () => { + it("lets exactly one of two claims for the same hour win", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const key = schedulerTickKey(T0); + + expect(await claimSchedulerTick(d1 as never, "", key, "cron", 1)).toBe( + true, + ); + expect(await claimSchedulerTick(d1 as never, "", key, "waker", 2)).toBe( + false, + ); + + expect(await getSchedulerTickClaim(d1 as never, "", key)).toEqual({ + tick_key: key, + source: "cron", + claimed_at: 1, + }); + expect(countRows(d1, "scheduler_tick_claims")).toBe(1); + }); + + it("releases only the claim made by the releasing source", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const key = schedulerTickKey(T0); + await claimSchedulerTick(d1 as never, "", key, "cron", 1); + + await releaseSchedulerTick(d1 as never, "", key, "waker"); + expect(countRows(d1, "scheduler_tick_claims")).toBe(1); + + await releaseSchedulerTick(d1 as never, "", key, "cron"); + expect(countRows(d1, "scheduler_tick_claims")).toBe(0); + }); +}); + +describe("runSchedulerTick — cross-entry guard", () => { + it("runs the business pass once per hour across both entry points", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeTickEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const sources = ["cron", "waker"] as const; + const results = await Promise.all( + sources.map((source) => + runSchedulerTick(env, { source, scheduledFor: T0 }), + ), + ); + + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + expect(results.filter((r) => r.executed)).toHaveLength(1); + const duplicate = results.find((r) => r.reason === "duplicate_tick"); + expect(duplicate).toBeDefined(); + const winnerIndex = results.findIndex((r) => r.executed); + const loserIndex = results.findIndex((r) => r.reason === "duplicate_tick"); + expect(duplicate?.claimedBy).toBe(sources[winnerIndex]); + expect(loserIndex).not.toBe(winnerIndex); + expect(countRows(d1, "scheduler_tick_claims")).toBe(1); + }); + + it("runs each distinct hour once", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeTickEnv(d1); + + const first = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0, + }); + const second = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0 + HOUR_MS, + }); + + expect(first.executed).toBe(true); + expect(second.executed).toBe(true); + expect(handleScheduledMock).toHaveBeenCalledTimes(2); + expect(countRows(d1, "scheduler_tick_claims")).toBe(2); + }); + + it("does not re-run an hour the other entry point already claimed", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeTickEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + await claimSchedulerTick( + d1 as never, + "", + schedulerTickKey(T0), + "cron", + Date.now(), + ); + + const result = await runSchedulerTick(env, { + source: "waker", + scheduledFor: T0 + 30_000, + }); + + expect(result).toMatchObject({ + executed: false, + reason: "duplicate_tick", + claimedBy: "cron", + tickKey: schedulerTickKey(T0), + }); + expect(handleScheduledMock).not.toHaveBeenCalled(); + }); +}); + +describe("runSchedulerTick — failure semantics", () => { + it("releases the hour on a waker failure so the retry can finish the job", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeTickEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + handleScheduledMock.mockRejectedValueOnce(new Error("hour blew up")); + + await expect( + runSchedulerTick(env, { source: "waker", scheduledFor: T0 }), + ).rejects.toThrow("hour blew up"); + expect(countRows(d1, "scheduler_tick_claims")).toBe(0); + + const retry = await runSchedulerTick(env, { + source: "waker", + scheduledFor: T0, + }); + expect(retry.executed).toBe(true); + expect(handleScheduledMock).toHaveBeenCalledTimes(2); + expect(countRows(d1, "scheduler_tick_claims")).toBe(1); + }); + + it("keeps the claim on a cron failure so the hour is not swept twice", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeTickEnv(d1); + handleScheduledMock.mockRejectedValueOnce(new Error("cron blew up")); + + const failed = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0, + }); + expect(failed).toMatchObject({ executed: false, reason: "job_failed" }); + expect(countRows(d1, "scheduler_tick_claims")).toBe(1); + + const again = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0, + }); + expect(again).toMatchObject({ + executed: false, + reason: "duplicate_tick", + claimedBy: "cron", + }); + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + }); + + it("runs anyway when the claim table is unavailable and no waker key is set", async () => { + // Fresh DB: scheduler_tick_claims does not exist (migration not applied). + const d1 = new SqliteD1(); + const env = makeTickEnv(d1); + const errorMock = vi.spyOn(console, "error").mockImplementation(() => {}); + + const result = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0, + }); + + expect(result.executed).toBe(true); + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + expect( + errorMock.mock.calls.some(([line]) => + String(line).includes("scheduler_tick_claim_unavailable"), + ), + ).toBe(true); + errorMock.mockRestore(); + }); + + it("fails safe on both entries when the claim table is unavailable and a waker key is set", async () => { + const d1 = new SqliteD1(); + const env = makeTickEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + const errorMock = vi.spyOn(console, "error").mockImplementation(() => {}); + + const cronResult = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0, + }); + expect(cronResult).toMatchObject({ + executed: false, + reason: "claim_unavailable", + }); + expect(handleScheduledMock).not.toHaveBeenCalled(); + + await expect( + runSchedulerTick(env, { source: "waker", scheduledFor: T0 }), + ).rejects.toThrow(/no such table/); + expect(handleScheduledMock).not.toHaveBeenCalled(); + errorMock.mockRestore(); + }); +}); + +describe("runSchedulerTick — housekeeping and prefixes", () => { + it("prunes claims older than 7 days and keeps recent ones", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const now = Date.now(); + d1.db + .prepare( + "INSERT INTO scheduler_tick_claims (tick_key, source, claimed_at) VALUES (?, ?, ?)", + ) + .run("hour:old", "cron", now - 8 * 24 * HOUR_MS); + d1.db + .prepare( + "INSERT INTO scheduler_tick_claims (tick_key, source, claimed_at) VALUES (?, ?, ?)", + ) + .run("hour:recent", "waker", now - 24 * HOUR_MS); + + const env = makeTickEnv(d1); + await runSchedulerTick(env, { source: "cron", scheduledFor: now }); + + const keys = ( + d1.db.prepare("SELECT tick_key FROM scheduler_tick_claims").all() as { + tick_key: string; + }[] + ).map((r) => r.tick_key); + expect(keys).not.toContain("hour:old"); + expect(keys).toContain("hour:recent"); + expect(keys).toContain(schedulerTickKey(now)); + }); + + it("keeps the tick result even when pruning fails", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeTickEnv(d1); + const errorMock = vi.spyOn(console, "error").mockImplementation(() => {}); + // The business pass succeeds but leaves no claim table for the prune step. + handleScheduledMock.mockImplementationOnce(async () => { + d1.db.exec("DROP TABLE scheduler_tick_claims"); + }); + + const result = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0, + }); + + expect(result.executed).toBe(true); + expect( + errorMock.mock.calls.some(([line]) => + String(line).includes("scheduler_tick_prune_failed"), + ), + ).toBe(true); + errorMock.mockRestore(); + }); + + it.each([ + ["default", undefined, "enotify_"], + ["explicit empty", "", ""], + ["custom", "eNotify", "eNotify_"], + ])( + "resolves the claim table for the %s TABLE_PREFIX state", + async (_n, prefix, resolved) => { + const d1 = new SqliteD1(); + applySchemaV3(d1, resolved); + const env = makeTickEnv(d1, { TABLE_PREFIX: prefix }); + + const result = await runSchedulerTick(env, { + source: "cron", + scheduledFor: T0, + }); + + const table = schedulerTickClaimsTable(resolved); + expect(table).toBe(`${resolved}scheduler_tick_claims`); + expect(result.executed).toBe(true); + expect(countRows(d1, table)).toBe(1); + }, + ); + + it("names the waker ledger table with the resolved prefix", () => { + expect(wakerExecutionsTable("enotify_")).toBe("enotify_waker_executions"); + expect(wakerExecutionsTable("")).toBe("waker_executions"); + expect(wakerExecutionsTable("eNotify_")).toBe("eNotify_waker_executions"); + }); +}); diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 448ec87..511cda4 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -166,6 +166,7 @@ describe("POST /api/setup (regression)", () => { migrations: [ { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, ], }); @@ -174,6 +175,7 @@ describe("POST /api/setup (regression)", () => { expect(db.ledger.get("_schema_migrations")).toEqual([ "schema_v1", "schema_v2", + "schema_v3", ]); }); @@ -197,6 +199,7 @@ describe("POST /api/setup (regression)", () => { migrations: [ { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, ], }); }); diff --git a/worker/test/support/sqlite-d1.ts b/worker/test/support/sqlite-d1.ts index d243d3e..d8fd135 100644 --- a/worker/test/support/sqlite-d1.ts +++ b/worker/test/support/sqlite-d1.ts @@ -3,8 +3,9 @@ * (`node:sqlite`, built into Node 22+). * * Unlike the `MockD1` in helpers.ts this keeps real column defaults, row data, - * foreign keys and PRAGMA output, which is what schema/migration assertions - * need to stay honest. D1 is SQLite, so the SQL under test runs unchanged. + * foreign keys, PRAGMA output and `meta.changes`, which is what + * schema/migration/claim assertions need to stay honest. D1 is SQLite, so the + * SQL under test runs unchanged. */ // @ts-expect-error node:sqlite ships with Node but is not in the Workers type set. import { DatabaseSync } from "node:sqlite"; @@ -24,15 +25,27 @@ export class SqliteD1 { results: statement().all(...(args as any[])) as T[], }), run: async () => { - statement().run(...(args as any[])); - return { success: true }; + const result = statement().run(...(args as any[])); + return { + success: true, + meta: { + changes: Number(result.changes), + last_row_id: Number(result.lastInsertRowid), + }, + }; }, }), first: async () => (statement().get() ?? null) as T | null, all: async () => ({ results: statement().all() as T[] }), run: async () => { - statement().run(); - return { success: true }; + const result = statement().run(); + return { + success: true, + meta: { + changes: Number(result.changes), + last_row_id: Number(result.lastInsertRowid), + }, + }; }, }; } diff --git a/worker/test/waker-callback.test.ts b/worker/test/waker-callback.test.ts new file mode 100644 index 0000000..638b8d2 --- /dev/null +++ b/worker/test/waker-callback.test.ts @@ -0,0 +1,367 @@ +import { Hono } from "hono"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getMigrations } from "../src/lib/migrations"; +import type { Env } from "../src/types"; +import { CALLBACK_MOUNT_PATH } from "../src/waker"; +import { wakerRoutes } from "../src/routes/waker"; +import { WAKER_JOB_NAME } from "../src/services/waker-callback"; +import { schedulerTickKey } from "../src/db/queries/scheduler-ticks"; +import { MockKV, TEST_JWT_SECRET, TEST_SETUP_SECRET } from "./helpers"; +import { SqliteD1 } from "./support/sqlite-d1"; + +// Business pass mocked: the receiver contract is about verification, idempotency +// and cross-entry claims, and the count of business runs must be exact. +const handleScheduledMock = vi.hoisted(() => vi.fn(async () => {})); +vi.mock("../src/services/scheduler", () => ({ + handleScheduled: handleScheduledMock, +})); + +const T0 = Date.UTC(2026, 9, 28, 10, 0, 0); +const TEST_WAKER_KEY = "test-waker-signing-key"; + +const app = new Hono(); +app.route(CALLBACK_MOUNT_PATH, wakerRoutes()); + +function applySchemaV3(d1: SqliteD1, prefix: string): void { + const migration = getMigrations(prefix).find((m) => m.name === "schema_v3"); + if (!migration) throw new Error("schema_v3 missing"); + for (const statement of migration.sql + .split(";") + .map((s) => s.trim()) + .filter((s) => s.length > 0)) { + d1.db.exec(statement); + } +} + +function makeEnv(d1: SqliteD1, overrides: Record = {}): Env { + return { + DB: d1, + KV: new MockKV(), + JWT_SECRET: TEST_JWT_SECRET, + SETUP_SECRET: TEST_SETUP_SECRET, + TABLE_PREFIX: "", + ASSETS: {}, + ...overrides, + } as unknown as Env; +} + +function countRows(d1: SqliteD1, table: string): number { + const row = d1.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { + n: number; + }; + return Number(row.n); +} + +interface CallbackOptions { + executionId?: string; + jobId?: string; + jobName?: string; + scheduledFor?: number; + payload?: unknown; +} + +/** The exact wire body: signatures are computed over this unparsed string. */ +function callbackBody(options: CallbackOptions = {}): string { + return JSON.stringify({ + protocolVersion: 2, + executionId: options.executionId ?? "exec-1", + jobId: options.jobId ?? "job-1", + projectId: "project-1", + jobName: options.jobName ?? WAKER_JOB_NAME, + kind: "cron", + trigger: "schedule", + misfire: false, + attempt: 0, + scheduledFor: options.scheduledFor ?? T0, + dispatchedAt: (options.scheduledFor ?? T0) + 1_000, + timeoutSeconds: 300, + payload: options.payload ?? {}, + }); +} + +async function hmacHex(key: string, message: string): Promise { + const imported = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(key), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const signature = await crypto.subtle.sign( + "HMAC", + imported, + new TextEncoder().encode(message), + ); + return [...new Uint8Array(signature)] + .map((byte) => byte.toString(16).padStart(2, "0")) + .join(""); +} + +async function signedHeaders( + body: string, + options: { + key?: string; + executionId?: string; + jobId?: string; + timestampSeconds?: number; + } = {}, +): Promise> { + const key = options.key ?? TEST_WAKER_KEY; + const executionId = options.executionId ?? "exec-1"; + const jobId = options.jobId ?? "job-1"; + const timestamp = String( + options.timestampSeconds ?? Math.floor(Date.now() / 1000), + ); + const hex = await hmacHex( + key, + `${timestamp}\n${executionId}\n${jobId}\n${body}`, + ); + return { + "Content-Type": "application/json", + "X-Waker-Timestamp": timestamp, + "X-Waker-Execution-Id": executionId, + "X-Waker-Job-Id": jobId, + "X-Waker-Project-Id": "project-1", + "X-Waker-Attempt": "0", + "X-Waker-Signature": `v2=${hex}`, + "X-Waker-Protocol-Version": "2", + }; +} + +async function post( + env: Env, + body: string, + headers: Record, +): Promise<{ status: number; text: string; json: any; contentType: string }> { + const res = await app.request( + CALLBACK_MOUNT_PATH + "/execute", + { method: "POST", headers, body }, + env, + ); + const text = await res.text(); + let json: any = null; + try { + json = JSON.parse(text); + } catch { + json = null; + } + return { + status: res.status, + text, + json, + contentType: res.headers.get("content-type") ?? "", + }; +} + +beforeEach(() => { + handleScheduledMock.mockReset(); + handleScheduledMock.mockImplementation(async () => {}); +}); + +describe("unconfigured signing key", () => { + it("fails closed with 500 JSON and never touches the DB or the business", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); // no WAKER_SIGNING_KEY + + const body = callbackBody(); + const result = await post(env, body, await signedHeaders(body)); + + expect(result.status).toBe(500); + expect(result.json).toEqual({ + ok: false, + error: { + code: "signing_key_missing", + message: expect.stringContaining("WAKER_SIGNING_KEY"), + }, + }); + expect(result.contentType).toContain("application/json"); + expect(handleScheduledMock).not.toHaveBeenCalled(); + expect(countRows(d1, "waker_executions")).toBe(0); + expect(countRows(d1, "scheduler_tick_claims")).toBe(0); + }); + + it("still answers 400 for a request without signature headers", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + + const result = await post(env, callbackBody(), {}); + + expect(result.status).toBe(400); + expect(result.json.error.code).toBe("invalid_request"); + expect(handleScheduledMock).not.toHaveBeenCalled(); + }); + + it("never answers GET with the SPA's 200 HTML", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1); + + const res = await app.request( + CALLBACK_MOUNT_PATH + "/execute", + { method: "GET" }, + env, + ); + const text = await res.text(); + + expect(res.status).toBe(404); + expect(res.headers.get("content-type") ?? "").not.toContain("text/html"); + expect(text).not.toContain(" { + it("accepts a correctly signed callback and runs the sweep once", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const body = callbackBody(); + const result = await post(env, body, await signedHeaders(body)); + + expect(result.status).toBe(200); + expect(result.json).toMatchObject({ + ok: true, + executed: true, + reason: "executed", + tickKey: schedulerTickKey(T0), + }); + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + expect(countRows(d1, "scheduler_tick_claims")).toBe(1); + const ledger = d1.db + .prepare("SELECT execution_id, status FROM waker_executions") + .all() as { execution_id: string; status: string }[]; + expect(ledger).toEqual([{ execution_id: "exec-1", status: "succeeded" }]); + }); + + it("replays a duplicate executionId without re-running the business", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const body = callbackBody({ executionId: "exec-replay" }); + const headers = await signedHeaders(body, { executionId: "exec-replay" }); + const first = await post(env, body, headers); + const second = await post(env, body, headers); + + expect(first.status).toBe(200); + expect(second.status).toBe(200); + expect(second.json).toMatchObject({ + ok: true, + duplicate: true, + executed: true, + reason: "executed", + }); + expect(handleScheduledMock).toHaveBeenCalledTimes(1); + expect(countRows(d1, "scheduler_tick_claims")).toBe(1); + }); + + it("rejects a stale timestamp", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const body = callbackBody(); + const headers = await signedHeaders(body, { + timestampSeconds: Math.floor(Date.now() / 1000) - 400, + }); + const result = await post(env, body, headers); + + expect(result.status).toBe(401); + expect(result.json.error.code).toBe("stale_timestamp"); + expect(handleScheduledMock).not.toHaveBeenCalled(); + expect(countRows(d1, "waker_executions")).toBe(0); + }); + + it("rejects a tampered signature", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const body = callbackBody(); + const headers = await signedHeaders(body); + const signature = headers["X-Waker-Signature"]; + headers["X-Waker-Signature"] = + signature.slice(0, -1) + (signature.endsWith("0") ? "1" : "0"); + const result = await post(env, body, headers); + + expect(result.status).toBe(401); + expect(result.json.error.code).toBe("invalid_signature"); + expect(handleScheduledMock).not.toHaveBeenCalled(); + }); + + it("answers 404 for an undeclared job name", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const body = callbackBody({ jobName: "some-other-job" }); + const headers = await signedHeaders(body); + const result = await post(env, body, headers); + + expect(result.status).toBe(404); + expect(result.json.error.code).toBe("unknown_job"); + expect(handleScheduledMock).not.toHaveBeenCalled(); + }); + + it("does not echo the signing key or the payload in the response", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const body = callbackBody({ payload: { marker: "payload-marker-value" } }); + const result = await post(env, body, await signedHeaders(body)); + + expect(result.status).toBe(200); + expect(result.text).not.toContain(TEST_WAKER_KEY); + expect(result.text).not.toContain("payload-marker-value"); + }); +}); + +describe("cross-entry claim from the callback", () => { + it("reports duplicate_tick and skips the sweep when cron owns the hour", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + d1.db + .prepare( + "INSERT INTO scheduler_tick_claims (tick_key, source, claimed_at) VALUES (?, ?, ?)", + ) + .run(schedulerTickKey(T0), "cron", Date.now()); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + + const body = callbackBody(); + const result = await post(env, body, await signedHeaders(body)); + + expect(result.status).toBe(200); + expect(result.json).toMatchObject({ + ok: true, + executed: false, + reason: "duplicate_tick", + claimedBy: "cron", + tickKey: schedulerTickKey(T0), + }); + expect(handleScheduledMock).not.toHaveBeenCalled(); + }); + + it("releases the executionId and the hour on failure so a retry completes the job", async () => { + const d1 = new SqliteD1(); + applySchemaV3(d1, ""); + const env = makeEnv(d1, { WAKER_SIGNING_KEY: TEST_WAKER_KEY }); + handleScheduledMock.mockRejectedValueOnce(new Error("sweep exploded")); + + const body = callbackBody({ executionId: "exec-retry" }); + const headers = await signedHeaders(body, { executionId: "exec-retry" }); + const failed = await post(env, body, headers); + + expect(failed.status).toBe(500); + expect(failed.json.error.code).toBe("job_failed"); + expect(countRows(d1, "waker_executions")).toBe(0); + expect(countRows(d1, "scheduler_tick_claims")).toBe(0); + + const retry = await post(env, body, headers); + expect(retry.status).toBe(200); + expect(retry.json).toMatchObject({ ok: true, executed: true }); + expect(handleScheduledMock).toHaveBeenCalledTimes(2); + }); +}); diff --git a/worker/test/waker-equivalence.test.ts b/worker/test/waker-equivalence.test.ts new file mode 100644 index 0000000..f2c4e3c --- /dev/null +++ b/worker/test/waker-equivalence.test.ts @@ -0,0 +1,272 @@ +/** + * Acceptance evidence for "business equivalence": the same seeded data swept + * through the native cron entry and through the waker callback must produce the + * same notifications and the same history rows. + * + * This file deliberately does **not** mock the scheduler — both runs go through + * the real `handleScheduled`, so the comparison covers channels, message + * content and history records (`trigger_source` included). + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import worker from "../src/index"; +import type { Env } from "../src/types"; +import { runSetup } from "../src/lib/setup"; +import { CALLBACK_MOUNT_PATH } from "../src/waker"; +import { WAKER_JOB_NAME } from "../src/services/waker-callback"; +import { MockKV, TEST_JWT_SECRET, TEST_SETUP_SECRET } from "./helpers"; +import { SqliteD1 } from "./support/sqlite-d1"; + +const T0 = Date.UTC(2026, 9, 28, 10, 0, 0); +const TEST_WAKER_KEY = "test-waker-signing-key"; + +const htmlAssets = { + fetch: async () => + new Response("", { + status: 200, + headers: { "content-type": "text/html" }, + }), +}; + +/** Fresh env with the real migrated schema (schema_v1..v3) and the same fixture. */ +async function seededEnv( + overrides: Record = {}, +): Promise<{ env: Env; d1: SqliteD1 }> { + const d1 = new SqliteD1(); + const env = { + DB: d1, + KV: new MockKV(), + JWT_SECRET: TEST_JWT_SECRET, + SETUP_SECRET: TEST_SETUP_SECRET, + TABLE_PREFIX: "", + ASSETS: htmlAssets, + ...overrides, + } as unknown as Env; + const setup = await runSetup(env); + expect(setup.success).toBe(true); + + const now = new Date().toISOString(); + const expiry = new Date(Date.now() + 3 * 86_400_000) + .toISOString() + .slice(0, 10); + + d1.db + .prepare( + `INSERT INTO users (id, email, password_hash, timezone, language, is_active, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, 1, ?, ?)`, + ) + .run("user-1", "user@example.com", "hash", "UTC", "en", now, now); + d1.db + .prepare( + `INSERT INTO notification_configs + (user_id, enabled_channels, default_channel, telegram_config, notification_hours, updated_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run( + "user-1", + JSON.stringify(["telegram"]), + "telegram", + JSON.stringify({ bot_token: "token", chat_id: "1" }), + "[]", + now, + ); + d1.db + .prepare( + `INSERT INTO items + (id, user_id, name, item_mode, expiry_date, period_value, period_unit, + reminder_unit, reminder_value, currency, is_active, auto_renew, + calendar_mode, channels, notification_hours, item_kind, created_at, updated_at) + VALUES (?, ?, ?, 'cycle', ?, 1, 'month', 'day', 7, 'CNY', 1, 0, + 'solar', '[]', '[]', 'subscription', ?, ?)`, + ) + .run("item-1", "user-1", "Equivalence item", expiry, now, now); + + return { env, d1 }; +} + +interface HistoryRow { + channel: string; + title: string; + body: string; + success: number; + trigger_source: string | null; +} + +/** Normalize the "sent at" wall clock so two runs in the same minute compare. */ +function normalizeBody(body: string): string { + return body.replace(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/g, "