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

58 lines
3.4 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=/^[0-9a-f]{40}$/;
// The deployment trigger is asynchronous. Never prune on its acknowledgement:
// the exact compiled build must first be served by the public website.
export async function prunePublishedArtifacts({sha,runId,token,request=fetch,wait=ms=>new Promise(resolve=>setTimeout(resolve,ms)),attempts=40}){
if(!SHA.test(sha||'')||!/^\d+$/.test(String(runId))||!token)throw Error('Missing CI publication identity or token');
let live=false;
for(let i=0;i<attempts;i++){
try{
const response=await request(LIVE+'?expected='+sha,{cache:'no-store',signal:AbortSignal.timeout(10000)});
if(response.ok&&(await response.json()).commit===sha){live=true;break;}
}catch{}
if(i+1<attempts)await wait(15000);
}
if(!live)return {pruned:0,reason:'Exact build not yet confirmed live; previous artifacts retained'};
const api=async(path,method='GET')=>{
const response=await request(API+path,{method,headers:{Authorization:'token '+token,Accept:'application/json'},signal:AbortSignal.timeout(20000)});
if(!response.ok)throw Error('CI artifact API returned '+response.status);
return method==='DELETE'?null:response.json();
};
const run=await api('/actions/runs/'+runId);
if(run.commit_sha!==sha||run.prettyref!=='main')throw Error('Refusing cleanup for a different commit or branch');
const artifacts=[];
for(let page=1;;page++){
if(page>100)throw Error('Artifact pagination exceeded safety bound');
const rows=await api('/actions/artifacts?limit=50&page='+page);
if(!Array.isArray(rows))throw Error('Unexpected artifact inventory');
artifacts.push(...rows);
if(!rows.length)break;
}
const current=artifacts.filter(a=>a.name==='DuneRealms-Website'&&String(a.run_id)===String(runId));
if(!current.length)throw Error('Current publication artifact not found; keeping previous builds');
const cutoff=Math.min(...current.map(a=>Date.parse(a.created_at)));
if(!Number.isFinite(cutoff))throw Error('Invalid current artifact date');
const previous=artifacts.filter(a=>a.name==='DuneRealms-Website'&&String(a.run_id)!==String(runId)&&Date.parse(a.created_at)<cutoff);
const statuses=new Map();
let pruned=0;
for(const artifact of previous){
if(!Number.isSafeInteger(artifact.id)||!Number.isSafeInteger(artifact.run_id))throw Error('Invalid artifact identity');
if(!statuses.has(artifact.run_id))statuses.set(artifact.run_id,(await api('/actions/runs/'+artifact.run_id)).status);
if(!['success','failure','cancelled','skipped'].includes(statuses.get(artifact.run_id)))continue;
// A newer publication or rollback must not race this cleanup.
const response=await request(LIVE+'?cleanup='+sha,{cache:'no-store',signal:AbortSignal.timeout(10000)});
if(!response.ok||(await response.json()).commit!==sha)throw Error('Live build changed; cleanup stopped');
await api('/actions/artifacts/'+artifact.id,'DELETE');
pruned++;
}
return {pruned,reason:'Previous completed CI artifacts removed; current publication retained'};
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
try{console.log(JSON.stringify(await prunePublishedArtifacts({sha:process.env.GITHUB_SHA,runId:process.env.GITHUB_RUN_ID,token:process.env.REPO_TOKEN})));}
catch{console.warn('::warning::CI artifact cleanup stopped safely; inspect artifact retention before retrying.');process.exitCode=1;}
}