diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index beadc7b..d3fd6a8 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -282,14 +282,14 @@ for (const scenario of [ ok: true, }, { - // 原生 Cron Trigger 丢了等于清理停摆,必须失败(与 key 无关)。 - name: 'schedules 为空 → 必须失败', + // 原生 Cron Trigger 还在 = 仍是双跑,切换没生效,必须失败(与 key 无关)。 + name: '仍残留原生 cron 0 3 * * * → 必须失败', version: 'uploaded', percentage: 100, prefix: 'hop', env: 'hop', - schedulesEmpty: true, - expectError: "expected exactly '0 3 \\* \\* \\*'", + schedulesLeftover: true, + expectError: 'expected no cron schedules', ok: false, }, ]) { @@ -325,9 +325,9 @@ esac join(f.dir, 'wrangler.toml'), 'name = "hop"\naccount_id = "0123456789abcdef0123456789abcdef"\n', ); - const schedulesBody = scenario.schedulesEmpty - ? '{"success":true,"result":{"schedules":[]}}' - : '{"success":true,"result":{"schedules":[{"cron":"0 3 * * *"}]}}'; + const schedulesBody = scenario.schedulesLeftover + ? '{"success":true,"result":{"schedules":[{"cron":"0 3 * * *"}]}}' + : '{"success":true,"result":{"schedules":[]}}'; writeFileSync( join(f.dir, 'curl'), `#!/bin/sh @@ -366,7 +366,7 @@ printf '%s\\n' '${schedulesBody}' /no WAKER_SIGNING_KEY configured — .*fails closed/, ); } - assert.match(stdout, /Cron schedules: 0 3 \* \* \*/); + assert.match(stdout, /Cron schedules: /); } else { let thrown = null; try { @@ -512,9 +512,10 @@ for (const scenario of [ toml, new RegExp(`^TABLE_PREFIX = "${scenario.expected}"$`, 'm'), ); - // 部署产物仍带 [triggers]:原生 Cron Trigger 静态保留,流水线不摘它。 + // 部署产物里 [triggers] crons = []:每次部署都清掉原生 Cron Trigger。 assert.match(toml, /^\[triggers\]$/m); - assert.match(toml, /^crons = \["0 3 \* \* \*"\]$/m); + assert.match(toml, /^crons = \[\]$/m); + assert.doesNotMatch(toml, /0 3 \* \* \*/); // 残留检查(Inject 步的 grep)通过:所有占位符都已替换。 assert.doesNotMatch(toml, /_PLACEHOLDER/); }); diff --git a/.github/scripts/test-waker-deploy.mjs b/.github/scripts/test-waker-deploy.mjs index fc4c20e..9728cbb 100644 --- a/.github/scripts/test-waker-deploy.mjs +++ b/.github/scripts/test-waker-deploy.mjs @@ -1,5 +1,6 @@ -// Static invariants of the simplified waker wiring: the scheduling config is -// static, the signing key is the only switch, and no deployment variable from +// Static invariants of the simplified waker wiring: waker is the only scheduler +// (wrangler.toml declares `crons = []` so every deploy clears the native Cron +// Trigger), the signing key is the only switch, and no deployment variable from // the old dual-mode design survived anywhere in the pipeline. // // Run from the repository root: @@ -39,18 +40,24 @@ function pipelineFiles(dir = join(repoRoot, '.github')) { return files; } -// ─── [triggers] is static: the native Cron Trigger is always deployed ──────── +// ─── native cron removed: waker is the only scheduler ──────────────────────── -test('wrangler.toml 的 [triggers] 静态保留,全仓唯一 cron 表达式仍是 0 3 * * *', () => { +test('wrangler.toml 声明 [triggers] crons = [],唯一调度在 waker', () => { assert.match(wranglerToml, /^\[triggers\]$/m); - assert.match(wranglerToml, /^crons = \["0 3 \* \* \*"\]$/m); + // 空数组才会删掉已部署的 Cron Trigger;整段删除会让旧调度原样跑着。 + assert.match(wranglerToml, /^crons = \[\]$/m); assert.equal( (wranglerToml.match(/^crons\s*=/gm) ?? []).length, 1, '只允许一条 crons 声明', ); + assert.doesNotMatch( + wranglerToml, + /0 3 \* \* \*/, + 'wrangler.toml 不得再声明任何 cron 表达式', + ); - // 任务名与表达式与 waker 管理面注册的参数逐字一致。 + // 全仓唯一的调度声明:任务名与表达式与 waker 管理面注册的参数逐字一致。 const service = read('apps', 'worker', 'src', 'services', 'waker.ts'); assert.match(service, /WAKER_JOB_CRON = '0 3 \* \* \*'/); assert.match(service, /WAKER_JOB_NIGHTLY_CLEANUP = 'nightly-cleanup'/); @@ -150,12 +157,17 @@ test('deploy.yml:secrets 文件步可选注入 key,并把解析状态交给 assert.ok(at('Deploy') < at('Verify deployment')); }); -test('verify-deployment.sh:无模式变量,cron 排期恒为 0 3 * * *', () => { +test('verify-deployment.sh:无模式变量,排期闸门要求零 cron', () => { assert.doesNotMatch(verifyScript, /WAKER_MODE|WAKER_TRIGGERS/); assert.match(verifyScript, /WAKER_SIGNING_KEY_EXPECTED/); assert.match( verifyScript, - /expected exactly '0 3 \* \* \*'/, - '排期闸门必须要求原生 Cron Trigger 在场', + /expected no cron schedules/, + '排期闸门必须要求原生 Cron Trigger 已移除(waker 是唯一调度)', + ); + assert.doesNotMatch( + verifyScript, + /expected exactly '0 3/, + '闸门不得再要求 0 3 * * * 在场', ); }); diff --git a/.github/scripts/verify-deployment.sh b/.github/scripts/verify-deployment.sh index 384cf3e..f557394 100644 --- a/.github/scripts/verify-deployment.sh +++ b/.github/scripts/verify-deployment.sh @@ -15,9 +15,15 @@ # without it only fails at 03:00 with 500 # signing_key_missing); 'absent' just records that # the receiver fails closed. No mode variable. +# Waker is the only scheduler now, so 'absent' also +# warns that no cleanup runs at all. # WORKER_NAME — optional, Worker name for the version lookup # (default 'hop', the name in wrangler.toml) # CLOUDFLARE_API_TOKEN — needed for the schedules lookup. +# +# The last gate asserts the Worker carries no native Cron Trigger at all: since +# the switch, waker delivers the nightly cleanup over HTTP and the native +# schedule must be gone (wrangler.toml declares `crons = []`). set -euo pipefail here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -58,6 +64,7 @@ case "${WAKER_SIGNING_KEY_EXPECTED:-}" in ;; absent) echo "Waker callback: no WAKER_SIGNING_KEY configured — /_waker/execute fails closed (500 signing_key_missing)" + echo "::warning::Waker is the only scheduler and no WAKER_SIGNING_KEY is configured: the nightly cleanup will NOT run at all until the GitHub Secret exists and a deployment injects it." ;; *) echo "::error::WAKER_SIGNING_KEY_EXPECTED must be 'bound' or 'absent' (got '${WAKER_SIGNING_KEY_EXPECTED:-}'); cannot verify the waker callback state." @@ -103,11 +110,12 @@ if [[ "$live" != "$expected" ]]; then fi echo "TABLE_PREFIX: ${live:-}" -# Cron schedules gate. `wrangler deploy` syncs cron schedules from the config, -# and `[triggers]` is static in wrangler.toml — the pipeline never rewrites it, so -# the native Cron Trigger must always be there. Moving the schedule to waker alone -# is a separate change that deletes [triggers]; once merged, this gate fails until -# it is updated along with that change, which is exactly the review it asks for. +# Cron schedules gate: none may remain. `wrangler deploy` replaces the deployed +# schedules with those in the config, and `[triggers] crons = []` in wrangler.toml +# therefore removes the native Cron Trigger on every deploy (an absent section +# would leave the already-deployed schedule in place). Waker is the only +# scheduler, so a leftover schedule means the switch did not take effect and the +# Worker would keep running a second, unmanaged nightly cleanup. account_id="$(sed -n 's/^account_id[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' wrangler.toml | head -n 1)" if [[ -z "$account_id" ]]; then echo "::error::Cannot read account_id from wrangler.toml; cannot verify cron schedules." @@ -126,8 +134,8 @@ if ! jq -e '.success == true and (.result.schedules | type == "array")' \ exit 1 fi crons="$(jq -r '[.result.schedules[].cron] | sort | join(" ")' <<<"$schedules")" -if [[ "$crons" != "0 3 * * *" ]]; then - echo "::error::Worker ${worker_name} has cron schedule(s) '${crons:-}', expected exactly '0 3 * * *'. The native Cron Trigger lives in wrangler.toml's static [triggers] section and must stay deployed (waker is a parallel trigger, not a replacement, until [triggers] is removed in a dedicated change)." +if [[ -n "$crons" ]]; then + echo "::error::Worker ${worker_name} still has cron schedule(s) '${crons}', expected no cron schedules. Waker is the only scheduler now and wrangler.toml declares [triggers] crons = [] so every deploy removes the native Cron Trigger. Remove the leftover schedule (dashboard → Triggers → delete the Cron Trigger, or PUT /accounts/${account_id}/workers/scripts/${worker_name}/schedules with an empty array) and re-run the deploy." exit 1 fi -echo "Cron schedules: 0 3 * * *" +echo "Cron schedules: " diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 1136815..682547f 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -142,7 +142,8 @@ jobs: # does not, the deploy still succeeds and /_waker/execute fails closed with # 500 signing_key_missing. The resolved state is handed to the verify step # so a version that was supposed to carry the key cannot silently ship - # without it. + # without it. Waker delivers the nightly cleanup, so an absent key means + # that nothing runs it — the verify step warns about exactly that. - name: Write secrets file id: secrets env: @@ -169,12 +170,12 @@ jobs: }; // The signing key is the only switch of the callback: injected when // the repository Secret exists, otherwise the callback answers 500 - // signing_key_missing and the native Cron Trigger is unaffected. + // signing_key_missing and nothing schedules the nightly cleanup. const key = (process.env.WAKER_SIGNING_KEY ?? "").trim(); if (key.length > 0) { secrets.WAKER_SIGNING_KEY = key; } else { - console.warn("WAKER_SIGNING_KEY is not configured — /_waker/execute will answer 500 signing_key_missing until it is set; the native Cron Trigger is unaffected."); + console.warn("WAKER_SIGNING_KEY is not configured — /_waker/execute will answer 500 signing_key_missing until it is set, and nothing else schedules the nightly cleanup."); } fs.writeFileSync( file, diff --git a/README.md b/README.md index f8d037b..e370904 100644 --- a/README.md +++ b/README.md @@ -195,32 +195,35 @@ Navigate to your deployed URL and register — the first account is automaticall --- -## Optional: also schedule with waker (dual run) +## Nightly cleanup: scheduled by waker -Hop's nightly cleanup (expired `verifications` rows, plus `totp_used` rows older than 90 s) runs -on the Cloudflare Cron Trigger `0 3 * * *` declared in `apps/worker/wrangler.toml`. A deployment -can also let [waker](https://github.com/WorkerHub/waker) deliver the same job over HTTP: the -platform POSTs `/_waker/execute`, which runs the **same** cleanup function as `scheduled()`. +Hop's nightly cleanup (expired `verifications` rows, plus `totp_used` rows older than 90 s) is +delivered by [waker](https://github.com/WorkerHub/waker): the platform POSTs `/_waker/execute`, +which runs the **same** cleanup function as the `scheduled()` handler. The Worker deploys no native +Cron Trigger — waker is the only scheduler. There is nothing to switch on: one input decides everything — the signing key. | `WAKER_SIGNING_KEY` | `/_waker/execute` | Native Cron Trigger | State | |---|---|---|---| -| Secret absent (or empty) | 500 `signing_key_missing` (JSON) | `0 3 * * *` | fail closed — nothing unverified ever runs | -| Secret present | signature verified, then the cleanup runs | `0 3 * * *` | dual run; the cleanup is idempotent | - -`[triggers]` is static: it lives in `apps/worker/wrangler.toml` and the pipeline never rewrites it, -so the native trigger is deployed in both states. There is no mode variable, platform URL or -schedule switch to configure — the deployment variables from the earlier dual-mode design are gone; -if your repository still has them, they are ignored and can be deleted. Any path under `/_waker` -that is not routed answers JSON (404 or the SDK's stable error code) — never the SPA's 200 HTML, -which waker would read as a successful run. +| Secret absent (or empty) | 500 `signing_key_missing` (JSON) | none | fail closed — and since nothing else schedules the job, the cleanup does not run at all | +| Secret present | signature verified, then the cleanup runs | none | waker alone drives the nightly cleanup | + +`apps/worker/wrangler.toml` declares `[triggers]` with `crons = []`, and that empty array is what +removes the native trigger: Cloudflare deletes all Cron Triggers only when `crons` is empty — with +the property undefined (an absent section) the already-deployed schedule would stay in place and +the Worker would keep a second, unmanaged nightly cleanup. The deployment workflow verifies the +result after every deploy (`Cron schedules: `; a leftover schedule fails the run). There is +no mode variable, platform URL or schedule switch to configure — the deployment variables from the +earlier dual-mode design are gone; if your repository still has them, they are ignored and can be +deleted. Any path under `/_waker` that is not routed answers JSON (404 or the SDK's stable error +code) — never the SPA's 200 HTML, which waker would read as a successful run. ### The only input: `WAKER_SIGNING_KEY` | Secret | Required | Source | Description | |---|---|---|---| -| `WAKER_SIGNING_KEY` | No | GitHub Secret → CI | The hop project's callback signing key, shown **once** when the project is created in the waker UI. When the Secret exists the deploy injects it through `--secrets-file`; when it does not, the deploy still succeeds and the callback answers 500 `signing_key_missing` instead of running an unverified job. Never logged, never committed. | +| `WAKER_SIGNING_KEY` | No | GitHub Secret → CI | The hop project's callback signing key, shown **once** when the project is created in the waker UI. When the Secret exists the deploy injects it through `--secrets-file` and the callback verifies and runs the cleanup; when it does not, the deploy still succeeds and the callback answers 500 `signing_key_missing` instead of running an unverified job — with no native trigger left, nothing runs the cleanup in that state. Never logged, never committed. | ### Create the waker job (once, in the waker UI) @@ -237,26 +240,29 @@ job — these values are frozen, copy them verbatim (the job name must match the | `maxRetries` / `backoffSeconds` | `2` / `60` | | `timeoutSeconds` / `jitterSeconds` | `30` / `0` | -### Dual run, switching to waker alone, and rolling back +### Setting it up, checking it, and rolling back 1. Create the `hop` project in waker (callback URL = this Worker's public base URL) and store the signing key it shows once as the GitHub Secret `WAKER_SIGNING_KEY` (same path as the other - runtime secrets — never in the repository). Deploy: the receiver is live next to the Cron - Trigger — the dual-run state, harmless because the cleanup is idempotent. + runtime secrets — never in the repository). Deploy: the receiver goes live with it. 2. Create and enable the `nightly-cleanup` job in waker, then watch one full daily cycle: waker's executions list shows a success, and the Worker log has - `"event":"nightly_cleanup","source":"waker"` with the delete counts and duration. -3. Switch over in a separate, small change: delete the `[triggers]` section from - `apps/worker/wrangler.toml` and merge it on its own. waker is then the only scheduler; nothing - else has to change. - -Rollback: revert that commit (the `[triggers]` section comes back) and redeploy — the Cron Trigger -is back, and waker can keep delivering in parallel or be paused in its UI. No database rollback is -needed: `schema_v3` only adds `{prefix}waker_executions`, which nothing else reads. - -To close the callback instead, delete the Worker's `WAKER_SIGNING_KEY` secret in the dashboard (the -deploy only ever adds secrets, it never removes one): `/_waker/execute` then answers 500 -`signing_key_missing`. Leaving the key bound is harmless as long as the waker job is paused. + `"event":"nightly_cleanup","source":"waker"` with the delete counts and duration. With the + native trigger gone, only `source: "waker"` entries appear from then on. +3. Check the switch took effect: the deploy's Verify step prints `Cron schedules: `, + `GET /accounts/{account_id}/workers/scripts/hop/schedules` returns an empty list, and the + Worker's Triggers tab in the dashboard lists no Cron Trigger. + +Rollback: put the expression back in `apps/worker/wrangler.toml` +(`[triggers] crons = ["0 3 * * *"]`) and redeploy — `wrangler deploy` replaces the deployed +schedules with the config, so the native trigger returns, and waker can keep delivering in +parallel or be paused in its UI. No database rollback is needed: `schema_v3` only adds +`{prefix}waker_executions`, which nothing else reads. + +To close the callback instead, pause or delete the `nightly-cleanup` job in the waker UI first — +having deleted the Worker's `WAKER_SIGNING_KEY` secret in the dashboard (the deploy only ever adds +secrets, it never removes one) `/_waker/execute` answers 500 `signing_key_missing`, and with no +native trigger left that stops the cleanup completely. Cleanup results are logged as structured JSON (`nightly_cleanup` with counts, duration and the trigger source; rejected callbacks as `waker_callback_rejected` with the HTTP status and the @@ -403,7 +409,7 @@ GET /:slug → 302 to destination URL | `JWT_SECRET` | Secret | Yes | GitHub Secret → CI | HS256 signing key, ≥ 32 chars | | `TOTP_ENCRYPTION_KEY` | Secret | Yes | GitHub Secret → CI | Hex string from `openssl rand -hex 32` | | `SETUP_SECRET` | Secret | Yes | GitHub Secret → CI | Secret path for triggering DB migrations via HTTP | -| `WAKER_SIGNING_KEY` | Secret | No | GitHub Secret → CI | The hop project's callback signing key, shown once when the project is created in waker. Present → the deploy injects it and `/_waker/execute` verifies and runs the cleanup; absent → the deploy still succeeds and the callback answers 500 `signing_key_missing`. See [Optional: also schedule with waker](#optional-also-schedule-with-waker-dual-run). Never logged or committed. | +| `WAKER_SIGNING_KEY` | Secret | No | GitHub Secret → CI | The hop project's callback signing key, shown once when the project is created in waker. Present → the deploy injects it and `/_waker/execute` verifies and runs the cleanup; absent → the deploy still succeeds and the callback answers 500 `signing_key_missing`. See [Nightly cleanup: scheduled by waker](#nightly-cleanup-scheduled-by-waker). Never logged or committed. | --- diff --git a/README.zh-CN.md b/README.zh-CN.md index eff1d4d..0bdcb0b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -176,30 +176,32 @@ curl -X POST https://your-worker.workers.dev/api/setup \ --- -## 可选:同时用 waker 调度(双跑) +## 夜间清理:由 waker 独驱动 hop 的每日清理(过期 `verifications` 行 + 超过 90 秒的 `totp_used` 行)由 -`apps/worker/wrangler.toml` 里的 Cloudflare Cron Trigger `0 3 * * *` 驱动。部署也可以让 -[waker](https://github.com/WorkerHub/waker) 通过 HTTP 投递同一份任务:平台回调 -`POST /_waker/execute`,执行的是与 `scheduled()` **同一个**清理函数。 +[waker](https://github.com/WorkerHub/waker) 投递:平台回调 `POST /_waker/execute`,执行的是与 +`scheduled()` **同一个**清理函数。Worker **不再部署原生 Cron Trigger**——waker 是唯一的调度源。 没有开关要配,只认一把签名密钥: | `WAKER_SIGNING_KEY` | `/_waker/execute` | 原生 Cron Trigger | 状态 | |---|---|---|---| -| 未配置(或为空) | 500 `signing_key_missing`(JSON) | `0 3 * * *` | fail closed —— 绝不执行未验签的任务 | -| 已配置 | 验签通过后执行清理 | `0 3 * * *` | 双跑;清理天然幂等 | +| 未配置(或为空) | 500 `signing_key_missing`(JSON) | 无 | fail closed —— 且因为再没有别的调度源,清理根本不会跑 | +| 已配置 | 验签通过后执行清理 | 无 | 夜间清理由 waker 独驱动 | -`[triggers]` 是静态的:它写在 `apps/worker/wrangler.toml` 里、流水线从不改写,所以两种状态下 -原生 Cron Trigger 都会部署。没有模式变量、没有平台地址、没有调度开关要配——旧版双模式的那些部署 -变量已经删除,仓库里若还留着也会被代码忽略,可以一并删掉。`/_waker` 下任何未挂载的路径都回 JSON -(404 或 SDK 的稳定错误码),永远不会落到 SPA 的 200 HTML(否则平台会把「没跑」当成「跑成功」)。 +`apps/worker/wrangler.toml` 里声明的是 `[triggers]` + `crons = []`,这个空数组才是移除动作: +Cloudflare 只在 `crons` 为空数组时删掉全部 Cron Trigger;属性为 undefined(即整段删掉)时已部署的 +调度会**原样留着**,Worker 就会继续跑第二份不受管理的夜间清理。每次部署后流水线都会核对结果 +(`Cron schedules: `;仍读到调度则部署失败)。没有模式变量、没有平台地址、没有调度开关要配 +——旧版双模式的那些部署变量已经删除,仓库里若还留着也会被代码忽略,可以一并删掉。`/_waker` 下 +任何未挂载的路径都回 JSON(404 或 SDK 的稳定错误码),永远不会落到 SPA 的 200 HTML(否则平台会把 +「没跑」当成「跑成功」)。 ### 唯一的输入:`WAKER_SIGNING_KEY` | 密钥 | 必填 | 来源 | 描述 | |---|---|---|---| -| `WAKER_SIGNING_KEY` | 否 | GitHub Secret → CI | hop 项目的回调签名密钥,在 waker 管理面建项目时**一次性**展示。仓库里有这个 Secret 时,部署经 `--secrets-file` 注入;没有时部署照样成功,只是回调回 500 `signing_key_missing`,绝不执行未验签的任务。永不进日志、永不进仓库。 | +| `WAKER_SIGNING_KEY` | 否 | GitHub Secret → CI | hop 项目的回调签名密钥,在 waker 管理面建项目时**一次性**展示。仓库里有这个 Secret 时,部署经 `--secrets-file` 注入,回调验签后执行清理;没有时部署照样成功,只是回调回 500 `signing_key_missing`,绝不执行未验签的任务——而原生 Cron Trigger 已经没有了,这个状态下清理不会跑。永不进日志、永不进仓库。 | ### 在 waker 管理面建任务(一次) @@ -216,22 +218,26 @@ hop 的每日清理(过期 `verifications` 行 + 超过 90 秒的 `totp_used` | `maxRetries` / `backoffSeconds` | `2` / `60` | | `timeoutSeconds` / `jitterSeconds` | `30` / `0` | -### 双跑、切到只跑 waker、以及回滚 +### 接上、核对、以及回滚 1. 在 waker 建 `hop` 项目(回调地址填本 Worker 的公网根地址),把一次性展示的 signing key 存进 GitHub Secret `WAKER_SIGNING_KEY`(与现有运行时密钥同路,绝不进仓库)后部署:receiver - 就此上线,Cron Trigger 继续跑——这就是双跑态,清理幂等,重复执行无副作用。 + 就此上线。 2. 在 waker 建并启用 `nightly-cleanup` 任务,观察一个完整日周期:waker 的执行记录有成功条目, - Worker 日志出现 `"event":"nightly_cleanup","source":"waker"` 及删除计数与耗时。 -3. 切换放在单独一个小变更里:删除 `apps/worker/wrangler.toml` 的 `[triggers]` 段,单独提 PR 合并。 - 之后 waker 是唯一调度源,其余什么都不用改。 + Worker 日志出现 `"event":"nightly_cleanup","source":"waker"` 及删除计数与耗时。原生触发已移除, + 此后只会出现 `source: "waker"` 的记录。 +3. 核对切换已生效:部署的 Verify 步输出 `Cron schedules: `, + `GET /accounts/{account_id}/workers/scripts/hop/schedules` 返回空列表,控制台该 Worker 的 + Triggers 下也没有 Cron Trigger。 -回滚:还原那个提交(`[triggers]` 段回来)重新部署即可——Cron Trigger 恢复,waker 可以继续并行 -投递,也可以在管理面停用任务。数据库无需回滚:`schema_v3` 只加法创建 `{prefix}waker_executions`, -没有别的代码读它。 +回滚:把表达式写回 `apps/worker/wrangler.toml`(`[triggers] crons = ["0 3 * * *"]`)重新部署即可 +——`wrangler deploy` 会用配置替换已部署的调度,原生触发恢复,waker 可以继续并行投递,也可以在 +管理面停用任务。数据库无需回滚:`schema_v3` 只加法创建 `{prefix}waker_executions`,没有别的代码 +读它。 -若只想关掉回调:在控制台删掉 Worker 的 `WAKER_SIGNING_KEY` 密钥(部署只会新增密钥、从不删除), -`/_waker/execute` 随后回 500 `signing_key_missing`;任务已停用时留着这把密钥也无影响。 +若只想关掉回调:先在 waker 管理面停用或删除 `nightly-cleanup` 任务——在控制台删掉 Worker 的 +`WAKER_SIGNING_KEY` 密钥后(部署只会新增密钥、从不删除),`/_waker/execute` 回 500 +`signing_key_missing`;原生触发已经没有了,这个阶段清理就是完全停的。 清理结果以结构化 JSON 记录(`nightly_cleanup` 含计数、耗时与触发来源;被拒回调记 `waker_callback_rejected`,含 HTTP 状态与 SDK 错误码,如 `invalid_signature`、 @@ -376,7 +382,7 @@ GET /:slug → 302 跳转到目标 URL | `JWT_SECRET` | 密钥 | 是 | GitHub Secret → CI | HS256 签名密钥,≥ 32 字符 | | `TOTP_ENCRYPTION_KEY` | 密钥 | 是 | GitHub Secret → CI | 来自 `openssl rand -hex 32` 的十六进制字符串 | | `SETUP_SECRET` | 密钥 | 是 | GitHub Secret → CI | 通过 HTTP 触发数据库迁移的密钥路径 | -| `WAKER_SIGNING_KEY` | 密钥 | 否 | GitHub Secret → CI | hop 项目的回调签名密钥,建项目时一次性展示。有值 → 部署注入,`/_waker/execute` 验签后执行清理;无值 → 部署照常成功,回调回 500 `signing_key_missing`。见 [可选:同时用 waker 调度](#可选同时用-waker-调度双跑)。不进日志、不进仓库。 | +| `WAKER_SIGNING_KEY` | 密钥 | 否 | GitHub Secret → CI | hop 项目的回调签名密钥,建项目时一次性展示。有值 → 部署注入,`/_waker/execute` 验签后执行清理;无值 → 部署照常成功,回调回 500 `signing_key_missing`。见 [夜间清理:由 waker 独驱动](#夜间清理由-waker-独驱动)。不进日志、不进仓库。 | --- diff --git a/apps/worker/.dev.vars.example b/apps/worker/.dev.vars.example index 6625e69..e898363 100644 --- a/apps/worker/.dev.vars.example +++ b/apps/worker/.dev.vars.example @@ -22,10 +22,11 @@ JWT_SECRET= TOTP_ENCRYPTION_KEY= SETUP_SECRET= -# ─── Optional waker integration ─────────────────────────────────────────────── -# The native Cron Trigger is the default and always on. The waker callback is -# switched by the signing key alone: with WAKER_SIGNING_KEY set here, a locally -# signed POST to /_waker/execute verifies and runs the same cleanup; without it -# the callback fails closed with 500 signing_key_missing. Use a locally generated -# test key — never the production one. +# ─── Waker integration (the nightly cleanup's only scheduler) ───────────────── +# Production scheduling is delivered by waker (POST /_waker/execute); the Worker +# no longer deploys a native Cron Trigger, so nothing fires the cleanup on a +# timer here either. The callback is switched by the signing key alone: with +# WAKER_SIGNING_KEY set, a locally signed POST to /_waker/execute verifies and +# runs the same cleanup; without it the callback fails closed with 500 +# signing_key_missing. Use a locally generated test key — never the production one. # WAKER_SIGNING_KEY= diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 7433679..719c12a 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -123,13 +123,15 @@ app.all('/api/*', (c) => { return apiError(c, 404, 'NOT_FOUND', 'Not found'); }); -// ─── waker callback (optional second trigger, dual run) ─────────────────────── +// ─── waker callback (the scheduler) ────────────────────────────────────────── // Registered before the short-link route and the SPA fallback so the whole // /_waker prefix is decided here. The sub-app hands POST /_waker/execute to the // SDK receiver; whether it actually runs is decided by one thing only — the // signing key binding (present: verify + run the same cleanup as scheduled(); // absent: 500 signing_key_missing). Every path under the prefix answers JSON, // never the SPA's 200 HTML, which waker would mistake for a successful run. +// This is the only scheduler: wrangler.toml declares `[triggers] crons = []`, +// which removes the native Cron Trigger on every deploy. app.all(CALLBACK_MOUNT_PATH, (c) => { return apiError(c, 404, 'NOT_FOUND', 'Not found'); }); @@ -176,9 +178,12 @@ export { app }; export default { fetch: app.fetch, - // L-2: Nightly cleanup of expired rows (native Cron Trigger "0 3 * * *", - // static in wrangler.toml; the waker callback runs the same runCleanup through - // /_waker/execute while its signing key is bound — the dual-run state). + // L-2: Nightly cleanup of expired rows. The schedule is delivered by waker + // (POST /_waker/execute → the same runCleanup), and wrangler.toml declares + // `[triggers] crons = []`, so no native Cron Trigger is deployed. The handler + // stays exported on purpose: restoring `crons = ["0 3 * * *"]` and + // redeploying brings the native path back without touching code (the rollback + // documented in the README). async scheduled( _event: ScheduledController, env: Env, diff --git a/apps/worker/src/services/waker.ts b/apps/worker/src/services/waker.ts index e4bc631..4050717 100644 --- a/apps/worker/src/services/waker.ts +++ b/apps/worker/src/services/waker.ts @@ -26,10 +26,11 @@ import { runCleanup } from './cleanup.js'; export const WAKER_JOB_NIGHTLY_CLEANUP = 'nightly-cleanup'; /** - * The declarative cron expression, character-for-character what - * apps/worker/wrangler.toml declares for the native trigger (CF dialect, UTC). - * The waker job is created by hand with this expression, so it is also the - * value to copy there; nothing in hop rewrites it. + * The declarative cron expression of the nightly cleanup — the only schedule hop + * has left. The job is created by hand in the waker UI with this value (CF cron + * dialect, UTC), so it is also what the README's job table freezes; nothing in + * hop rewrites it. wrangler.toml declares `[triggers] crons = []`, which removes + * the native Cron Trigger on every deploy — waker is the only scheduler. */ export const WAKER_JOB_CRON = '0 3 * * *'; diff --git a/apps/worker/wrangler.toml b/apps/worker/wrangler.toml index cead569..3459553 100644 --- a/apps/worker/wrangler.toml +++ b/apps/worker/wrangler.toml @@ -28,10 +28,14 @@ binding = "LINKS_KV" id = "KV_NAMESPACE_ID_PLACEHOLDER" [triggers] -# Native Cron Trigger — static: this section is always deployed and the pipeline -# never rewrites it. The waker callback runs next to it (dual run, the cleanup is -# idempotent) as soon as its signing key is bound; switching the schedule over to -# waker alone is a separate, reviewable change that deletes this section (revert -# that commit to roll back). Keep the expression character-for-character: the -# waker job is created with the same value. -crons = ["0 3 * * *"] +# Native Cron Trigger disabled — waker is the only scheduler now: it POSTs +# /_waker/execute for the `nightly-cleanup` job declared in +# src/services/waker.ts and created by hand in the waker UI. +# +# The empty array is what removes it, on every deploy: Cloudflare deletes all +# Cron Triggers when `crons` is an empty array, but leaves the deployed ones in +# place when `triggers`/`crons` is undefined (i.e. deleting this section would +# keep the old schedule running). Keeping it explicit also makes the state +# idempotent and reviewable. Rollback: restore the previous expression (see the +# README's waker section) and redeploy — the native trigger returns. +crons = []