Repository navigation
252 lines (222 loc) · 11.1 KB
/
Copy pathdeploy.yml
File metadata and controls
252 lines (222 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
name: Deploy
on:
push:
branches: [main]
workflow_dispatch:
run-name: Deploy ${{ github.ref_name }} by ${{ github.actor }}
permissions:
contents: read
concurrency:
group: deploy
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
env:
WRANGLER_SEND_METRICS: "false"
steps:
# 版本号(前端页脚与 Worker 的 APP_VERSION 同源)由 scripts/build-info.mjs
# 从 git describe 生成;浅克隆拿不到 tag,故取全历史。
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v7
with:
node-version: 26
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
# 资源 ID 只经 secrets.* 引用(GitHub 自动掩码),不另加掩码步骤;
# D1_DATABASE_NAME / TABLE_PREFIX 是明文 variables。
# 逐键非空校验在脚本里:缺任一把即退出 1,不写 secrets.json,绝不带空值或占位值上线。
# 放在构建之前:配置不全就不值得先花时间构建产物。
- name: Materialize secrets + wrangler config
env:
SETUP_SECRET: ${{ secrets.SETUP_SECRET }}
SIGNING_SECRET: ${{ secrets.SIGNING_SECRET }}
WAKER_SIGNING_KEY: ${{ secrets.WAKER_SIGNING_KEY }}
PIX_SERVER_URL: ${{ secrets.PIX_SERVER_URL }}
PIX_SERVER_SECRET: ${{ secrets.PIX_SERVER_SECRET }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
D1_DATABASE_ID: ${{ secrets.D1_DATABASE_ID }}
D1_DATABASE_NAME: ${{ vars.D1_DATABASE_NAME }}
TABLE_PREFIX: ${{ vars.TABLE_PREFIX }}
run: node scripts/materialize-secrets.mjs
# 前端构建产物与 Worker 同一部署单元(wrangler.toml 的 [assets] 指向 ../web/dist)。
- name: Build web
run: pnpm build:web
# 版本号(§6.3):与前端页脚同源,由 scripts/build-info.mjs 在 CI 内从 git describe 现算
# (tag 形态 v<semver>-<提交数>-<短哈希>,无 tag 兜底 v1.0.0-<提交数>-<短哈希>)。
# APP_VERSION 非密钥,因此走 --var 注入、与 wrangler.toml 的 [vars] TABLE_PREFIX 并存;
# 不进 secrets.json,也不进 scripts/materialize-secrets.mjs 的校验名单(该脚本不为此改动)。
#
# DEFAULT_MODEL 非密钥(模型 ID,白名单值),同样走 --var 注入;Worker 侧
# resolveDefaultModel(env) 读 env.DEFAULT_MODEL(#23 已合并)。LCM 对比验收
# 已通过,默认模型恢复为 realistic-lcm(回退条款第二处)。不读 secret(非密钥,走 secret 无谓增加配置面与漂移风险)。
- name: Deploy Worker
working-directory: worker
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
run: |
APP_VERSION=$(node ../scripts/build-info.mjs --print)
if [ "${APP_VERSION##*-}" = "unknown" ]; then
echo "APP_VERSION 无法从 git describe 解析(检出缺 git 历史?checkout 需 fetch-depth: 0):${APP_VERSION}" >&2
exit 1
fi
pnpm exec wrangler deploy --secrets-file "$RUNNER_TEMP/secrets.json" \
--var "APP_VERSION:${APP_VERSION}" \
--var "DEFAULT_MODEL:realistic-lcm"
# 数据库自动升级:Worker 部署成功后,由 CI 自动调用 /api/setup 执行增量迁移并校验账本。
- name: Run database migrations
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
SETUP_SECRET: ${{ secrets.SETUP_SECRET }}
run: |
if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ] || [ -z "$SETUP_SECRET" ]; then
echo "Missing required environment variables for database migration" >&2
exit 1
fi
WORKER_NAME=$(node -e '
import fs from "node:fs";
const toml = fs.readFileSync("worker/wrangler.toml", "utf8");
const m = toml.match(/^name\s*=\s*"([^"]+)"/m);
if (!m) { console.error("Missing name in worker/wrangler.toml"); process.exit(1); }
process.stdout.write(m[1]);
')
if [ -z "$WORKER_NAME" ]; then
echo "Failed to resolve worker name from worker/wrangler.toml" >&2
exit 1
fi
SUBDOMAIN_RES=$(curl -sS -X GET "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/subdomain" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
-H "Content-Type: application/json")
SUBDOMAIN=$(echo "$SUBDOMAIN_RES" | jq -r '.result.subdomain // empty')
if [ -z "$SUBDOMAIN" ]; then
echo "Failed to retrieve workers.dev subdomain: $(echo "$SUBDOMAIN_RES" | jq -c '.errors // .')" >&2
exit 1
fi
ROUTE_RES=$(curl -sS -X GET "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/scripts/${WORKER_NAME}/subdomain" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
-H "Content-Type: application/json")
ENABLED=$(echo "$ROUTE_RES" | jq -r '.result.enabled // false')
if [ "$ENABLED" != "true" ]; then
echo "workers.dev route is disabled for ${WORKER_NAME}, enabling..."
ENABLE_RES=$(curl -sS -X POST "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/scripts/${WORKER_NAME}/subdomain" \
-H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"enabled": true}')
ENABLE_SUCCESS=$(echo "$ENABLE_RES" | jq -r '.success // false')
if [ "$ENABLE_SUCCESS" != "true" ]; then
echo "Failed to enable workers.dev route for ${WORKER_NAME}: $(echo "$ENABLE_RES" | jq -c '.errors // .')" >&2
exit 1
fi
fi
APP_VERSION=$(node scripts/build-info.mjs --print)
if [ "${APP_VERSION##*-}" = "unknown" ]; then
echo "APP_VERSION 无法从 git describe 解析:${APP_VERSION}" >&2
exit 1
fi
DELAYS=(3 6 12 20)
verify_version() {
local PHASE="$1"
local VER_FILE
VER_FILE=$(mktemp)
local V_HTTP_STATUS=""
local V_VERSION=""
local V_OK=false
for V_ATTEMPT in 1 2 3 4 5; do
V_HTTP_STATUS=$(curl -sS -o "$VER_FILE" -w "%{http_code}" \
"https://${WORKER_NAME}.${SUBDOMAIN}.workers.dev/api/public?t=$(date +%s)" \
-H "Content-Type: application/json" 2>/dev/null) || V_HTTP_STATUS="000"
if [ "$V_HTTP_STATUS" = "200" ]; then
V_VERSION=$(jq -r '.version // empty' "$VER_FILE" 2>/dev/null || true)
echo "Version check (${PHASE}) attempt ${V_ATTEMPT}/5: served=${V_VERSION:-<none>}, expected=${APP_VERSION}"
if [ -n "$V_VERSION" ] && [ "$V_VERSION" = "$APP_VERSION" ]; then
V_OK=true
break
fi
else
echo "Version check (${PHASE}) attempt ${V_ATTEMPT}/5: HTTP ${V_HTTP_STATUS}" >&2
fi
if [ "$V_ATTEMPT" -lt 5 ]; then
sleep "${DELAYS[$((V_ATTEMPT - 1))]}"
fi
done
rm -f "$VER_FILE"
if [ "$V_OK" != "true" ]; then
echo "Version self-verification (${PHASE}) failed: /api/public never served ${APP_VERSION} (last served=${V_VERSION:-<none>}, HTTP ${V_HTTP_STATUS})" >&2
exit 1
fi
echo "Version self-verification (${PHASE}) passed: /api/public serving ${APP_VERSION}"
}
verify_version "pre-setup"
EXPECTED_MIGRATIONS=$(node -e '
import { registerHooks } from "node:module";
registerHooks({
resolve(specifier, context, nextResolve) {
try {
return nextResolve(specifier, context);
} catch (err) {
if (err.code === "ERR_MODULE_NOT_FOUND" && !specifier.endsWith(".ts")) {
return nextResolve(specifier + ".ts", context);
}
throw err;
}
}
});
const { getMigrations } = await import("./worker/src/lib/migrations.ts");
process.stdout.write(JSON.stringify(getMigrations("").map(m => m.name)));
')
RESP_FILE=$(mktemp)
HTTP_STATUS=$(curl -sS -o "$RESP_FILE" -w "%{http_code}" -X POST \
"https://${WORKER_NAME}.${SUBDOMAIN}.workers.dev/api/setup" \
-H "X-Setup-Secret: ${SETUP_SECRET}" \
-H "Content-Type: application/json" \
-d '' 2>/dev/null) || HTTP_STATUS="000"
if [ "$HTTP_STATUS" = "403" ]; then
echo "HTTP 403: Invalid setup secret" >&2
exit 1
fi
if [ "$HTTP_STATUS" != "200" ]; then
echo "HTTP ${HTTP_STATUS}: /api/setup failed: $(cat "$RESP_FILE" 2>/dev/null)" >&2
exit 1
fi
RESP_FILE="$RESP_FILE" EXPECTED_MIGRATIONS="$EXPECTED_MIGRATIONS" node -e '
import fs from "node:fs";
const expected = JSON.parse(process.env.EXPECTED_MIGRATIONS || "[]");
const resp = JSON.parse(fs.readFileSync(process.env.RESP_FILE, "utf8"));
if (resp.success !== true) {
console.error("Migration validation failed: response success is not true");
process.exit(1);
}
const migrations = resp.migrations || [];
const seen = new Set();
for (const m of migrations) {
if (m.status !== "applied" && m.status !== "skipped") {
console.error(`Migration validation failed: migration "${m.name}" has invalid status "${m.status}"`);
process.exit(1);
}
if (seen.has(m.name)) {
console.error(`Migration validation failed: duplicate migration "${m.name}" in response`);
process.exit(1);
}
seen.add(m.name);
}
const expectedSet = new Set(expected);
const actualSet = new Set(migrations.map(m => m.name));
const missing = expected.filter(n => !actualSet.has(n));
const extra = migrations.map(m => m.name).filter(n => !expectedSet.has(n));
if (missing.length > 0 || extra.length > 0) {
console.error(`Migration validation failed: set mismatch (missing: [${missing.join(", ")}], extra: [${extra.join(", ")}])`);
process.exit(1);
}
'
echo "Active table prefix: $(jq -r '.tablePrefix' "$RESP_FILE")"
echo "Migration ledger summary:"
jq -r '.migrations[] | " - \(.name): \(.status)"' "$RESP_FILE"
verify_version "post-setup"
rm -f "$RESP_FILE"