fix(ci): prune previous artifacts only after exact build is live

This commit is contained in:
unimatrix 2026-11-17 12:23:11 +00:00
commit cf8f9ceef9
5 changed files with 193 additions and 75 deletions

View file

@ -76,3 +76,11 @@ jobs:
printf '%s\n' '91.107.196.242 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC8x/XocsIz41fWHGty0DbZhSvafSQFt9jaHHgzdr55W root@ubuntu-4gb-fsn1-1' >> ~/.ssh/known_hosts
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

@ -1,28 +1,46 @@
# Migrated web deployment
# Migrated web deployment
The production website is hosted at `91.107.196.242`. The Forgejo Actions
workflow pins that host's SSH key and can trigger deployment only from `main`.
Its deploy key is restricted to `/usr/local/bin/dunerealms-ci-trigger`, which
rejects commits that do not match the current main branch.
Forgejo, repositories, artifact storage, the rootless runner, container data,
build workspaces and deployment state use `/mnt/HC_Volume_107481500/dunegit`.
Compatibility links preserve the existing application and home-directory paths.
The volume is part of the live service and must remain attached. The services
require its mount before starting, rather than writing to an empty mountpoint.
`promote-safe-v3.py` is installed as
`/usr/local/sbin/dunerealms-promote-safe-v3`. It prepares an immutable release,
checks a candidate website and panel, updates their shared nginx configuration,
checks public readiness, and restores the previous routing if that check fails.
Retired background workers are stopped and the active process list is saved.
The first successful promotion retires the migrated baseline systemd website
services. Subsequent candidates are supervised by `dunerealms-runtime.service`.
The separate Forgejo service remains `dunegit.service`.
Run the promoter routing checks with:
```sh
python3 -m unittest discover -s website/ops -p 'test_*.py'
```
The production website is hosted at `91.107.196.242`. The Forgejo Actions
workflow pins that host's SSH key and can trigger deployment only from `main`.
Its deploy key is restricted to `/usr/local/bin/dunerealms-ci-trigger`, which
rejects commits that do not match the current main branch.
## CI artifact retention
Forgejo, repositories, artifact storage, the rootless runner, container data,
build workspaces and deployment state use `/mnt/HC_Volume_107481500/dunegit`.
Compatibility links preserve the existing application and home-directory paths.
The volume is part of the live service and must remain attached. The services
require its mount before starting, rather than writing to an empty mountpoint.
Feature CI runs build and test without uploading the website artifact. Main
publications keep their current artifact with a one-day expiry as a fallback.
`prune-ci-artifacts.mjs` runs after the asynchronous deploy trigger and waits
for `/ci-build.json` to report the exact CI commit. Only then can it remove
older `DuneRealms-Website` artifacts belonging to completed runs. It preserves
the current build, newer artifacts, running jobs, and all other artifact names.
A changed live commit stops deletion. Failed or unconfirmed deployment leaves
previous artifacts available. Cleanup errors are warnings and do not turn an
already successful publication into a failed deployment.
`promote-safe-v3.py` is installed as
`/usr/local/sbin/dunerealms-promote-safe-v3`. It prepares an immutable release,
checks a candidate website and panel, updates their shared nginx configuration,
checks public readiness, and restores the previous routing if that check fails.
Retired background workers are stopped and the active process list is saved.
The first successful promotion retires the migrated baseline systemd website
services. Subsequent candidates are supervised by `dunerealms-runtime.service`.
The separate Forgejo service remains `dunegit.service`.
Run the promoter routing checks with:
```sh
python3 -m unittest discover -s website/ops -p 'test_*.py'
```
Forgejo removes the corresponding physical chunks through its existing
`cleanup_actions` maintenance task; deleting API records need not immediately
increase free disk space. Deployed application releases and their rollback
retention are separate from CI artifact retention. No backups or Git history
are removed by this policy.

View file

