Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions .github/scripts/test-deploy-checks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
]) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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: <none>/);
} else {
let thrown = null;
try {
Expand Down Expand Up @@ -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/);
});
Expand Down
30 changes: 21 additions & 9 deletions .github/scripts/test-waker-deploy.mjs
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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'/);
Expand Down Expand Up @@ -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 * * * 在场',
);
});
24 changes: 16 additions & 8 deletions .github/scripts/verify-deployment.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down Expand Up @@ -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:-<unset>}'); cannot verify the waker callback state."
Expand Down Expand Up @@ -103,11 +110,12 @@ if [[ "$live" != "$expected" ]]; then
fi
echo "TABLE_PREFIX: ${live:-<none>}"

# 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."
Expand All @@ -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:-<none>}', 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: <none>"
7 changes: 4 additions & 3 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
Expand Down
68 changes: 37 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <none>`; 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)

Expand All @@ -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: <none>`,
`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
Expand Down Expand Up @@ -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. |

---

Expand Down
Loading
Loading