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
178 changes: 178 additions & 0 deletions .github/scripts/configure-waker-mode.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// Deploy-time configuration of the optional waker mode.
//
// The deploy workflow runs this after the resource-ID injection step and before
// the build, so the uploaded version is configured exactly as the GitHub
// variables say:
//
// WAKER_MODE=cron (default) native CF Cron Trigger — `[triggers]` stays,
// WAKER_MODE="cron" is written explicitly (keep_vars=true
// would otherwise leave a previous `waker` value alive),
// no WAKER_URL, no WAKER_SIGNING_KEY is injected.
// WAKER_MODE=waker waker callback mode — WAKER_MODE="waker" and WAKER_URL
// are written. `[triggers]` is removed only with an
// explicit WAKER_TRIGGERS=remove (the switch action);
// the default `keep` is the dual-run state: receiver on,
// native trigger still firing.
//
// Nothing secret is read or written here: WAKER_URL is plain configuration and
// WAKER_SIGNING_KEY never appears in wrangler.toml (the workflow puts it in the
// --secrets-file only).
//
// Usage (from the repository root):
// node .github/scripts/configure-waker-mode.mjs
// Env: WAKER_MODE (cron|waker), WAKER_URL, WAKER_TRIGGERS (keep|remove, keep by
// default), WRANGLER_TOML (optional path override), GITHUB_OUTPUT.
//
// Prints `mode=…` / `triggers=…` to $GITHUB_OUTPUT for later workflow steps.

import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';

const DEFAULT_TOML = 'apps/worker/wrangler.toml';

function fail(message) {
console.error(`::error::${message}`);
process.exit(1);
}

function readEnum(name, raw, allowed, fallback) {
const value = (raw ?? '').trim().toLowerCase();
if (value === '') return fallback;
if (!allowed.includes(value)) {
fail(
`${name}=${JSON.stringify(raw)} is invalid; expected one of: ${allowed.join(', ')}`,
);
}
return value;
}

const mode = readEnum(
'WAKER_MODE',
process.env.WAKER_MODE,
['cron', 'waker'],
'cron',
);
const triggers = readEnum(
'WAKER_TRIGGERS',
process.env.WAKER_TRIGGERS,
['keep', 'remove'],
'keep',
);

// A cron-mode deploy that removes the native triggers would leave the app with
// no scheduler at all. Refuse instead of silently deploying that state.
if (mode === 'cron' && triggers === 'remove') {
fail(
'WAKER_MODE=cron with WAKER_TRIGGERS=remove would leave the app without any scheduler; ' +
'use WAKER_MODE=waker to remove [triggers], or WAKER_TRIGGERS=keep.',
);
}

