diff --git a/.gitea/workflows/build-and-package.yml b/.gitea/workflows/build-and-package.yml index ca2ebb5..72d6d83 100644 --- a/.gitea/workflows/build-and-package.yml +++ b/.gitea/workflows/build-and-package.yml @@ -4,12 +4,13 @@ on: workflow_dispatch: inputs: runtime_run_id: - description: 'Run ID from a successful Build runtime workflow (not a job/task ID)' - required: true + description: 'Optional runtime workflow run ID; defaults to the MUSRFLOW_RUNTIME_RUN_ID repository variable' + required: false permissions: contents: read actions: read + packages: write jobs: build-package: @@ -20,6 +21,8 @@ jobs: shell: bash env: ELECTRON_SKIP_BINARY_DOWNLOAD: '1' + RUNTIME_RUN_ID: ${{ inputs.runtime_run_id || vars.MUSRFLOW_RUNTIME_RUN_ID }} + PACKAGE_RUN_ID: ${{ gitea.run_id }} steps: - name: Check out muSRFlow uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 @@ -28,11 +31,9 @@ jobs: persist-credentials: false - name: Check runtime selection - env: - RUNTIME_RUN_ID: ${{ inputs.runtime_run_id }} - PACKAGE_RUN_ID: ${{ gitea.run_id }} run: | - [[ "$RUNTIME_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo 'A numeric runtime workflow run ID is required' >&2; exit 1; } + [[ "$RUNTIME_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo 'Set the MUSRFLOW_RUNTIME_RUN_ID repository variable or enter a numeric runtime_run_id' >&2; exit 1; } + echo "Selected runtime workflow run: $RUNTIME_RUN_ID" echo "Packaging run ID for Publish packages: $PACKAGE_RUN_ID" - name: Download selected runtime @@ -40,7 +41,7 @@ jobs: with: name: musrflow-runtime-linux-x64 path: runtime-download - run-id: ${{ inputs.runtime_run_id }} + run-id: ${{ env.RUNTIME_RUN_ID }} repository: ${{ gitea.repository }} github-token: ${{ secrets.GITEA_TOKEN }} @@ -88,9 +89,6 @@ jobs: cp -a dist/runtime-downloads artifacts/ cp "$RUNTIME_DIR/runtime-manifest.json" artifacts/ printf 'runtime_workflow_run=%s\nmuSRFlow=%s\n' "$RUNTIME_RUN_ID" "$(git rev-parse HEAD)" > artifacts/build-source.txt - env: - RUNTIME_RUN_ID: ${{ inputs.runtime_run_id }} - - name: Upload packages uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: @@ -99,3 +97,12 @@ jobs: if-no-files-found: error compression-level: 0 retention-days: 30 + + # Preserve the complete artifact before publishing so registry failures + # can be retried with Publish packages without recompiling anything. + - name: Publish and link packages to repository + env: + GITEA_SERVER_URL: ${{ gitea.server_url }} + GITEA_REPOSITORY: ${{ gitea.repository }} + PACKAGES_TOKEN: ${{ secrets.PACKAGES_TOKEN || secrets.GITEA_TOKEN }} + run: node scripts/ci-publish-packages.js artifacts diff --git a/.gitea/workflows/publish-packages.yml b/.gitea/workflows/publish-packages.yml index 5e8e9d3..473b941 100644 --- a/.gitea/workflows/publish-packages.yml +++ b/.gitea/workflows/publish-packages.yml @@ -4,7 +4,7 @@ on: workflow_dispatch: inputs: package_run_id: - description: 'Workflow run ID of a successful Build and package run (not the runtime run ID)' + description: 'Build and package workflow run ID with an uploaded package artifact (also retries failed publication)' required: true permissions: @@ -35,24 +35,10 @@ jobs: with: node-version: '22.23.2' - - name: Check selected build succeeded + - name: Check selected package artifact env: ACTIONS_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: | - node <<'JS' - (async () => { - const { GITEA_SERVER_URL, GITEA_REPOSITORY, PACKAGE_RUN_ID, ACTIONS_TOKEN } = process.env; - if (!/^[1-9][0-9]*$/.test(PACKAGE_RUN_ID)) throw new Error('A numeric packaging workflow run ID is required'); - const response = await fetch(`${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/actions/runs/${PACKAGE_RUN_ID}`, { - headers: { Authorization: `token ${ACTIONS_TOKEN}` }, - redirect: 'error', signal: AbortSignal.timeout(60000) - }); - if (!response.ok) throw new Error(`Cannot inspect packaging run: HTTP ${response.status}`); - const run = await response.json(); - if (run.conclusion !== 'success') throw new Error('The selected packaging run did not finish successfully'); - console.log(`Publishing package artifact from workflow run ${PACKAGE_RUN_ID}`); - })().catch(error => { console.error(error.message); process.exitCode = 1; }); - JS + run: node scripts/ci-check-package-run.js - name: Download existing packages uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 diff --git a/docs/DESKTOP_DEPLOYMENT.md b/docs/DESKTOP_DEPLOYMENT.md index 50689b2..efc9f4a 100644 --- a/docs/DESKTOP_DEPLOYMENT.md +++ b/docs/DESKTOP_DEPLOYMENT.md @@ -101,48 +101,73 @@ for 14 days, subject to PSI's storage policy. Keep release copies separately. ### Package a selected runtime +**One-time setup:** in the repository's **Settings -> Actions -> Variables**, +set **MUSRFLOW_RUNTIME_RUN_ID** to the approved successful runtime workflow run +ID. Keep the working **PACKAGES_TOKEN** Actions secret configured for registry +publication. Variables are non-secret configuration; the token must remain a +secret. See [Gitea configuration variables](https://docs.gitea.com/usage/actions/actions-variables/). + 1. After a successful runtime build, open **Actions -> Build and package -> Run workflow**. -2. Enter its workflow run ID in **runtime_run_id**. There is no automatic +2. Leave **runtime_run_id** empty to use **MUSRFLOW_RUNTIME_RUN_ID**, or enter + a runtime workflow run ID to override it for this build. There is no automatic "latest runtime" selection and no fallback to files from an earlier job. 3. The workflow downloads **musrflow-runtime-linux-x64** from this repository - using the job's read-only Actions token. It verifies and restores the bundle + using the job token's Actions read permission. It verifies and restores the bundle in a job-local directory, then validates the scientific tools before building. -4. Download **musrflow-linux-packages** from the completed run's artifacts. +4. After tests and packaging succeed, the workflow saves **musrflow-linux-packages** + as a run artifact, then **automatically publishes** the application and runtime + RPM/AppImage files to the repository's **Packages** tab. There is no second + publishing workflow or packaging run ID to enter on the normal path. This produces the application RPM/AppImage, separate runtime RPM/AppImage, checksums, runtime download bundle, runtime manifest, and build-source record. Application packaging populates electron-builder's tool cache before the runtime packagers use it. Missing output fails the job; collection errors are not suppressed. `--publish never` prevents implicit electron-builder release -publishing; uploading run artifacts does not create a release or deploy a site. +publishing; the final explicit publisher handles the package registry. Neither +step creates a Release page or deploys a site. Publication only starts after +the complete artifact is saved, so a registry failure can be retried without +recompiling (see below). + +This is the first automation step: the combined workflow is still started +manually. Tag triggers, release-version naming, draft Releases, and durable +runtime reuse are not enabled yet. Runtime artifacts still expire according +to their retention policy; saving an ID in a variable does not extend it. The old `build_runtime=false` option is removed: skipping a build does not supply a runtime on a fresh runner. The two workflow files are [build-runtime.yml](../.gitea/workflows/build-runtime.yml) and [build-and-package.yml](../.gitea/workflows/build-and-package.yml). The latter currently builds **Linux packages only**. Windows/WSL packaging and -release-page publication are separate next steps. Package-registry publishing -is available separately as described below. +release-page publication are separate next steps. The standalone publisher +remains available for recovery as described below. Both workflows use pinned artifact actions. PSI's runner must support their Gitea adaptation and artifact storage. An upload preflight failure must be resolved before compilation; a download failure should be checked for an -incorrect run ID, expired artifact, or Actions-token permissions. No personal -token is required by the normal same-repository workflow. +incorrect run ID, expired artifact, or Actions-token permissions. Artifact +download does not require a personal token; PSI registry publication uses the +**PACKAGES_TOKEN** secret described below. -### Publish to the repository Packages section +### Retry publication without rebuilding -Publishing is an explicit step, separate from compilation. This can publish an -already successful **Build and package** run without rebuilding ROOT, musrfit, -or the application. +**Build and package** now publishes automatically. Use the standalone +**Publish packages** workflow only for older builds or to retry a registry +failure. A combined run may be marked failed even though its complete package +artifact was uploaded successfully. The recovery workflow verifies that it +is a finished packaging run with the expected, unexpired artifact; a runtime +run, missing artifact, or unfinished run is rejected with a clear error. 1. Push the workflow changes, then open **Actions -> Publish packages -> Run workflow** on the updated branch. -2. Enter **package_run_id**, the workflow run ID of the successful **Build and - package** run. This is **not** the runtime run ID or a job/task ID. New +2. Enter **package_run_id**, the workflow run ID of the **Build and package** + run whose **Upload packages** step succeeded. This is **not** the runtime + run ID or a job/task ID. New packaging runs print it in **Check runtime selection** as `Packaging run ID - for Publish packages`. For older runs, open + for Publish packages`. Older upload logs also print an **Artifact download + URL**: the number immediately after `/actions/runs/` in that action-generated + URL is the run ID (not the final artifact ID). Alternatively, open `https://gitea.psi.ch/api/v1/repos/salman/muSRFlow/actions/runs` while signed in, find the successful packaging entry by its `html_url`/`head_sha`, and use its `id` field. Do not confuse that with `run_number` or assume that the @@ -165,13 +190,15 @@ and skips identical uploads; different contents fail without deleting files. Publication is not atomic: a failed upload may leave a partial package. Rerun **Publish packages** with the same ID to complete it. -The workflow requests `packages: write` for its built-in job token. If PSI's -token policy refuses uploads or repository linking (HTTP 401/403), add a +Both publishing paths request `packages: write` for the built-in job token. +PSI rejected that token for registry uploads (HTTP 401); the tested setup uses a repository **Actions secret** named **PACKAGES_TOKEN** with a token owned by -the package owner and scoped to **write:package**. Do not put tokens in files +the package owner and scoped to **write:package**. If it is already configured, +no additional secret is needed for the combined workflow. Do not put tokens in files or workflow inputs. Also ensure the repository's Packages feature is enabled. -The optional secret is used only for registry upload/linking; artifact download -still uses the job token. +The secret is passed only to the registry publishing step; artifact download +still uses the job token. Other Gitea servers may allow the built-in token +fallback, but do not remove the working PSI secret. This uses Gitea's [Generic Package Registry](https://docs.gitea.com/usage/packages/generic/), not an RPM installation repository, and explicitly diff --git a/scripts/ci-check-package-run.js b/scripts/ci-check-package-run.js new file mode 100644 index 0000000..0cfd841 --- /dev/null +++ b/scripts/ci-check-package-run.js @@ -0,0 +1,52 @@ +// Copyright (C) 2026 Zaher Salman +// SPDX-License-Identifier: GPL-3.0-or-later + +async function checkPackageRun(env = process.env, request = fetch) { + const { GITEA_SERVER_URL, GITEA_REPOSITORY, PACKAGE_RUN_ID, ACTIONS_TOKEN } = env; + if (!/^[1-9][0-9]*$/.test(PACKAGE_RUN_ID || '')) throw new Error('A numeric packaging workflow run ID is required'); + if (!/^[\w.-]+\/[\w.-]+$/.test(GITEA_REPOSITORY || '')) throw new Error('Expected owner/repository'); + if (!ACTIONS_TOKEN) throw new Error('An Actions read token is required'); + const server = new URL(GITEA_SERVER_URL); + if (server.protocol !== 'https:' || server.username || server.password || server.search || server.hash) { + throw new Error('Expected an HTTPS Gitea server URL without credentials, query, or fragment'); + } + const base = `${server.href.replace(/\/$/, '')}/api/v1/repos/${GITEA_REPOSITORY}/actions/runs/${PACKAGE_RUN_ID}`; + const headers = { Authorization: `token ${ACTIONS_TOKEN}` }; + const response = await request(base, { + headers, redirect: 'error', signal: AbortSignal.timeout(60000) + }); + if (!response.ok) throw new Error(`Cannot inspect packaging run: HTTP ${response.status}`); + const run = await response.json(); + const workflow = String(run.path || '').split('@')[0].split('/').pop(); + if (workflow !== 'build-and-package.yml') { + throw new Error(`Run ${PACKAGE_RUN_ID} is not Build and package (${run.path || 'unknown workflow'}). Use the packaging run ID, not the runtime run ID`); + } + if (!['success', 'failure'].includes(run.conclusion)) { + throw new Error('The packaging run must finish before publishing its artifacts'); + } + // A registry failure marks the whole combined run failed, but its package + // artifact was uploaded only after tests, builds, and collection succeeded. + const artifactResponse = await request(`${base}/artifacts?name=musrflow-linux-packages`, { + headers, redirect: 'error', signal: AbortSignal.timeout(60000) + }); + if (!artifactResponse.ok) throw new Error(`Cannot inspect package artifacts: HTTP ${artifactResponse.status}`); + const listing = await artifactResponse.json(); + const matches = (listing.artifacts || []).filter(artifact => artifact.name === 'musrflow-linux-packages'); + if (matches.length !== 1) throw new Error(`Run ${PACKAGE_RUN_ID} must contain one musrflow-linux-packages artifact; check its Upload packages step`); + const artifact = matches[0]; + if (artifact.expired || (artifact.expires_at && Date.parse(artifact.expires_at) <= Date.now())) { + throw new Error(`The package artifact for run ${PACKAGE_RUN_ID} has expired`); + } + console.log(`Selected packaging run ${PACKAGE_RUN_ID}, artifact ${artifact.id}: ${artifact.name}`); + if (run.conclusion === 'failure') console.log('Retrying publication from the saved package artifact; no rebuild needed'); + return artifact; +} + +module.exports = { checkPackageRun }; + +if (require.main === module) { + checkPackageRun().catch(error => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/tests/ci-publish-packages.test.js b/tests/ci-publish-packages.test.js index c4e33cb..1f65b8e 100644 --- a/tests/ci-publish-packages.test.js +++ b/tests/ci-publish-packages.test.js @@ -7,6 +7,7 @@ const os = require('os'); const path = require('path'); const crypto = require('crypto'); const { publishPackages } = require('../scripts/ci-publish-packages'); +const { checkPackageRun } = require('../scripts/ci-check-package-run'); async function main() { const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'musrflow-publish-')); @@ -35,6 +36,51 @@ async function main() { return new Response(stored.get(url)); } try { + const runEnv = { ...env, ACTIONS_TOKEN: 'actions-token' }; + let run = { path: '.gitea/workflows/build-and-package.yml', conclusion: 'success' }; + let artifacts = [{ id: 456, name: 'musrflow-linux-packages', expired: false }]; + const apiCalls = []; + async function actionsApi(url, options) { + apiCalls.push(url); + assert.strictEqual(options.headers.Authorization, 'token actions-token'); + assert.strictEqual(options.redirect, 'error'); + assert(url.startsWith('https://gitea.example.test/api/v1/repos/owner/muSRFlow/actions/runs/123')); + return Response.json(url.endsWith('/artifacts?name=musrflow-linux-packages') ? { artifacts } : run); + } + assert.strictEqual((await checkPackageRun(runEnv, actionsApi)).id, 456); + run.conclusion = 'failure'; + assert.strictEqual((await checkPackageRun(runEnv, actionsApi)).id, 456, 'registry failures must be recoverable without rebuilding'); + run.path = 'build-and-package.yml@refs/heads/master'; + assert.strictEqual((await checkPackageRun(runEnv, actionsApi)).id, 456); + run.path = '.gitea/workflows/build-runtime.yml'; + await assert.rejects(checkPackageRun(runEnv, actionsApi), /not Build and package/); + assert(apiCalls[apiCalls.length - 1].endsWith('/123'), 'reject the wrong workflow before requesting artifacts'); + run.path = '.gitea/workflows/build-and-package.yml'; + for (const conclusion of ['', 'cancelled', 'skipped']) { + run.conclusion = conclusion; + await assert.rejects(checkPackageRun(runEnv, actionsApi), /must finish/); + } + for (const conclusion of ['success', 'failure']) { + run.conclusion = conclusion; + for (const missingArtifacts of [[], [{ name: 'musrflow-runtime-linux-x64' }], + [{ name: 'musrflow-linux-packages' }, { name: 'musrflow-linux-packages' }]]) { + artifacts = missingArtifacts; + await assert.rejects(checkPackageRun(runEnv, actionsApi), /must contain one/); + } + } + artifacts = [{ name: 'musrflow-linux-packages', expired: true }]; + await assert.rejects(checkPackageRun(runEnv, actionsApi), /expired/); + artifacts = [{ name: 'musrflow-linux-packages', expires_at: '2000-01-01T00:00:00Z' }]; + await assert.rejects(checkPackageRun(runEnv, actionsApi), /expired/); + await assert.rejects(checkPackageRun(runEnv, async () => new Response(null, { status: 403 })), /inspect packaging run: HTTP 403/); + await assert.rejects(checkPackageRun(runEnv, async url => url.endsWith('/123') + ? Response.json(run) : new Response(null, { status: 403 })), /inspect package artifacts: HTTP 403/); + const callCount = apiCalls.length; + await assert.rejects(checkPackageRun({ ...runEnv, PACKAGE_RUN_ID: '../123' }, actionsApi), /numeric/); + await assert.rejects(checkPackageRun({ ...runEnv, ACTIONS_TOKEN: '' }, actionsApi), /read token/); + await assert.rejects(checkPackageRun({ ...runEnv, GITEA_SERVER_URL: 'http://example.test' }, actionsApi), /HTTPS/); + assert.strictEqual(apiCalls.length, callCount); + const names = ['musrflow-9.8.7-x86_64.rpm', 'muSRFlow-9.8.7-x86_64.AppImage', 'musrflow-runtime-9.8.7-x86_64.rpm', 'musrflow-runtime-9.8.7-x86_64.AppImage']; for (const name of names) { diff --git a/tests/release-packaging.test.js b/tests/release-packaging.test.js index fa0c65b..88b520e 100644 --- a/tests/release-packaging.test.js +++ b/tests/release-packaging.test.js @@ -94,11 +94,21 @@ assert(packageWorkflow.includes('--publish never')); assert(packageWorkflow.indexOf('node scripts/ci-restore-runtime.js') < packageWorkflow.indexOf('npx --yes electron-builder')); assert(packageWorkflow.includes('cp "dist/$file" "dist/$file.md5" "dist/$file.sha256" artifacts/')); assert(!packageWorkflow.includes('|| true')); +assert(packageWorkflow.includes('inputs.runtime_run_id || vars.MUSRFLOW_RUNTIME_RUN_ID')); +assert(packageWorkflow.includes('run-id: ${{ env.RUNTIME_RUN_ID }}')); +assert(packageWorkflow.includes('packages: write')); +assert(packageWorkflow.includes('PACKAGE_RUN_ID: ${{ gitea.run_id }}')); +assert(packageWorkflow.includes('PACKAGES_TOKEN: ${{ secrets.PACKAGES_TOKEN || secrets.GITEA_TOKEN }}')); +assert(packageWorkflow.indexOf('name: Upload packages') < packageWorkflow.indexOf('node scripts/ci-publish-packages.js artifacts')); +assert(packageWorkflow.indexOf('name: Run tests') < packageWorkflow.indexOf('name: Upload packages')); +assert(packageWorkflow.indexOf('name: Collect complete package set') < packageWorkflow.indexOf('name: Upload packages')); +assert(!packageWorkflow.includes('if: always()'), 'publication must not run after a failed build or upload'); const publishWorkflow = fs.readFileSync(path.join(root, '.gitea/workflows/publish-packages.yml'), 'utf8'); assert(publishWorkflow.includes('package_run_id:')); assert(publishWorkflow.includes('packages: write')); -assert(publishWorkflow.includes("run.conclusion !== 'success'")); +assert(publishWorkflow.includes('node scripts/ci-check-package-run.js')); +assert(publishWorkflow.indexOf('node scripts/ci-check-package-run.js') < publishWorkflow.indexOf('name: Download existing packages')); assert(publishWorkflow.includes('name: musrflow-linux-packages')); assert(publishWorkflow.includes('node scripts/ci-publish-packages.js artifacts')); assert(!publishWorkflow.includes('electron-builder'));