diff --git a/.github/workflows/atomgit-mirror.yml b/.github/workflows/atomgit-mirror.yml index fe8459508..2850d4d1c 100644 --- a/.github/workflows/atomgit-mirror.yml +++ b/.github/workflows/atomgit-mirror.yml @@ -1,6 +1,8 @@ name: AtomGit mirror on: + schedule: + - cron: '17 */3 * * *' workflow_run: workflows: [CI] types: [completed] @@ -8,8 +10,8 @@ on: workflow_dispatch: inputs: run_id: - description: Original CI run that published the current GitHub release - required: true + description: Original CI run (optional; otherwise find the current published source) + required: false type: string permissions: @@ -25,7 +27,7 @@ jobs: mirror: if: >- github.repository == 'TNTcraftHIM/Piik' && github.ref == 'refs/heads/main' && - (github.event_name == 'workflow_dispatch' || + (github.event_name == 'workflow_dispatch' || github.event_name == 'schedule' || (github.event.workflow_run.event == 'push' && github.event.workflow_run.head_branch == 'main')) runs-on: ubuntu-latest @@ -35,17 +37,30 @@ jobs: - uses: actions/checkout@v6 with: persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + /scripts/ + /package.json + /package-lock.json + /.node-version - uses: actions/setup-node@v6 with: node-version-file: .node-version cache: npm + - name: Check mirror readiness without build dependencies + id: readiness + run: node scripts/release-mirror-ready.mjs + env: + GH_TOKEN: ${{ github.token }} - run: npm ci --ignore-scripts + if: steps.readiness.outputs.status == 'ready' - name: Resolve the published source id: source + if: steps.readiness.outputs.status == 'ready' run: node scripts/release-mirror-source.mjs "$PIIK_SOURCE_RUN_ID" env: GH_TOKEN: ${{ github.token }} - PIIK_SOURCE_RUN_ID: ${{ inputs.run_id || github.event.workflow_run.id }} + PIIK_SOURCE_RUN_ID: ${{ inputs.run_id }} - name: Download original Server artifacts if: steps.source.outputs.mirror == 'true' uses: actions/download-artifact@v8 @@ -77,6 +92,6 @@ jobs: - name: Explain recovery if: failure() && steps.source.outputs.mirror == 'true' run: | - printf 'Mirror failed; GitHub publication and Website are independent. Retry this workflow with original CI run %s. If artifacts expired, recover the retained original build output; do not rebuild this version. See docs/operations/github.md.\n' "$PIIK_SOURCE_RUN_ID" >> "$GITHUB_STEP_SUMMARY" + printf 'Mirror failed; the scheduled check will retry from original CI run %s. GitHub publication and Website are independent. If artifacts expired, recover the retained original build output; do not rebuild this version. See docs/operations/github.md.\n' "$PIIK_SOURCE_RUN_ID" >> "$GITHUB_STEP_SUMMARY" env: PIIK_SOURCE_RUN_ID: ${{ steps.source.outputs.run_id }} diff --git a/docs/operations/github.md b/docs/operations/github.md index 20430500a..4aeb607a2 100644 --- a/docs/operations/github.md +++ b/docs/operations/github.md @@ -94,24 +94,47 @@ Image checks, version identity and retries follow source and Release mirror. GitHub owns development, issues and original packages. AtomGit's configured repository synchronization handles branches, tags and commits; the **AtomGit mirror** GitHub workflow separately copies published binary assets. +Git synchronization remains AtomGit's responsibility; this workflow does not push, +create or change Git references, and does not ask users to synchronize them manually. Its repository Actions secret is `ATOMGIT_TOKEN`. Never put this token in source, a remote URL or a distributed package. GitHub publication keeps its scoped token. -After a completed main-push CI run, the workflow checks whether that run published -the current stable GitHub release. A later failed container step does not prevent -mirroring already-published packages. It downloads the matching run's complete +After a completed main-push CI run, the workflow checks the current stable GitHub +release and finds its original publishing CI run, even when the triggering run +only updated tooling. A later failed container step does not prevent +mirroring already-published packages. It downloads the source run's complete original Server and App artifacts and invokes `scripts/mirror-release.mjs`. -Runs without the current published release are skipped. GitHub publication -and **Website** do not depend on mirror success. An unfinished mirror remains a +GitHub publication and **Website** do not depend on mirror success. An unfinished mirror remains a prerelease until every package passes anonymous full-download SHA-256 validation. This includes the original signed APK and its already-built ZIP wrapper. +Every three hours the same workflow also checks the latest GitHub release's mirror +metadata. A stable mirror with the matching source marker and complete package +inventory of uploaded attachments needs no further work; provider-generated source +archives do not count as packages. A missing source commit or matching tag is +reported as deferred until AtomGit's scheduled Git synchronization completes. +Both outcomes use a sparse tools-only checkout and skip dependency installation +and artifact downloads. API failures +or conflicting source identities remain failures, not successful deferrals. + +When ready, recovery locates the completed main-push CI run for that exact source, +downloads its original artifacts and resumes the existing publisher. It never +builds software. The publisher verifies every package anonymously before marking +the mirror stable; the periodic metadata check reuses that completion boundary. +Expired original artifacts require retained original build output, not rebuilding +the same published version. A stable release missing packages is an explicit +integrity failure and is never silently replaced. + For recovery, rerun **AtomGit mirror** with the original publishing CI run ID: ```sh gh workflow run atomgit-mirror.yml --repo TNTcraftHIM/Piik --ref main -f run_id=RUN_ID ``` +The run ID is optional for a manual status check; without it, the workflow uses +the same latest-release lookup as its scheduled check. Ordinary delayed source +synchronization or interrupted uploads need no manual trigger. + The source must be a completed main-push CI run matching the latest published GitHub release. The workflow runs trusted main tooling and treats artifacts only as data. A superseded release cannot complete a new mirror. Both publishers reject diff --git a/scripts/mirror-release.mjs b/scripts/mirror-release.mjs index 95133b321..4a2f7ff13 100644 --- a/scripts/mirror-release.mjs +++ b/scripts/mirror-release.mjs @@ -3,6 +3,7 @@ import { createHash } from "node:crypto"; import { openAsBlob } from "node:fs"; import { setTimeout as delay } from "node:timers/promises"; import { readReleaseArtifacts } from "./release-artifacts.mjs"; +import { mirrorSourceReady } from "./release-mirror-ready.mjs"; const [directory, version, revision, option] = process.argv.slice(2); if (option && option !== "--dry-run") { @@ -111,6 +112,8 @@ if (option === "--dry-run") { const body = `${source.body ?? ""}\n\nSource: https://github.com/${repository}/commit/${revision}\n\n${marker}\n`; if (!release || release.prerelease) requireLatestSource(); if (!release) { + if (!await mirrorSourceReady(version, revision, request)) + throw new Error("AtomGit Git synchronization is pending; the scheduled mirror check will resume after the matching commit and tag arrive"); const repo = await request(""); if (!repo || repo.private || !repo.default_branch) throw new Error("A public initialized AtomGit mirror is required"); release = await request("/releases", "POST", { @@ -133,8 +136,9 @@ if (option === "--dry-run") { // Signed locations and callback headers are credentials; never log them. let response; try { + // The signed APK exceeded three minutes on the cross-border upload path. response = await fetch(upload.url, { method: "PUT", redirect: "error", headers: upload.headers, - body: await openAsBlob(file.path), signal: AbortSignal.timeout(180_000) }); + body: await openAsBlob(file.path), signal: AbortSignal.timeout(600_000) }); if (!response.ok) throw new Error("HTTP " + response.status); await response.arrayBuffer(); } catch (error) { diff --git a/scripts/release-mirror-ready.mjs b/scripts/release-mirror-ready.mjs new file mode 100644 index 000000000..3282a78cf --- /dev/null +++ b/scripts/release-mirror-ready.mjs @@ -0,0 +1,68 @@ +import { execFileSync } from "node:child_process"; +import { appendFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +const repository = "TNTcraftHIM/Piik"; +export async function readMirror(path) { + const response = await fetch(`https://api.atomgit.com/api/v5/repos/${repository}${path}`, { + redirect: "error", signal: AbortSignal.timeout(30_000), headers: { Accept: "application/json" }, + }); + if (response.status === 404) return null; + if (!response.ok) throw new Error(`AtomGit readiness ${path}: HTTP ${response.status}`); + return response.json(); +} + +// Git synchronization belongs to AtomGit. Release creation must never create a tag. +export async function mirrorSourceReady(version, revision, read = readMirror) { + const commit = await read(`/commits/${revision}`); + if (!commit) return false; + if (commit.sha !== revision) throw new Error("AtomGit source commit differs from the published source"); + for (let page = 1; page <= 10; page++) { + const tags = await read(`/tags?per_page=100&page=${page}`); + if (!Array.isArray(tags)) throw new Error("Unexpected AtomGit tag list"); + const tag = tags.find(tag => tag.name === version); + if (tag) { + if (tag.commit?.sha !== revision) throw new Error("AtomGit release tag belongs to another source revision"); + return true; + } + if (tags.length < 100) return false; + } + throw new Error("AtomGit tag inventory exceeds 10 pages; source readiness cannot be determined"); +} + +export async function mirrorReadiness(source, read = readMirror) { + if (source.draft !== false || source.prerelease !== false || typeof source.tag_name !== "string" + || !/^[a-f0-9]{40}$/.test(source.target_commitish)) throw new Error("A published GitHub release with a full source SHA is required"); + const version = source.tag_name, revision = source.target_commitish; + const mirror = await read(`/releases/tags/${encodeURIComponent(version)}`); + if (mirror) { + if (mirror.tag_name !== version || ![true, false].includes(mirror.prerelease) + || !mirror.body?.split(/\r?\n/).includes(``)) + throw new Error("Existing mirror release belongs to a different or unknown source revision"); + const packages = source.assets?.filter(asset => asset.name?.startsWith("piik-")); + const complete = packages?.length > 0 && Array.isArray(mirror.assets) && packages.every(asset => { + const matches = mirror.assets.filter(candidate => candidate.type === "attach" && candidate.name === asset.name); + return asset.state === "uploaded" && /^sha256:[a-f0-9]{64}$/.test(asset.digest ?? "") + && matches.length === 1 && matches[0].size === asset.size + && matches[0].browser_download_url === `https://atomgit.com/${repository}/releases/download/${version}/${asset.name}`; + }); + if (!mirror.prerelease) { + if (!complete) throw new Error("Published mirror is incomplete; it cannot be silently replaced"); + return { status: "complete", version, revision }; + } + } + return { status: await mirrorSourceReady(version, revision, read) ? "ready" : "deferred", version, revision }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const source = JSON.parse(execFileSync("gh", ["api", `repos/${repository}/releases/latest`], { + encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000, + })); + const result = await mirrorReadiness(source); + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `status=${result.status}\n`); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, + result.status === "deferred" ? `Mirror ${result.version} deferred until AtomGit's scheduled Git synchronization supplies the matching commit and tag. The next mirror check will resume automatically.\n` + : result.status === "complete" ? `Mirror ${result.version} is already stable with the complete published attachment inventory.\n` + : `Mirror ${result.version} is ready to resume from original CI artifacts.\n`); + console.log(JSON.stringify(result)); +} diff --git a/scripts/release-mirror-source.mjs b/scripts/release-mirror-source.mjs index 0d5364462..1b5c46e3b 100644 --- a/scripts/release-mirror-source.mjs +++ b/scripts/release-mirror-source.mjs @@ -9,6 +9,15 @@ const gh = (path) => JSON.parse(execFileSync("gh", ["api", `repos/${repository}/ })); export function resolveMirrorSource(runId, automatic = false) { + if (!runId && automatic) { + const latest = gh("releases/latest"); + if (latest.draft !== false || latest.prerelease !== false || !isReleaseVersion(latest.tag_name) + || !/^[a-f0-9]{40}$/.test(latest.target_commitish)) throw new Error("A published stable GitHub release with a full source SHA is required"); + const runs = gh(`actions/workflows/repository-hygiene.yml/runs?event=push&branch=main&status=completed&head_sha=${latest.target_commitish}&per_page=100`); + const source = runs.workflow_runs?.find(run => run.head_sha === latest.target_commitish); + if (!source) throw new Error("The published release's original completed CI run is unavailable; do not rebuild its packages"); + return resolveMirrorSource(String(source.id), true); + } if (!/^[1-9]\d*$/.test(runId) || !Number.isSafeInteger(Number(runId))) { throw new Error("Provide the original CI run's numeric ID"); } @@ -34,7 +43,7 @@ export function resolveMirrorSource(runId, automatic = false) { } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - const source = resolveMirrorSource(process.argv[2], process.env.GITHUB_EVENT_NAME === "workflow_run"); + const source = resolveMirrorSource(process.argv[2], ["workflow_run", "schedule"].includes(process.env.GITHUB_EVENT_NAME) || !process.argv[2]); const output = { mirror: source !== null, ...source }; if (process.env.GITHUB_OUTPUT) { appendFileSync(process.env.GITHUB_OUTPUT, diff --git a/tests/publish-release.test.ts b/tests/publish-release.test.ts index e336dff6c..e4323b51b 100644 --- a/tests/publish-release.test.ts +++ b/tests/publish-release.test.ts @@ -53,7 +53,7 @@ describe("AtomGit mirror publication", () => { }); async function mirror(options: { existing?: "pending" | "published" | "unknown"; corrupt?: boolean; wrongSource?: boolean; wrongDigest?: boolean; missing?: boolean; uploadFailure?: boolean | number; - stale?: boolean; supersededDuringUpload?: boolean; + stale?: boolean; supersededDuringUpload?: boolean; mirrorSourceMissing?: boolean; downloadFault?: { remaining: number; name: "TimeoutError" | "TypeError" }; fault?: { method: string; remaining: number; status: number | "timeout" | "body-timeout" } } = {}) { const interrupted = (bytes: Uint8Array, error: Error) => { @@ -128,6 +128,8 @@ describe("AtomGit mirror publication", () => { ? Response.json({ id: 42, tag_name: version, body: options.existing === "unknown" ? "unknown" : marker, prerelease: pending, assets: [...present] }) : new Response(null, { status: 404 }); if (path === "") return Response.json({ private: false, default_branch: "master" }); + if (path === `/commits/${revision}`) return options.mirrorSourceMissing ? new Response(null, { status: 404 }) : Response.json({ sha: revision }); + if (path === "/tags?per_page=100&page=1") return Response.json([{ name: version, commit: { sha: revision } }]); if (path === "/releases" && method === "POST") { const body = JSON.parse(String(init?.body)); expect(body.release_status).toBe("pre"); @@ -165,6 +167,12 @@ describe("AtomGit mirror publication", () => { return { mutations, failure }; } + it("waits for AtomGit Git synchronization without creating a release or tag", async () => { + const result = await mirror({ mirrorSourceMissing: true }); + expect(result.failure).toContain("Git synchronization is pending"); + expect(result.mutations).toEqual([]); + }); + it("copies the published bytes, verifies anonymous downloads and marks stable last", async () => { const result = await mirror(); expect(result.failure).toBeUndefined(); diff --git a/tests/release-mirror-ready.test.ts b/tests/release-mirror-ready.test.ts new file mode 100644 index 000000000..b61396828 --- /dev/null +++ b/tests/release-mirror-ready.test.ts @@ -0,0 +1,54 @@ +import { expect, test, vi } from "vitest"; +import { mirrorReadiness, mirrorSourceReady, readMirror } from "../scripts/release-mirror-ready.mjs"; + +const revision = "a".repeat(40), version = "v2.6.1"; +const asset = { name: "piik-app-fixture.zip", state: "uploaded", size: 1024, digest: `sha256:${"b".repeat(64)}` }; +const source = { tag_name: version, target_commitish: revision, draft: false, prerelease: false, assets: [asset] }; +const mirror = { tag_name: version, prerelease: false, body: ``, assets: [{ + type: "attach", name: asset.name, size: asset.size, browser_download_url: `https://atomgit.com/TNTcraftHIM/Piik/releases/download/${version}/${asset.name}`, +}, ...["zip", "tar.gz", "tar.bz2", "tar"].map(extension => ({ type: "source", name: `${version}.${extension}` }))] }; + +test("a completed stable mirror needs only its metadata and no source search or package download", async () => { + const read = vi.fn(async () => mirror); + expect(await mirrorReadiness(source, read)).toEqual({ status: "complete", version, revision }); + expect(read.mock.calls).toEqual([[`/releases/tags/${version}`]]); +}); + +test.each(["commit", "tag"])("missing synced %s defers without a Git mutation", async missing => { + const read = vi.fn(async (path: string) => path.startsWith("/releases/") ? null + : path.startsWith("/commits/") ? missing === "commit" ? null : { sha: revision } : []); + expect(await mirrorReadiness(source, read)).toEqual({ status: "deferred", version, revision }); +}); + +test("a pending release resumes only after its exact tag and source exist", async () => { + const read = vi.fn(async (path: string) => path.startsWith("/releases/") ? { ...mirror, prerelease: true, assets: [] } + : path.startsWith("/commits/") ? { sha: revision } : [{ name: version, commit: { sha: revision } }]); + expect(await mirrorReadiness(source, read)).toEqual({ status: "ready", version, revision }); + expect(read.mock.calls.every(([path]) => path.startsWith("/releases/") || path.startsWith("/commits/") || path.startsWith("/tags?"))).toBe(true); +}); + +test("a missing attachment in a published release and a conflicting tag fail rather than silently repairing identity", async () => { + await expect(mirrorReadiness(source, async () => ({ ...mirror, assets: [] }))).rejects.toThrow("incomplete"); + await expect(mirrorSourceReady(version, revision, async (path: string) => path.startsWith("/commits/") + ? { sha: revision } : [{ name: version, commit: { sha: "c".repeat(40) } }])).rejects.toThrow("another source"); +}); + +test("a provider source archive cannot stand in for a published package", async () => { + await expect(mirrorReadiness(source, async () => ({ ...mirror, + assets: mirror.assets.map(asset => ({ ...asset, type: "source" })), + }))).rejects.toThrow("incomplete"); +}); + +test("a truncated tag inventory fails after ten pages rather than claiming the source is absent", async () => { + const read = vi.fn(async (path: string) => path.startsWith("/commits/") ? { sha: revision } + : Array.from({ length: 100 }, (_, index) => ({ name: `other-${index}`, commit: { sha: revision } }))); + await expect(mirrorSourceReady(version, revision, read)).rejects.toThrow("exceeds 10 pages"); + expect(read).toHaveBeenCalledTimes(11); + expect(read.mock.calls.at(-1)).toEqual(["/tags?per_page=100&page=10"]); +}); + +test("readiness treats an unavailable API as failure, not pending synchronization", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 503 }))); + try { await expect(readMirror("/commits/" + revision)).rejects.toThrow("HTTP 503"); } + finally { vi.unstubAllGlobals(); } +}); diff --git a/tests/release-mirror-source.test.ts b/tests/release-mirror-source.test.ts index eb457bed9..1e6fe3e51 100644 --- a/tests/release-mirror-source.test.ts +++ b/tests/release-mirror-source.test.ts @@ -25,6 +25,13 @@ function api(source = run, latest = release) { beforeEach(() => { command.mockReset(); api(); }); describe("mirror source authority", () => { + it("scheduled recovery finds the original completed main CI by published source", () => { + const existing = command.getMockImplementation()!; + command.mockImplementation((program: string, args: string[]) => args[1].includes("actions/workflows/") + ? JSON.stringify({ workflow_runs: [run] }) : existing(program, args)); + expect(resolveMirrorSource("", true)).toEqual({ run_id: "12345", version: release.tag_name, revision }); + expect(command.mock.calls.some(([, args]) => args[1].includes(`head_sha=${revision}`))).toBe(true); + }); it("binds automatic and manual retries to the published source run", () => { const expected = { run_id: "12345", version: release.tag_name, revision }; expect(resolveMirrorSource("12345", true)).toEqual(expected);