let url = '';
if (mode === 'waker') {
url = (process.env.WAKER_URL ?? '').trim().replace(/\/+$/, '');
if (url === '') {
fail(
'WAKER_MODE=waker requires WAKER_URL (the platform base URL, e.g. https://waker.oneboy.app). ' +
'It is plain configuration: set it as a GitHub variable.',
);
}
if (!/^https?:\/\/[^\s"'\\]+$/.test(url)) {
fail(
`WAKER_URL=${JSON.stringify(process.env.WAKER_URL)} is not a plain http(s) URL; ` +
'it must not contain whitespace, quotes or backslashes.',
);
}
}

const tomlPath = process.env.WRANGLER_TOML ?? DEFAULT_TOML;
let toml;
try {
toml = readFileSync(tomlPath, 'utf8');
} catch (error) {
fail(`cannot read ${tomlPath}: ${error.message}`);
}

// ─── [triggers] ──────────────────────────────────────────────────────────────

function hasTriggers(text) {
return (
/^\[triggers\]\s*$/m.test(text) && /^crons\s*=\s*\[.*\]\s*$/m.test(text)
);
}

function stripTriggers(text) {
// The [triggers] block is the last table in hop's wrangler.toml. Header and
// body (comments included) are dropped; a table header that follows (if one
// is ever added) is kept, along with everything after it.
const out = [];
let inTriggers = false;
for (const line of text.split('\n')) {
if (/^\s*\[triggers\]\s*$/.test(line)) {
inTriggers = true;
continue;
}
if (inTriggers) {
// The block ends at the next table header; blank lines and comments that
// belonged to it are dropped with it.
if (/^\s*\[/.test(line)) {
inTriggers = false;
out.push(line);
}
continue;
}
out.push(line);
}
while (out.length > 0 && out[out.length - 1] === '') out.pop();
return `${out.join('\n')}\n`;
}

if (triggers === 'keep') {
if (!hasTriggers(toml)) {
fail(
`${tomlPath} has no [triggers] block with a crons entry, but WAKER_TRIGGERS=keep ` +
'requires the native Cron Trigger to stay. Restore the section in the repository.',
);
}
} else {
toml = stripTriggers(toml);
}

// ─── [vars] ──────────────────────────────────────────────────────────────────
// Managed entries are rewritten on every run so a value from an earlier mode
// can never survive inside the file itself. (keep_vars=true in wrangler.toml is
// why WAKER_MODE must always be written, even in cron mode.)

if (!/^\[vars\]\s*$/m.test(toml)) {
fail(`${tomlPath} has no [vars] section to write WAKER_MODE into.`);
}

toml = toml
.replace(/^WAKER_MODE\s*=.*\n/gm, '')
.replace(/^WAKER_URL\s*=.*\n/gm, '');

const managed = [`WAKER_MODE = "${mode}"`];
if (mode === 'waker') managed.push(`WAKER_URL = "${url}"`);
toml = toml.replace(/^\[vars\]\s*$/m, `[vars]\n${managed.join('\n')}`);

writeFileSync(tomlPath, toml);

// ─── Report ──────────────────────────────────────────────────────────────────

const outputs = [`mode=${mode}`, `triggers=${triggers}`];
if (mode === 'waker') outputs.push(`url=${url}`);
if (process.env.GITHUB_OUTPUT) {
appendFileSync(process.env.GITHUB_OUTPUT, `${outputs.join('\n')}\n`);
}

if (mode === 'waker') {
console.log(
`waker mode: WAKER_MODE=waker WAKER_URL=${url} WAKER_TRIGGERS=${triggers}` +
(triggers === 'keep'
? ' — dual run: the native Cron Trigger still fires, the receiver is open'
: ' — native [triggers] removed, the platform is the only scheduler'),
);
} else {
console.log(
`waker mode: WAKER_MODE=cron WAKER_TRIGGERS=${triggers} — native Cron Trigger, waker callback closed`,
);
}
28 changes: 15 additions & 13 deletions .github/scripts/test-d1-migrations.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ test('无前缀:保留 Wrangler 迁移路径及重复执行行为', (t) => {
assert.deepEqual(f.query('SELECT name FROM d1_migrations ORDER BY name')[0], [
{ name: '0001_init.sql' },
{ name: '0002_token_version.sql' },
{ name: '0003_waker_executions.sql' },
]);
assert.match(f.script('d1-prepare-migrations.sh', ''), /already tracked/);
assert.match(
Expand All @@ -233,18 +234,19 @@ test('无前缀:保留 Wrangler 迁移路径及重复执行行为', (t) => {

test('无前缀:setup 历史可 baseline 为 Wrangler 历史', (t) => {
const f = fixture(t);
f.setup('', ['schema_v1', 'schema_v2']);
f.setup('', ['schema_v1', 'schema_v2', 'schema_v3']);
assert.match(f.script('d1-prepare-migrations.sh', ''), /Baselining/);
assert.deepEqual(f.query('SELECT name FROM d1_migrations ORDER BY name')[0], [
{ name: '0001_init.sql' },
{ name: '0002_token_version.sql' },
{ name: '0003_waker_executions.sql' },
]);
});

test('有前缀且已全部执行:只打印空计划,仅执行 SELECT,共享库不变', (t) => {
const f = fixture(t);
const before = f.shared();
f.setup('SL', ['schema_v1', 'schema_v2']);
f.setup('SL', ['schema_v1', 'schema_v2', 'schema_v3']);
assert.match(f.script('d1-prepare-migrations.sh', 'SL'), /prefixed/);
// Bash trace 核对脚本实际调用的每条 D1 SQL,不能只比较最终数据。
const trace = f.run(
Expand All @@ -268,19 +270,19 @@ test('有前缀且已全部执行:只打印空计划,仅执行 SELECT,共
assert.deepEqual(f.foreignSnapshot(), before);
});

test('有前缀且有待执行迁移:仅应用 v2,保留其他应用的表、索引和数据', (t) => {
test('有前缀且有待执行迁移:仅应用 v2、v3,保留其他应用的表、索引和数据', (t) => {
const f = fixture(t);
const before = f.shared();
f.setup('SL', ['schema_v1']);
f.query(`INSERT INTO SL_users (email,username,password_hash)
VALUES ('sl@example.com','sl-user','hash')`);
assert.match(
f.script('d1-prefixed-migrations.sh', 'SL'),
/Planned migrations: schema_v2\n/,
/Planned migrations: schema_v2 schema_v3\n/,
);
assert.deepEqual(
f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0],
[{ name: 'schema_v1' }, { name: 'schema_v2' }],
[{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }],
);
f.assertOwnIndexes('SL');
assert.deepEqual(f.query('SELECT email,token_version FROM SL_users')[0], [
Expand All @@ -298,12 +300,12 @@ test('有前缀的新安装:只创建本应用的表,共享库保持不变',
const before = f.shared();
assert.match(
f.script('d1-prefixed-migrations.sh', 'SL'),
/Planned migrations: schema_v1 schema_v2/,
/Planned migrations: schema_v1 schema_v2 schema_v3/,
);
assert.deepEqual(f.foreignSnapshot(), before);
assert.deepEqual(
f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0],
[{ name: 'schema_v1' }, { name: 'schema_v2' }],
[{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }],
);
f.assertOwnIndexes('SL');
});
Expand Down Expand Up @@ -331,7 +333,7 @@ test('已知限制:别的应用占用同名索引时,本应用索引会被
f.query('CREATE INDEX idx_links_slug ON ZETA_links(slug)');
assert.match(
f.script('d1-prefixed-migrations.sh', 'SL'),
/Planned migrations: schema_v1 schema_v2/,
/Planned migrations: schema_v1 schema_v2 schema_v3/,
);
assert.throws(() => f.assertOwnIndexes('SL'), /Expected values/);
});
Expand Down Expand Up @@ -361,7 +363,7 @@ test('防静默切换:库中已有 prefixed schema + 显式空前缀 → 中
test('回归:共享库他表 + Hop 已有 SL 前缀 → 增量迁移放行,不误杀', (t) => {
const f = fixture(t);
const before = f.shared(); // 他应用:bare users + ZETA_*
f.setup('SL', ['schema_v1', 'schema_v2']);
f.setup('SL', ['schema_v1', 'schema_v2', 'schema_v3']);
assert.match(f.script('d1-prepare-migrations.sh', 'SL'), /prefixed/);
assert.match(
f.script('d1-prefixed-migrations.sh', 'SL'),
Expand Down Expand Up @@ -396,11 +398,11 @@ test('回归:仅外来 d1_migrations(别家文件名)+ SL 表全删 →
assert.match(f.outputs(), /mode=prefixed/);
assert.match(
f.script('d1-prefixed-migrations.sh', 'SL'),
/Planned migrations: schema_v1 schema_v2\n/,
/Planned migrations: schema_v1 schema_v2 schema_v3\n/,
);
assert.deepEqual(
f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0],
[{ name: 'schema_v1' }, { name: 'schema_v2' }],
[{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }],
);
f.assertOwnIndexes('SL');
assert.deepEqual(f.foreignSnapshot(), before);
Expand Down Expand Up @@ -485,7 +487,7 @@ for (const scenario of [
assert.doesNotMatch(output, /::error::/);
assert.deepEqual(
f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0],
[{ name: 'schema_v1' }, { name: 'schema_v2' }],
[{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }],
);
f.assertOwnIndexes('SL');
assert.deepEqual(f.foreignSnapshot(), before);
Expand Down Expand Up @@ -534,7 +536,7 @@ for (const scenario of [
assert.match(run(), /Deployed Worker uses TABLE_PREFIX=SL/);
assert.deepEqual(
f.query('SELECT name FROM _SL_schema_migrations ORDER BY name')[0],
[{ name: 'schema_v1' }, { name: 'schema_v2' }],
[{ name: 'schema_v1' }, { name: 'schema_v2' }, { name: 'schema_v3' }],
);
f.assertOwnIndexes('SL');
assert.deepEqual(f.foreignSnapshot(), before);
Expand Down
Loading
Loading