MC/website/scripts/manual-ci-cleanup.mjs
2026-11-27 23:43:05 +00:00

50 lines
3.2 KiB
JavaScript

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