diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 967890e..7069355 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,6 +10,11 @@ on: description: Release tag already merged into main (e.g. v0.8.14) required: true type: string + mirror_only: + description: Reuse the existing GitHub assets and repair only the Gitea mirror + required: false + default: false + type: boolean concurrency: group: release-${{ inputs.tag || github.ref_name }} @@ -27,6 +32,7 @@ jobs: contents: write env: RELEASE_TAG: ${{ inputs.tag || github.ref_name }} + MIRROR_ONLY: ${{ inputs.mirror_only || false }} steps: - name: Checkout uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 @@ -47,34 +53,43 @@ jobs: bun run scripts/verify-release.ts "$RELEASE_TAG" - name: Install dependencies + if: ${{ !inputs.mirror_only }} run: bun install --frozen-lockfile - name: Check committed version consistency + if: ${{ !inputs.mirror_only }} run: bun run check:version - name: Generate & bundle OpenAPI + if: ${{ !inputs.mirror_only }} run: bun run openapi:all - name: Type-check + if: ${{ !inputs.mirror_only }} run: bun run check - name: Test + if: ${{ !inputs.mirror_only }} run: bun test - name: Compile multi-target binaries + if: ${{ !inputs.mirror_only }} run: | mkdir -p dist/bin node scripts/build-binary.mjs --all --release - name: Verify packaged MCP entrypoint + if: ${{ !inputs.mirror_only }} run: bun run scripts/verify-binary.ts dist/bin/hose-use-linux-x64 - name: Verify plugin bundle runtime + if: ${{ !inputs.mirror_only }} run: | bun run build:plugin bun run scripts/verify-binary.ts dist/mcp/server.js --plugin - name: Package release archives + if: ${{ !inputs.mirror_only }} run: | sudo apt-get update && sudo apt-get install -y zip package_unix() { @@ -102,6 +117,7 @@ jobs: (cd dist/bin && sha256sum hose-use-* > checksums.txt) - name: Publish GitHub Release + if: ${{ !inputs.mirror_only }} env: GH_TOKEN: ${{ github.token }} run: | @@ -115,28 +131,40 @@ jobs: - name: Publish Gitea Release env: + GH_TOKEN: ${{ github.token }} GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} GITEA_HOST: "https://git.ying-qing.cn" GITEA_REPO: "gitea/hose-use" run: | + set -euo pipefail if [ -z "$GITEA_TOKEN" ]; then + if [ "${MIRROR_ONLY:-false}" = "true" ]; then + echo "::error::GITEA_TOKEN is required to repair the mirror." + exit 1 + fi echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload." exit 0 fi TAG_NAME="${RELEASE_TAG}" + if [ "${MIRROR_ONLY:-false}" = "true" ]; then + # Preserve the published bytes and checksums; never rebuild or replace GitHub assets. + mkdir -p dist/bin + gh release download "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --dir dist/bin --pattern 'hose-use-*' --pattern checksums.txt + (cd dist/bin && sha256sum --strict -c checksums.txt) + fi TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d') NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}" echo "==> Creating release on Gitea for ${TAG_NAME}..." - RELEASE_RESP=$(curl -s -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \ + RELEASE_RESP=$(curl -sS --connect-timeout 15 --max-time 60 -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \ -H "Authorization: token ${GITEA_TOKEN}" \ -H "Content-Type: application/json" \ -d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":$(echo "$NOTES" | jq -Rsa .),\"draft\":false,\"prerelease\":false}") RELEASE_ID=$(echo "$RELEASE_RESP" | jq -r '.id // empty') if [ -z "$RELEASE_ID" ]; then - RELEASE_ID=$(curl -s -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty') + RELEASE_ID=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty') fi if [ -z "$RELEASE_ID" ]; then @@ -146,32 +174,56 @@ jobs: echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..." upload_asset() { - local file="$1" - local filename + local file="$1" filename expected_hash attempt info existing remote_hash asset_id response delete_failed filename=$(basename "$file") - echo " [start] Uploading ${filename} to Gitea..." - # Match GitHub --clobber when retrying the same verified release. - existing=$(curl -fsS -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id') - for asset_id in $existing; do - curl -fsS -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}" + expected_hash=$(sha256sum "$file" | awk '{ print $1 }') + for attempt in 1 2 3; do + if [ "$attempt" -gt 1 ]; then sleep "${GITEA_RETRY_DELAY:-3}"; fi + echo " [start] Uploading ${filename} to Gitea (attempt ${attempt}/3)..." + if ! info=$(curl -fsS --connect-timeout 15 --max-time 60 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}"); then + continue + fi + existing=$(printf '%s' "$info" | jq -r --arg name "$filename" '.assets[]? | select(.name == $name) | .id') + if [ -n "$existing" ]; then + if ! remote_hash=$(curl -fLsS --connect-timeout 15 --max-time 600 -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/${GITEA_REPO}/releases/download/${TAG_NAME}/${filename}" | sha256sum | awk '{ print $1 }'); then + continue + fi + if [ "$remote_hash" = "$expected_hash" ]; then + echo " [skip] ${filename} already matches SHA-256" + return 0 + fi + # Match GitHub --clobber only when the existing bytes differ. + delete_failed=0 + for asset_id in $existing; do + curl -fsS --connect-timeout 15 --max-time 60 -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets/${asset_id}" || delete_failed=1 + done + if [ "$delete_failed" -ne 0 ]; then continue; fi + fi + if response=$(curl -fsS --connect-timeout 15 --max-time 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \ + -H "Authorization: token ${GITEA_TOKEN}" \ + -F "attachment=@${file}"); then + echo " [done] ${filename} -> $(printf '%s' "$response" | tail -n 1)" + return 0 + fi done - RESP=$(curl -fsS -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \ - -H "Authorization: token ${GITEA_TOKEN}" \ - -F "attachment=@${file}") - STATUS=$(echo "$RESP" | tail -n 1) - echo " [done] ${filename} -> ${STATUS}" + echo "::error::Failed to upload ${filename} after 3 attempts." + return 1 } + # Bound outbound traffic: large raw binaries must not compete with all archives. pids=() + failed=0 for file in dist/bin/hose-use-* dist/bin/checksums.txt; do upload_asset "$file" & pids+=($!) + if [ "${#pids[@]}" -eq 2 ]; then + for pid in "${pids[@]}"; do wait "$pid" || failed=1; done + pids=() + fi done - - failed=0 - for pid in "${pids[@]}"; do - wait "$pid" || failed=1 - done + if [ "${#pids[@]}" -gt 0 ]; then + for pid in "${pids[@]}"; do wait "$pid" || failed=1; done + fi if [ "$failed" -ne 0 ]; then echo "::error::One or more Gitea assets failed to upload." exit 1 diff --git a/scripts/release-validation.test.ts b/scripts/release-validation.test.ts index 77090f5..85bb8f0 100644 --- a/scripts/release-validation.test.ts +++ b/scripts/release-validation.test.ts @@ -1,5 +1,6 @@ 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"; @@ -32,6 +33,48 @@ function repository() { 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"]; + 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: 5000 }) }; +} + describe("release preparation and publication guards", () => { test("bump rejects wrong branches, dirty trees and invalid/non-increasing versions before writes", () => { const f = repository(); @@ -93,6 +136,10 @@ describe("release preparation and publication guards", () => { 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 release archives", "Publish GitHub Release"]) { + expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}"); + } }); test("a failed background Gitea upload makes the Release step fail", () => { @@ -112,9 +159,42 @@ for arg in "$@"; do 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_HOST: "https://example.test", GITEA_REPO: "test/repo", RELEASE_TAG: "v1.0.0" }, encoding: "utf8", timeout: 5000 }); + 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: 5000 }); expect(result.status).toBe(1); expect(result.stdout).toContain("assets failed to upload"); expect(result.stdout).not.toContain("Successfully published"); }); + + 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/3"); + }); + + 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); + }); + + 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"); + }); + + test("asset transfers never exceed two concurrent workers", () => { + 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).toBeLessThanOrEqual(2); + }); }); diff --git a/src/packaging/README.packaging.md b/src/packaging/README.packaging.md index 771a71a..9e6e9ab 100644 --- a/src/packaging/README.packaging.md +++ b/src/packaging/README.packaging.md @@ -30,6 +30,8 @@ Skill 初始化明确执行 `skill install --yes`;失败会报告二进制已 - 插件 bundle:`bun run build:plugin`;`.mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。 - Release:构建前检查 tag 版本、实际 HEAD 和 main 祖先关系;手动触发也必须输入 tag。正式构建显式使用 `--release`,两个发布源都上传校验清单,后台镜像上传失败会使任务失败。 +Gitea 同时最多传输两个资产,每个资产最多尝试三次;已有文件经 SHA-256 验证一致时直接保留。镜像传输中断后,可在 main 上手动运行 Release workflow,传入原 tag 并启用 `mirror_only`:该模式下载并核对 GitHub 已发布资产,只修复 Gitea,不重建或替换 GitHub 产物,也不移动 tag。 + 版本准备使用 `codex/release-vX.Y.Z` 或 `release/vX.Y.Z` 分支及干净工作区。`bun run bump <版本|patch|minor|major>` 在写入前校验分支、递增版本和重复 tag,再同步仓库版本及生成物;全局开发版同步通过单独的 `bun run dev:override` 执行。预检失败不写版本文件;后续生成步骤若失败,会保留可复查的仓库修改以便修复。 完成本地验证后,提交发布分支、开 PR、等待 CI 和审查、合入并同步 main;然后创建带说明的 tag,依次推送 `home`、`origin`,最后检查两个源的 Release 产物。GitHub 是否能把 CI 设置为强制合并条件取决于仓库规则与套餐,workflow 本身只负责执行检查。