From a7aff9d12e89b88de5e54539679daf61c71a97ec Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:40:32 +0800 Subject: [PATCH] =?UTF-8?q?ci:=20=E9=83=A8=E7=BD=B2=E6=97=B6=E7=94=B1=20CI?= =?UTF-8?q?=20=E5=86=99=E5=85=A5=20Worker=20=E7=9A=84=20TABLE=5FPREFIX=20?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=20(ONE-511)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - apps/worker/wrangler.toml 新增 [vars] TABLE_PREFIX 占位符,keep_vars 不变 - deploy.yml 把 Resolve TABLE_PREFIX 步移到 Inject 步之前,Inject 复用既有 sed 占位符替换机制写入已解析前缀(未配→hop、none→空字符串、其他原样), 既有 _PLACEHOLDER 残留 grep 自动覆盖 - test-deploy-checks.mjs 新增回归:直接执行 deploy.yml 里的 Inject 步脚本, 覆盖 SL / 默认 hop / none→空字符串三态且无占位符残留;Verify 比对覆盖 配置托管默认值、空字符串无前缀通过与不一致失败 --- .github/scripts/test-deploy-checks.mjs | 183 ++++++++++++++++++++++++- .github/workflows/deploy.yml | 25 ++-- apps/worker/wrangler.toml | 6 + 3 files changed, 202 insertions(+), 12 deletions(-) diff --git a/.github/scripts/test-deploy-checks.mjs b/.github/scripts/test-deploy-checks.mjs index 58a8141..9bde13e 100644 --- a/.github/scripts/test-deploy-checks.mjs +++ b/.github/scripts/test-deploy-checks.mjs @@ -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'; @@ -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 })); @@ -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', @@ -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); @@ -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 || ''}`), + stdout, + ); } else { assert.throws(run, /Command failed/); } @@ -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/); + }); +} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 03dcf2a..bc55c80 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -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:-}" + 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 @@ -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 @@ -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:-}" - echo "table_prefix=${resolved}" >> "$GITHUB_OUTPUT" - - name: Prepare D1 migrations id: d1 working-directory: apps/worker diff --git a/apps/worker/wrangler.toml b/apps/worker/wrangler.toml index b52f328..15ee2df 100644 --- a/apps/worker/wrangler.toml +++ b/apps/worker/wrangler.toml @@ -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"