Merge pull request 'Remove artifact pruning from the website CI critical path' (#410) from fix/remove-inline-ci-prune into main

This commit is contained in:
unimatrix 2026-11-19 18:55:20 +00:00
commit b60c90dbc3
6 changed files with 126 additions and 7 deletions

View file

@ -0,0 +1,37 @@
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: Install Node 22
uses: actions/setup-node@v4
with:
node-version: '22'
- 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

View file

@ -78,10 +78,3 @@ jobs:
ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@91.107.196.242 "$GITHUB_SHA"
rm -f ~/.ssh/deploy_key
- name: Prune previous CI artifacts after confirmed publication
if: github.ref == 'refs/heads/main'
continue-on-error: true
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node website/scripts/prune-ci-artifacts.mjs

View file

@ -0,0 +1,12 @@
The Forgejo administrator navigation trash icon opens the repository's manual
`clean-ci-artifacts.yml` action. It does not delete anything on navigation.
Click Run workflow, leave Preview enabled to inspect candidates, or untick it
to apply the limited cleanup. Only website artifacts older than seven days are
eligible; the newest six, current production, main-head and active builds stay.
Install `extra_links.tmpl` as Forgejo's `custom/templates/custom/extra_links.tmpl`
and restart the `dunegit` service to load the administrator-only link. Preserve
any existing custom extra links rather than replacing them.
Cleanup is separate from normal website builds. One-day upload artifact expiry
and the daily maintenance automation remain configured independently.

View file

@ -0,0 +1,5 @@
{{if .IsSigned}}{{if .SignedUser.IsAdmin}}
<a class="item dune-ci-cleanup" href="/git/unimatrix/MC/actions?workflow=clean-ci-artifacts.yml" title="Oude CI-artifacts opruimen" aria-label="Oude CI-artifacts opruimen">
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M5 6l1 14a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1l1-14M10 10v7M14 10v7"/></svg>
</a>
{{end}}{{end}}

View file

@ -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;}
}

View file

@ -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,[]);});