Files
hose-use/scripts/release/release-validation.test.ts
gitea bfbf6cf55f chore: 加固 Gitea Release 上传,避免维护期丢资产
0.9.5 的 Release workflow 因 Gitea 服务端维护期不稳,5 个资产
上传 3 次重试全部失败,Gitea 侧只落地 7/12(已手动补齐)。
根因不是代码缺陷,但二进制变大后并发大文件上传放大了影响。

- job timeout-minutes: 30 → 60,给重试留足窗口。
- 单资产重试次数 3 → 5,间隔保持 3 秒。
- 上传从「2 并发 + wait」改为串行,维护期不再互相抢带宽;
  幂等逻辑不变(已存在资产校验 SHA-256 后跳过,字节不同才删除重传)。
- 同步 release-validation.test.ts:断言改 attempt 2/5,
  并发用例改为验证严格单 worker(peak === 1),
  失败用例的 spawnSync 超时放宽到 40s。

校验:YAML parse 通过;bun test 1114 pass / 0 fail;
bun run check、check:readme 37/37 全通过。
本次只改 CI,不打 tag、不发版。
2026-11-06 10:39:49 +08:00

204 lines
12 KiB
TypeScript

import { afterEach, describe, expect, test } from "bun:test";
import { execFileSync, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parse } from "yaml";
import { bumpVersion } from "./bump-version.js";
import { verifyReleaseTag } from "./verify-release.js";
// Shell fixtures start several processes; allow headroom on a busy host.
const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
function repository() {
const root = mkdtempSync(join(tmpdir(), "hose-release-test-"));
roots.push(root);
const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
git("init", "--initial-branch=main");
git("config", "user.name", "Release fixture");
git("config", "user.email", "fixture@example.test");
git("config", "core.hooksPath", "/dev/null");
git("config", "commit.gpgsign", "false");
git("config", "tag.gpgsign", "false");
for (const dir of ["skills/hose-use", "specs/hose-open-api", ".zcode-plugin"]) mkdirSync(join(root, dir), { recursive: true });
writeFileSync(join(root, "package.json"), '{"version":"1.0.0"}\n');
writeFileSync(join(root, "README.md"), "# hose-use (v1.0.0)\n");
writeFileSync(join(root, "skills/hose-use/SKILL.md"), "version: 1.0.0\n# hose-use (v1.0.0)\n");
writeFileSync(join(root, "specs/hose-open-api/openapi.yaml"), "info:\n version: 1.0.0\n");
writeFileSync(join(root, ".zcode-plugin/plugin.json"), '{"version":"1.0.0"}\n');
git("add", ".");
git("commit", "-m", "fixture");
git("update-ref", "refs/remotes/origin/main", "HEAD");
return { root, git, version: () => JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version };
}
function mirrorFixture(mode: "retry" | "skip" | "concurrency", mirrorOnly = false) {
const f = repository();
const tools = join(f.root, "tools"), published = join(f.root, "published");
mkdirSync(tools); mkdirSync(published); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
const names = mode === "concurrency" ? Array.from({ length: 5 }, (_, i) => `hose-use-fixture-${i}`) : ["hose-use-linux-x64", "hose-use-plugin-v1.0.0.tar.gz"];
const manifest = names.map(name => {
const data = `published bytes for ${name}`;
writeFileSync(join(published, name), data);
return `${createHash("sha256").update(data).digest("hex")} ${name}\n`;
}).join("");
writeFileSync(join(published, "checksums.txt"), manifest);
const files = [...names, "checksums.txt"];
if (!mirrorOnly) for (const name of files) writeFileSync(join(f.root, "dist/bin", name), readFileSync(join(published, name)));
writeFileSync(join(f.root, "info.json"), JSON.stringify({ assets: mode === "skip" ? files.map((name, i) => ({ id: i + 1, name })) : [] }));
writeFileSync(join(tools, "gh"), '#!/bin/sh\nprintf "%s\\n" "$*" > "$MIRROR_FIXTURE/gh.log"\ncp "$MIRROR_FIXTURE"/published/* dist/bin/\n', { mode: 0o755 });
writeFileSync(join(tools, "curl"), `#!/bin/bash
url=""
for arg in "$@"; do case "$arg" in https://*) url="$arg" ;; esac; done
case "$url" in
*/assets?*)
name="\${url##*name=}"
printf 'start\\n' >> "$MIRROR_FIXTURE/events"
if [ "$MIRROR_MODE" = "skip" ]; then printf 'unexpected upload\\n' >> "$MIRROR_FIXTURE/uploads"; exit 22; fi
count_file="$MIRROR_FIXTURE/count-$name"
count=0; [ ! -f "$count_file" ] || count=$(cat "$count_file")
count=$((count + 1)); printf '%s' "$count" > "$count_file"
if [ "$MIRROR_MODE" = "retry" ] && [ "$count" -eq 1 ]; then printf 'end\\n' >> "$MIRROR_FIXTURE/events"; exit 28; fi
if [ "$MIRROR_MODE" = "concurrency" ]; then sleep 0.1; fi
printf 'end\\n' >> "$MIRROR_FIXTURE/events"
printf '{"id":100}\\nHTTP_STATUS:201'
;;
*/download/*) cat "$MIRROR_FIXTURE/published/\${url##*/}" ;;
*/releases) printf '{"id":42}' ;;
*/releases/42) cat "$MIRROR_FIXTURE/info.json" ;;
*) exit 22 ;;
esac
`, { mode: 0o755 });
const workflow = parse(readFileSync(join(import.meta.dir, "../../.github/workflows/release.yml"), "utf8"));
const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release");
return { ...f, files, run: () => spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${tools}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0", MIRROR_ONLY: String(mirrorOnly), GITHUB_REPOSITORY: "test/repo", MIRROR_FIXTURE: f.root, MIRROR_MODE: mode }, encoding: "utf8", timeout: 30_000 }) };
}
describe("release preparation and publication guards", () => {
test("bump rejects wrong branches, dirty trees and invalid/non-increasing versions before writes", () => {
const f = repository();
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("release-v1.0.1");
f.git("switch", "-c", "codex/release-v1.0.1");
writeFileSync(join(f.root, "untracked.txt"), "work in progress");
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("clean working tree");
rmSync(join(f.root, "untracked.txt"));
for (const version of ["1.0.0", "0.9.9", "1.0.01", "1.0.1-rc.01", "invalid"]) expect(() => bumpVersion(f.root, version, () => {})).toThrow();
expect(f.version()).toBe("1.0.0");
expect(f.git("status", "--porcelain")).toBe("");
}, 60_000);
test("bump updates sources on its release branch and explicitly invokes regeneration", () => {
const f = repository();
f.git("switch", "-c", "release/v1.0.1");
let rebuilt = false;
expect(bumpVersion(f.root, "patch", () => { rebuilt = true; })).toBe("1.0.1");
expect(rebuilt).toBe(true);
expect(f.version()).toBe("1.0.1");
expect(readFileSync(join(f.root, "skills/hose-use/SKILL.md"), "utf8")).toContain("version: 1.0.1");
expect(parse(readFileSync(join(f.root, "specs/hose-open-api/openapi.yaml"), "utf8")).info.version).toBe("1.0.1");
}, 60_000);
test("an existing release tag cannot be reused during bump", () => {
const f = repository();
f.git("switch", "-c", "release/v1.0.1");
f.git("tag", "v1.0.1");
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("already exists");
expect(f.version()).toBe("1.0.0");
}, 60_000);
test("publication validates the actual HEAD, main ancestry and package version", () => {
const f = repository();
f.git("tag", "v1.0.0");
expect(() => verifyReleaseTag(f.root, "v1.0.0")).not.toThrow();
expect(() => verifyReleaseTag(f.root, "main")).toThrow("Invalid release tag");
f.git("tag", "v9.9.9");
expect(() => verifyReleaseTag(f.root, "v9.9.9")).toThrow("does not match");
f.git("switch", "-c", "unmerged");
writeFileSync(join(f.root, "change"), "unreviewed");
f.git("add", "."); f.git("commit", "-m", "unmerged fixture");
expect(() => verifyReleaseTag(f.root, "v1.0.0")).toThrow("exact tagged commit");
f.git("tag", "v1.0.1");
expect(() => verifyReleaseTag(f.root, "v1.0.1")).toThrow("ancestor");
}, 60_000);
test("workflows validate committed versions before generation and ship the checksum manifest", () => {
const root = join(import.meta.dir, "../..");
const ci = parse(readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"));
const release = parse(readFileSync(join(root, ".github/workflows/release.yml"), "utf8"));
expect(ci.on.pull_request.branches).toContain("main");
expect(ci.permissions.contents).toBe("read");
const steps = release.jobs["build-and-publish"].steps;
const runs = steps.map((s: { run?: string }) => s.run || "");
expect(runs.findIndex((s: string) => s.includes("check:version"))).toBeLessThan(runs.findIndex((s: string) => s.includes("openapi:all")));
expect(steps[0].with.ref).toContain("inputs.tag");
expect(runs.some((s: string) => s.includes("verify-release.ts"))).toBe(true);
expect(runs.some((s: string) => s.includes("sha256sum hose-use-* > checksums.txt"))).toBe(true);
for (const step of [...ci.jobs.validate.steps, ...steps]) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
expect(JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"].command).toBe("bun");
expect(release.on.workflow_dispatch.inputs.mirror_only.type).toBe("boolean");
for (const name of ["Compile multi-target binaries", "Package plugin archive", "Package release archives", "Publish GitHub Release"]) {
expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}");
}
expect(runs.findIndex((s: string) => s.includes("package:plugin"))).toBeLessThan(runs.findIndex((s: string) => s.includes("sha256sum hose-use-*")));
expect(steps.find((s: { name?: string }) => s.name === "Package plugin archive").run).toBe("bun run package:plugin");
}, 60_000);
test("a failed background Gitea upload makes the Release step fail", () => {
const f = repository();
const workflow = parse(readFileSync(join(import.meta.dir, "../../.github/workflows/release.yml"), "utf8"));
const step = workflow.jobs["build-and-publish"].steps.find((s: { name?: string }) => s.name === "Publish Gitea Release");
mkdirSync(join(f.root, "tools")); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
writeFileSync(join(f.root, "dist/bin/hose-use-linux-x64"), "fixture");
writeFileSync(join(f.root, "dist/bin/checksums.txt"), "fixture checksums");
writeFileSync(join(f.root, "tools/curl"), `#!/bin/sh
for arg in "$@"; do
case "$arg" in
*/assets?*) exit 22 ;;
*/releases) printf '{"id":42}'; exit 0 ;;
*/releases/42) printf '{"assets":[]}'; exit 0 ;;
esac
done
exit 22
`, { mode: 0o755 });
const result = spawnSync("bash", ["-eo", "pipefail", "-c", step.run], { cwd: f.root, env: { ...process.env, PATH: `${join(f.root, "tools")}:${process.env.PATH}`, GITEA_TOKEN: "fixture", GITEA_RETRY_DELAY: "0", GITEA_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 40_000 });
expect(result.status).toBe(1);
expect(result.stdout).toContain("assets failed to upload");
expect(result.stdout).not.toContain("Successfully published");
}, 60_000);
test("transient asset upload failures are retried", () => {
const f = mirrorFixture("retry");
const result = f.run();
expect(result.status).toBe(0);
for (const name of f.files) expect(readFileSync(join(f.root, `count-${name}`), "utf8")).toBe("2");
expect(result.stdout).toContain("attempt 2/5");
}, 60_000);
test("correct mirror assets are verified and retained without uploading replacements", () => {
const f = mirrorFixture("skip");
const result = f.run();
expect(result.status).toBe(0);
expect(result.stdout.match(/already matches SHA-256/g)).toHaveLength(f.files.length);
}, 60_000);
test("mirror-only recovery downloads and verifies the existing GitHub assets", () => {
const f = mirrorFixture("skip", true);
expect(f.run().status).toBe(0);
expect(readFileSync(join(f.root, "gh.log"), "utf8")).toContain("release download v1.0.0");
}, 60_000);
test("asset transfers are serialized to a single worker", () => {
const f = mirrorFixture("concurrency");
expect(f.run().status).toBe(0);
let active = 0, peak = 0;
for (const event of readFileSync(join(f.root, "events"), "utf8").trim().split("\n")) {
active += event === "start" ? 1 : -1;
peak = Math.max(peak, active);
}
expect(active).toBe(0);
expect(peak).toBe(1);
}, 60_000);
});