From e4f09b3adf64c9b8a3a5c4d9056e45b7a51ae2cd Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:50:59 +0100 Subject: [PATCH] Add a separate manual trash-can CI artifact cleanup action --- .forgejo/workflows/clean-ci-artifacts.yml | 33 +++++++++++++++ website/scripts/manual-ci-cleanup.mjs | 50 +++++++++++++++++++++++ website/tests/manual-ci-cleanup.test.mjs | 22 ++++++++++ 3 files changed, 105 insertions(+) create mode 100644 .forgejo/workflows/clean-ci-artifacts.yml create mode 100644 website/scripts/manual-ci-cleanup.mjs create mode 100644 website/tests/manual-ci-cleanup.test.mjs diff --git a/.forgejo/workflows/clean-ci-artifacts.yml b/.forgejo/workflows/clean-ci-artifacts.yml new file mode 100644 index 00000000..bb9930c4 --- /dev/null +++ b/.forgejo/workflows/clean-ci-artifacts.yml @@ -0,0 +1,33 @@ +name: "🗑️ Clean old CI artifacts" + +on: + workflow_dispatch: + inputs: + dry_run: + description: "Preview only (untick to delete eligible artifacts)" + type: boolean + default: true + +concurrency: + group: manual-ci-artifact-cleanup + cancel-in-progress: false + +jobs: + cleanup: + if: github.ref == 'refs/heads/main' + runs-on: dune-ci + timeout-minutes: 5 + steps: + - name: Checkout cleanup script + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Preview or clean old website artifacts + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DRY_RUN: ${{ inputs.dry_run }} + run: node website/scripts/manual-ci-cleanup.mjs diff --git a/website/scripts/manual-ci-cleanup.mjs b/website/scripts/manual-ci-cleanup.mjs new file mode 100644 index 00000000..e1e1c915 --- /dev/null +++ b/website/scripts/manual-ci-cleanup.mjs @@ -0,0 +1,50 @@ +import {pathToFileURL} from 'node:url'; +const API='https://www.dunerealms.com/git/api/v1/repos/unimatrix/MC'; +const LIVE='https://www.dunerealms.com/ci-build.json'; +const SHA=/^[a-f0-9]{40}$/; +const terminal=new Set(['success','failure','cancelled','skipped']); +export async function cleanArtifacts({token,dryRun=true,request=fetch,now=Date.now()}) { + if(!token)throw Error('Missing repository token'); + const api=async(path,method='GET')=>{ + const r=await request(API+path,{method,headers:{Authorization:'token '+token,Accept:'application/json'},signal:AbortSignal.timeout(20000)}); + if(!r.ok)throw Error('Artifact API failed: '+r.status); + return method==='DELETE'?null:r.json(); + }; + const live=async()=>{const r=await request(LIVE,{cache:'no-store',signal:AbortSignal.timeout(10000)});if(!r.ok)throw Error('Live release unavailable');const d=await r.json();if(!SHA.test(d.commit))throw Error('Live commit unavailable');return d.commit;}; + const active=await live(),head=(await api('/branches/main')).commit?.id; + if(!SHA.test(head))throw Error('Main commit unavailable'); + const inventory=[],ids=new Set(); + for(let page=1;;page++) { + if(page>100)throw Error('Artifact pagination exceeded safety bound'); + const rows=await api('/actions/artifacts?limit=100&page='+page); + if(!Array.isArray(rows))throw Error('Unexpected artifact inventory'); + if(!rows.length)break; + for(const row of rows){if(!Number.isSafeInteger(row.id)||ids.has(row.id))throw Error('Unstable artifact pagination');ids.add(row.id);inventory.push(row);} + } + const website=inventory.filter(a=>a.name==='DuneRealms-Website'); + for(const a of website)if(!Number.isSafeInteger(a.run_id)||!Number.isFinite(Date.parse(a.created_at))||!Number.isSafeInteger(a.size_in_bytes)||a.size_in_bytes<0)throw Error('Invalid artifact metadata'); + website.sort((a,b)=>Date.parse(b.created_at)-Date.parse(a.created_at)||b.id-a.id); + const runs=new Map(),eligible=[]; + for(const a of website.slice(6)){ + if(Date.parse(a.created_at)>=now-7*86400000)continue; + if(!runs.has(a.run_id))runs.set(a.run_id,await api('/actions/runs/'+a.run_id)); + const run=runs.get(a.run_id); + if(!terminal.has(run.status)||!SHA.test(run.commit_sha)||[active,head].includes(run.commit_sha))continue; + eligible.push(a); + } + const result={dryRun,inventoryCount:inventory.length,eligible:eligible.map(a=>({id:a.id,name:a.name,runId:a.run_id,size:a.size_in_bytes})),deleted:0,deletedBytes:0}; + for(const a of eligible){ + if(dryRun)continue; + if(await live()!==active||(await api('/branches/main')).commit?.id!==head)throw Error('Release changed; cleanup stopped'); + const run=await api('/actions/runs/'+a.run_id); + if(!terminal.has(run.status)||run.commit_sha!==runs.get(a.run_id).commit_sha)throw Error('Build state changed; cleanup stopped'); + // Never retry an uncertain DELETE. The next manual run inventories actual state. + await api('/actions/artifacts/'+a.id,'DELETE'); + result.deleted++;result.deletedBytes+=a.size_in_bytes; + } + return result; +} +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){ + try{console.log(JSON.stringify(await cleanArtifacts({token:process.env.REPO_TOKEN,dryRun:process.env.DRY_RUN!=='false'}),null,2));} + catch(error){console.error('Cleanup stopped: '+error.message);process.exitCode=1;} +} diff --git a/website/tests/manual-ci-cleanup.test.mjs b/website/tests/manual-ci-cleanup.test.mjs new file mode 100644 index 00000000..c381ae9e --- /dev/null +++ b/website/tests/manual-ci-cleanup.test.mjs @@ -0,0 +1,22 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {cleanArtifacts} from '../scripts/manual-ci-cleanup.mjs'; +const active='a'.repeat(40),head='b'.repeat(40),old='c'.repeat(40); +function fixture({changing=false,duplicate=false,invalid=false}={}){ + const deleted=[];let liveReads=0; + const row=id=>({id,run_id:id,name:'DuneRealms-Website',created_at:`2026-10-${String(id).padStart(2,'0')}T00:00:00Z`,size_in_bytes:100}); + const rows=Array.from({length:12},(_,i)=>row(i+1));rows.push({...row(13),name:'DuneKits'}); + const request=async(url,options={})=>{ + if(url.includes('/ci-build.json'))return Response.json({commit:changing&&liveReads++>0?head:active}); + if(url.endsWith('/branches/main'))return Response.json({commit:{id:head}}); + if(url.includes('/actions/artifacts?'))return Response.json(url.endsWith('page=1')?rows:duplicate?[rows[0]]:[]); + if(options.method==='DELETE'){deleted.push(Number(url.split('/').pop()));return new Response(null,{status:204});} + const id=Number(url.split('/').pop());return Response.json({status:id===4?'running':'success',commit_sha:invalid?'invalid':id===5?active:id===6?head:old}); + }; + return {deleted,request}; +} +const run=(f,dryRun=true)=>cleanArtifacts({token:'fixture',request:f.request,dryRun,now:Date.parse('2026-11-19T00:00:00Z')}); +test('preview paginates, protects newest six, live/main and running builds, and never writes',async()=>{const f=fixture(),r=await run(f);assert.deepEqual(r.eligible.map(a=>a.id),[3,2,1]);assert.deepEqual(f.deleted,[]);}); +test('apply deletes only eligible artifacts and reports declared byte totals',async()=>{const f=fixture(),r=await run(f,false);assert.deepEqual(f.deleted,[3,2,1]);assert.equal(r.deleted,3);assert.equal(r.deletedBytes,300);}); +test('release change prevents deletion',async()=>{const f=fixture({changing:true});await assert.rejects(run(f,false),/Release changed/);assert.deepEqual(f.deleted,[]);}); +test('repeated pagination fails closed',async()=>{const f=fixture({duplicate:true});await assert.rejects(run(f,false),/Unstable/);assert.deepEqual(f.deleted,[]);}); +test('unverifiable build identities are retained',async()=>{const f=fixture({invalid:true});assert.deepEqual((await run(f,false)).eligible,[]);assert.deepEqual(f.deleted,[]);});