@ -1,50 +1,50 @@
import {HOUSE_STYLE_CSS} from './house-style.mjs';
import {bankRatesPage} from './bank-rates-page.mjs';
import{withCanonicalMenu,MAIN_MENU}from'./main-menu.mjs';
import{withMenuBadges}from'./menu-updates.mjs';
import{updatePortalNavigation}from'./portal-navigation.mjs';
// Package the authored web and worker sources without rewriting their content.
import {readFileSync,writeFileSync,openSync,writeSync,closeSync,readdirSync,statSync,mkdirSync,existsSync,rmSync,cpSync} from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist');
// Fail before packaging if a public menu destination or illustration is missing.
for(const [label,href,icon] of MAIN_MENU){
const url=new URL(href);
if(url.hostname==='www.dunerealms.com'){
const relative=url.pathname==='/'?'index.html':decodeURIComponent(url.pathname.slice(1));
if(!existsSync(path.join(web,relative)))throw Error('Broken public menu link: '+label+' -> '+relative);
}
if(!existsSync(path.join(web,'assets',icon)))throw Error('Missing menu artwork: '+label+' -> '+icon);
}
for(const [page,dependencies] of [['shop.html',['shop-landing.css','shop-embed.js']],['kits.html',['kits.css','kits.js']]]){
for(const file of dependencies)if(!existsSync(path.join(web,file)))throw Error('Missing '+page+' dependency: '+file);
}
// Menu badges are now published manually through Imperial Bureau.
const homepage=readFileSync(path.join(web,'index.html'),'utf8');
const legalNotice=homepage.match(/<aside class="legal-notice"[\s\S]*?<\/aside>/)?.[0];
if(!legalNotice)throw Error('Homepage legal notice is missing');
function preparePublicHtml(html){
let result=updatePortalNavigation(html);
if(!result.includes('class="legal-notice"')){
if(!result.includes('</body>'))throw Error('Public HTML page missing closing body');
result=result.replace('</body>',legalNotice+'</body>');
}
return result;
}
writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage());
let assetCount=0;let assetWriter=null;const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.zip':'application/zip','.svg':'image/svg+xml'};
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative)||/^assets\/organisation-deed(?:s)?-[a-z0-9-]+\.png$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withCanonicalMenu(withMenuBadges(bytes.toString('utf8')))):relative==='portal-navigation.css'?Buffer.concat([bytes,Buffer.from(HOUSE_STYLE_CSS)]):bytes;writeSync(assetWriter,JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})}
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});assetWriter=openSync(path.join(dist,'server/index.js'),'w');writeSync(assetWriter,'const ASSET_DATA={');collect(web);writeSync(assetWriter,'};\n');
let api=['feed-api.mjs','exchange-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,'');
writeSync(assetWriter,api+'\n'+runtime);closeSync(assetWriter);cpSync(path.join(root,'.openai/hosting.json'),path.join(dist,'.openai/hosting.json'));console.log('Built Worker with',assetCount,'embedded website assets');
if(existsSync(path.join(root,'drizzle')))cpSync(path.join(root,'drizzle'),path.join(dist,'.openai/drizzle'),{recursive:true});
// Native applications consume the same compiled chrome as the public Worker.
// nginx follows the atomically promoted current release, so no stale host copy
// can retain an old Alpha version, navigation badge or rates page.
const shared=path.join(dist,'shared-chrome');mkdirSync(shared,{recursive:true});
for(const name of ['portal-navigation.js','portal-navigation.css','release.json','menu-new-items.json','rates-and-charges.html','bank-rates.css']){
let content=readFileSync(path.join(web,name));
if(name==='portal-navigation.js')content=Buffer.from(withCanonicalMenu(withMenuBadges(content.toString('utf8'))));
if(name==='portal-navigation.css')content=Buffer.concat([content,Buffer.from(HOUSE_STYLE_CSS)]);
if(name.endsWith('.html'))content=Buffer.from(preparePublicHtml(content.toString('utf8')));
writeFileSync(path.join(shared,name),content);
}
import {HOUSE_STYLE_CSS} from './house-style.mjs';
import {bankRatesPage} from './bank-rates-page.mjs';
import{withCanonicalMenu,MAIN_MENU}from'./main-menu.mjs';
import{withMenuBadges}from'./menu-updates.mjs';
import{updatePortalNavigation}from'./portal-navigation.mjs';
// Package the authored web and worker sources without rewriting their content.
import {readFileSync,writeFileSync,openSync,writeSync,closeSync,readdirSync,statSync,mkdirSync,existsSync,rmSync,cpSync} from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist');
// Fail before packaging if a public menu destination or illustration is missing.
for(const [label,href,icon] of MAIN_MENU){
const url=new URL(href);
if(url.hostname==='www.dunerealms.com'){
const relative=url.pathname==='/'?'index.html':decodeURIComponent(url.pathname.slice(1));
if(!existsSync(path.join(web,relative)))throw Error('Broken public menu link: '+label+' -> '+relative);
}
if(!existsSync(path.join(web,'assets',icon)))throw Error('Missing menu artwork: '+label+' -> '+icon);
}
for(const [page,dependencies] of [['shop.html',['shop-landing.css','shop-embed.js']],['kits.html',['kits.css','kits.js']]]){
for(const file of dependencies)if(!existsSync(path.join(web,file)))throw Error('Missing '+page+' dependency: '+file);
}
// Menu badges are now published manually through Imperial Bureau.
const homepage=readFileSync(path.join(web,'index.html'),'utf8');
const legalNotice=homepage.match(/<aside class="legal-notice"[\s\S]*?<\/aside>/)?.[0];
if(!legalNotice)throw Error('Homepage legal notice is missing');
function preparePublicHtml(html){
let result=updatePortalNavigation(html);
if(!result.includes('class="legal-notice"')){
if(!result.includes('</body>'))throw Error('Public HTML page missing closing body');
result=result.replace('</body>',legalNotice+'</body>');
}
return result;
}
writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage());
let assetCount=0;let assetWriter=null;const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.zip':'application/zip','.svg':'image/svg+xml'};
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative)||/^assets\/organisation-deed(?:s)?-[a-z0-9-]+\.png$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withCanonicalMenu(withMenuBadges(bytes.toString('utf8')))):relative==='portal-navigation.css'?Buffer.concat([bytes,Buffer.from(HOUSE_STYLE_CSS)]):bytes;writeSync(assetWriter,JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})}
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});assetWriter=openSync(path.join(dist,'server/index.js'),'w');writeSync(assetWriter,'const ASSET_DATA={');collect(web);const buildCommit=process.env.GITHUB_SHA;if(buildCommit&&/^[0-9a-f]{40}$/.test(buildCommit)){writeSync(assetWriter,JSON.stringify('/ci-build.json')+':'+JSON.stringify(['application/json; charset=utf-8',Buffer.from(JSON.stringify({commit:buildCommit})).toString('base64')])+',');}writeSync(assetWriter,'};\n');
let api=['feed-api.mjs','exchange-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,'');
writeSync(assetWriter,api+'\n'+runtime);closeSync(assetWriter);cpSync(path.join(root,'.openai/hosting.json'),path.join(dist,'.openai/hosting.json'));console.log('Built Worker with',assetCount,'embedded website assets');
if(existsSync(path.join(root,'drizzle')))cpSync(path.join(root,'drizzle'),path.join(dist,'.openai/drizzle'),{recursive:true});
// Native applications consume the same compiled chrome as the public Worker.
// nginx follows the atomically promoted current release, so no stale host copy
// can retain an old Alpha version, navigation badge or rates page.
const shared=path.join(dist,'shared-chrome');mkdirSync(shared,{recursive:true});
for(const name of ['portal-navigation.js','portal-navigation.css','release.json','menu-new-items.json','rates-and-charges.html','bank-rates.css']){
let content=readFileSync(path.join(web,name));
if(name==='portal-navigation.js')content=Buffer.from(withCanonicalMenu(withMenuBadges(content.toString('utf8'))));
if(name==='portal-navigation.css')content=Buffer.concat([content,Buffer.from(HOUSE_STYLE_CSS)]);
if(name.endsWith('.html'))content=Buffer.from(preparePublicHtml(content.toString('utf8')));
writeFileSync(path.join(shared,name),content);
}

View file

@ -0,0 +1,58 @@
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;}
}

