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
183 changes: 180 additions & 3 deletions .github/scripts/test-deploy-checks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
// HTTP 检查使用真实本地服务;控制面检查用固定响应模拟 Wrangler,不调用生产 API。
import assert from 'node:assert/strict';
import { execFile, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import {
copyFileSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
Expand All @@ -11,8 +18,55 @@ import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';

const scripts = fileURLToPath(new URL('.', import.meta.url));
const repoRoot = fileURLToPath(new URL('../..', import.meta.url));
const exec = promisify(execFile);

// 取出 deploy.yml 里真实步骤的 run 脚本执行:测试跑的就是 workflow 本身,
// 不复制、不另写一份等价逻辑。
function stepScript(name) {
const lines = readFileSync(
join(repoRoot, '.github', 'workflows', 'deploy.yml'),
'utf8',
).split('\n');
const start = lines.findIndex((line) => line.trim() === `- name: ${name}`);
assert.notEqual(start, -1, `deploy.yml 缺少步骤「${name}」`);
const runAt = lines.findIndex(
(line, i) => i > start && /^\s*run: \|\s*$/.test(line),
);
assert.ok(runAt > start, `步骤「${name}」缺少 run 脚本`);
const blockIndent = lines[runAt].match(/^\s*/)[0].length;
const body = [];
for (let i = runAt + 1; i < lines.length; i++) {
const line = lines[i];
if (line.trim() !== '' && line.match(/^\s*/)[0].length <= blockIndent) {
break;
}
body.push(line);
}
const bodyIndent = Math.min(
...body
.filter((line) => line.trim() !== '')
.map((line) => line.match(/^\s*/)[0].length),
);
return `${body.map((line) => line.slice(bodyIndent)).join('\n')}\n`;
}

// 部署 workflow 跑在 ubuntu 上,用 GNU sed 语法(`sed -i 's/x/y/' f`);
// macOS 自带 BSD sed 要求 `-i` 带备份后缀。本地跑测试时补一层适配,
// 而不是为 macOS 去改 workflow。
function gnuSedShim(dir) {
if (process.platform !== 'darwin') return;
writeFileSync(
join(dir, 'sed'),
`#!/bin/sh
if command -v gsed >/dev/null 2>&1; then exec gsed "$@"; fi
if [ "$1" = "-i" ]; then shift; exec /usr/bin/sed -i '' "$@"; fi
exec /usr/bin/sed "$@"
`,
{ mode: 0o755 },
);
}

function fixture(t) {
const dir = mkdtempSync(join(tmpdir(), 'hop-deploy-test-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
Expand Down Expand Up @@ -99,6 +153,24 @@ for (const scenario of [
prefix: 'SL',
ok: true,
},
{
// 配置托管的默认前缀:CI 写入的绑定与 GitHub 变量解析结果一致。
name: '配置托管默认前缀 hop 时通过',
version: 'uploaded',
percentage: 100,
prefix: 'hop',
env: 'hop',
ok: true,
},
{
// 配置托管的无前缀情形:绑定为空字符串,期望也是空字符串。
name: '配置托管空字符串(none 无前缀)时通过',
version: 'uploaded',
percentage: 100,
prefix: '',
env: '',
ok: true,
},
{
name: '仍在运行旧版本',
version: 'old',
Expand All @@ -120,6 +192,22 @@ for (const scenario of [
prefix: 'ZETA',
ok: false,
},
{
name: '绑定为空但期望 hop 必须失败',
version: 'uploaded',
percentage: 100,
prefix: '',
env: 'hop',
ok: false,
},
{
name: '绑定为 hop 但期望无前缀必须失败',
version: 'uploaded',
percentage: 100,
prefix: 'hop',
env: '',
ok: false,
},
]) {
test(`控制面:${scenario.name}`, (t) => {
const f = fixture(t);
Expand All @@ -142,14 +230,20 @@ esac
execFileSync('bash', [join(scripts, 'verify-deployment.sh')], {
env: {
...f.env,
TABLE_PREFIX: 'SL',
// 期望值(GitHub 变量解析结果)默认取 SL;用例可单独指定。
TABLE_PREFIX: scenario.env ?? 'SL',
WRANGLER_OUTPUT_FILE_PATH: output,
},
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
});
if (scenario.ok) {
assert.match(run(), /serves 100% of production traffic/);
const stdout = run();
assert.match(stdout, /serves 100% of production traffic/);
assert.ok(
stdout.includes(`TABLE_PREFIX: ${scenario.prefix || '<none>'}`),
stdout,
);
} else {
assert.throws(run, /Command failed/);
}
Expand Down Expand Up @@ -204,3 +298,86 @@ esac
);
assert.equal(out, 'hop');
});

// ─── 改动 A:CI 部署时把配置托管前缀写进 Worker 绑定 ─────────────────────────

test('wrangler.toml:声明配置托管的 TABLE_PREFIX 占位符', () => {
const toml = readFileSync(
join(repoRoot, 'apps', 'worker', 'wrangler.toml'),
'utf8',
);
assert.match(toml, /^\[vars\]$/m);
assert.match(toml, /^TABLE_PREFIX = "TABLE_PREFIX_PLACEHOLDER"$/m);
// keep_vars 不变:控制台独有变量继续保留。
assert.match(toml, /^keep_vars = true$/m);
});

test('deploy.yml:Resolve 步在 Inject 步之前', () => {
const lines = readFileSync(
join(repoRoot, '.github', 'workflows', 'deploy.yml'),
'utf8',
).split('\n');
const stepAt = (name) =>
lines.findIndex((line) => line.trim() === `- name: ${name}`);
const resolve = stepAt('Resolve TABLE_PREFIX (three-state)');
const inject = stepAt('Inject resource IDs');
assert.ok(resolve !== -1 && inject !== -1, '步骤缺失');
assert.ok(resolve < inject, 'Resolve 步必须在 Inject 步之前');
});

for (const scenario of [
{ name: 'vars 为 SL → 绑定 SL', env: 'SL', expected: 'SL' },
{ name: 'vars 未配 → 绑定默认 hop', env: undefined, expected: 'hop' },
{ name: 'vars 为 none → 绑定空字符串', env: 'none', expected: '' },
]) {
test(`Inject:${scenario.name}`, (t) => {
const f = fixture(t);
gnuSedShim(f.dir);
const tomlPath = join(f.dir, 'apps', 'worker', 'wrangler.toml');
mkdirSync(join(f.dir, 'apps', 'worker'), { recursive: true });
copyFileSync(join(repoRoot, 'apps', 'worker', 'wrangler.toml'), tomlPath);

// 1) 与 workflow 的 Resolve 步同一命令解析三态前缀。
const resolveEnv = { ...f.env };
if (scenario.env === undefined) {
delete resolveEnv.TABLE_PREFIX;
} else {
resolveEnv.TABLE_PREFIX = scenario.env;
}
const resolved = execFileSync(
'node',
[
'--disable-warning=MODULE_TYPELESS_PACKAGE_JSON',
join(scripts, 'resolve-table-prefix.mjs'),
],
{
cwd: repoRoot,
env: resolveEnv,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
},
);
assert.equal(resolved, scenario.expected);

// 2) 执行 deploy.yml 里真实的 Inject 步脚本。资源 ID 用合法格式的假值,
// 变量名从脚本自身的 check 调用里取,避免测试里重写一份校验清单。
const script = stepScript('Inject resource IDs');
const env = { ...f.env, TABLE_PREFIX: resolved };
for (const [, name] of script.matchAll(/^\s*check\s+([A-Z0-9_]+)\s/gm)) {
env[name] = '0'.repeat(32);
}
execFileSync(
'bash',
['--noprofile', '--norc', '-eo', 'pipefail', '-c', script],
{ cwd: f.dir, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
);

const toml = readFileSync(tomlPath, 'utf8');
assert.match(
toml,
new RegExp(`^TABLE_PREFIX = "${scenario.expected}"$`, 'm'),
);
// 残留检查(Inject 步的 grep)通过:所有占位符都已替换。
assert.doesNotMatch(toml, /_PLACEHOLDER/);
});
}
25 changes: 16 additions & 9 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,25 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile

# Runs before Inject so the inject step can write the resolved prefix
# into wrangler.toml: the GitHub variable is the single source of truth
# for the Worker's TABLE_PREFIX binding. Depends only on vars.TABLE_PREFIX.
- name: Resolve TABLE_PREFIX (three-state)
id: prefix
env:
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
run: |
resolved="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON .github/scripts/resolve-table-prefix.mjs)"
echo "resolved TABLE_PREFIX: ${resolved:-<empty>}"
echo "table_prefix=${resolved}" >> "$GITHUB_OUTPUT"

- name: Inject resource IDs
env:
D1_DATABASE_ID: ${{ secrets.D1_DATABASE_ID }}
D1_DATABASE_NAME: ${{ vars.D1_DATABASE_NAME }}
KV_NAMESPACE_ID: ${{ secrets.KV_NAMESPACE_ID }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
TABLE_PREFIX: ${{ steps.prefix.outputs.table_prefix }}
run: |
check() {
if ! [[ "${!1}" =~ $2 ]]; then
Expand All @@ -78,6 +91,9 @@ jobs:
sed -i "s/D1_DATABASE_NAME_PLACEHOLDER/${D1_DATABASE_NAME}/g" "$f"
sed -i "s/KV_NAMESPACE_ID_PLACEHOLDER/${KV_NAMESPACE_ID}/g" "$f"
sed -i "s/CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER/${CLOUDFLARE_ACCOUNT_ID}/g" "$f"
# TABLE_PREFIX is config-managed: the resolved GitHub variable
# (default 'hop', 'none' → empty string) becomes the Worker binding.
sed -i "s/TABLE_PREFIX_PLACEHOLDER/${TABLE_PREFIX}/g" "$f"
if grep -q '_PLACEHOLDER' "$f"; then
echo "::error::Unreplaced placeholders remain in $f"
exit 1
Expand All @@ -91,15 +107,6 @@ jobs:
# Order: migrate first, then deploy code. Migrations must therefore be
# backward compatible with the code currently live (expand → deploy →
# contract: add columns/tables now, drop old ones in a later release).
- name: Resolve TABLE_PREFIX (three-state)
id: prefix
env:
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
run: |
resolved="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON .github/scripts/resolve-table-prefix.mjs)"
echo "resolved TABLE_PREFIX: ${resolved:-<empty>}"
echo "table_prefix=${resolved}" >> "$GITHUB_OUTPUT"

- name: Prepare D1 migrations
id: d1
working-directory: apps/worker
Expand Down
6 changes: 6 additions & 0 deletions apps/worker/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ account_id = "CLOUDFLARE_ACCOUNT_ID_PLACEHOLDER"
compatibility_flags = ["nodejs_compat"]
keep_vars = true

# TABLE_PREFIX is config-managed: CI replaces this placeholder with the
# resolved GitHub variable vars.TABLE_PREFIX before wrangler uploads the
# version, so the binding always matches the prefix the migrations used.
[vars]
TABLE_PREFIX = "TABLE_PREFIX_PLACEHOLDER"

[assets]
directory = "../web/dist"
binding = "ASSETS"
Expand Down
Loading