View file

@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {prunePublishedArtifacts} from '../scripts/prune-ci-artifacts.mjs';
const sha='a'.repeat(40);
const artifact=(id,run_id,name='DuneRealms-Website',created_at='2026-11-16T00:00:00Z')=>({id,run_id,name,created_at});
function fixture({published=true,changing=false,current=true}={}){
const deletes=[],reads=[];let liveReads=0;
const request=async(url,options={})=>{
reads.push(url);
if(url.includes('/ci-build.json'))return Response.json({commit:published&&(!changing||++liveReads===1)?sha:'b'.repeat(40)});
if(options.method==='DELETE'){deletes.push(url.split('/').pop());return new Response(null,{status:204});}
if(url.endsWith('/actions/runs/10'))return Response.json({commit_sha:sha,prettyref:'main',status:'running'});
if(url.includes('/actions/artifacts?'))return Response.json(url.endsWith('page=1')?[
...(current?[artifact(100,10,'DuneRealms-Website','2026-11-17T00:00:00Z')]:[]),
artifact(99,9),artifact(98,8),artifact(97,7,'unrelated-backup'),artifact(101,11,'DuneRealms-Website','2026-11-18T00:00:00Z')]:[]);
if(url.endsWith('/actions/runs/9'))return Response.json({status:'success'});
if(url.endsWith('/actions/runs/8'))return Response.json({status:'running'});
throw Error('Unexpected request '+url);
};
return {deletes,reads,request};
}
const run=f=>prunePublishedArtifacts({sha,runId:10,token:'fixture-token',request:f.request,attempts:1});
test('unconfirmed live build leaves all prior artifacts and avoids authenticated API calls',async()=>{
const f=fixture({published:false});assert.equal((await run(f)).pruned,0);assert.deepEqual(f.deletes,[]);assert.equal(f.reads.length,1);
});
test('confirmed publication prunes only older completed website artifacts',async()=>{
const f=fixture();assert.equal((await run(f)).pruned,1);assert.deepEqual(f.deletes,['99']);
});
test('missing current artifact fails closed',async()=>{
const f=fixture({current:false});await assert.rejects(run(f),/Current publication artifact not found/);assert.deepEqual(f.deletes,[]);
});
test('rollback or newer publication stops deletion',async()=>{
const f=fixture({changing:true});await assert.rejects(run(f),/Live build changed/);assert.deepEqual(f.deletes,[]);
});