import {resolve} from 'node:path'; import {mkdir,mkdtemp,writeFile} from 'node:fs/promises'; const root=resolve(import.meta.dir,'..'); if(process.argv.includes('--check')){console.log('Concurrent image experiment parsed without accessing the stand');process.exit(0);} const base=process.env.BASE_URL??'http://127.0.0.1:28204'; const prefix='st_'+crypto.randomUUID().replaceAll('-','').slice(0,16); async function command(args:string[]){const p=Bun.spawn(args,{cwd:root,stdout:'pipe',stderr:'pipe',signal:AbortSignal.timeout(60000)});const [out,err]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);if(await p.exited!==0)throw new Error('Image experiment command failed');return out;} async function guard(){const p=Bun.spawn(['/home/rey/.local/bin/game-running'],{stdout:'ignore',stderr:'pipe'});await new Response(p.stderr).text();if(await p.exited!==1)throw new Error('Close the game before the memory experiment');} async function json(method:string,path:string,status:number,token?:string,body?:unknown,headers:Record={}){const r=await fetch(base+path,{method,headers:{...headers,...(token?{Authorization:'Bearer '+token}:{}),...(body!==undefined?{'Content-Type':'application/json'}:{})},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(30000)});const out=await r.json() as any;if(r.status!==status)throw new Error('Image experiment HTTP status differs');return out;} const parent=resolve(root,'evidence/concurrent-images');await mkdir(parent,{recursive:true}); const evidence=await mkdtemp(resolve(parent,'run-')); await writeFile(resolve(evidence,'run.json'),JSON.stringify({run_id:prefix,started_at:new Date().toISOString(),state:'started'})+'\n',{flag:'wx'}); let finished=false,touched=false,primary:unknown,monitorError:unknown,result:unknown; let monitor:Promise|undefined;const cleanupErrors:string[]=[];const samples:any[]=[]; try{ await guard(); const published=(await command([resolve(root,'scripts/compose.sh'),'port','lb','8080'])).trim(); if(new URL(base).origin!=='http://'+published)throw new Error('API URL differs from the pinned coursework load balancer'); const raw=new Uint8Array(await Bun.file(resolve(root,'.local/concurrent.png')).arrayBuffer()); touched=true; await command([resolve(root,'scripts/compose.sh'),'up','-d','--no-deps','--force-recreate','api']); await command([process.execPath,'--no-env-file','student-tests/wait.ts']); const user=await json('POST','/api/v1/users',201,undefined,{username:prefix,display_name:'Synthetic image experiment',password:'synthetic-password-123'}); const session=await json('POST','/api/v1/auth/sessions',201,undefined,undefined,{Authorization:'Basic '+Buffer.from(prefix+':synthetic-password-123').toString('base64')}); const chat=await json('POST','/api/v1/chats',201,session.token,{title:'Ten concurrent image uploads',member_ids:[user.id]}); const ids=(await command([resolve(root,'scripts/compose.sh'),'ps','-q','api'])).trim().split(/\s+/); monitor=(async()=>{while(!finished){const out=await command(['docker','stats','--no-stream','--format','{{json .}}',...ids]);for(const line of out.trim().split('\n').filter(Boolean)){const row=JSON.parse(line);samples.push({name:row.Name,cpu_percent:row.CPUPerc,memory:row.MemUsage});}}})().catch(error=>{monitorError=error;finished=true;}); const uploads=Array.from({length:10},async(_,index)=>{ let offset=0; const body=new ReadableStream({async pull(controller){if(offset===raw.length){controller.close();return;}await Bun.sleep(30);const next=Math.min(raw.length,offset+65536);controller.enqueue(raw.slice(offset,next));offset=next;}}); const r=await fetch(base+'/api/v1/chats/'+chat.id+'/attachments?filename=concurrent-'+index+'.png',{method:'POST',headers:{Authorization:'Bearer '+session.token,'Content-Type':'image/png'},body,signal:AbortSignal.timeout(30000)}); const payload=await r.json() as any; if(r.status!==201&&r.status!==503)throw new Error('Unexpected concurrent upload status'); if(r.status===201){const content=await fetch(base+'/api/v1/attachments/'+payload.id+'/content',{headers:{Authorization:'Bearer '+session.token},signal:AbortSignal.timeout(10000)});const bytes=new Uint8Array(await content.arrayBuffer());if(content.status!==200||!Buffer.from(bytes).equals(Buffer.from(raw)))throw new Error('Concurrent upload original was corrupted');} return r.status; }); const results=await Promise.allSettled(uploads);finished=true;await monitor;if(monitorError)throw monitorError; const statuses:number[]=[];for(const r of results){if(r.status==='rejected')throw r.reason;statuses.push(r.value);} if(!statuses.includes(201))throw new Error('No upload succeeded'); const peaks=[]; for(const id of ids){ const pid=Number((await command(['docker','inspect','--format','{{.State.Pid}}',id])).trim()); if(!Number.isSafeInteger(pid)||pid<=0)throw new Error('Invalid owned API process ID'); const group=(await Bun.file('/proc/'+pid+'/cgroup').text()).split('\n').find(line=>line.startsWith('0::'))?.slice(3); if(!group||!group.startsWith('/')||group.includes('..'))throw new Error('Invalid cgroup path'); const peak=Number((await Bun.file('/sys/fs/cgroup'+group+'/memory.peak').text()).trim()); if(!Number.isFinite(peak)||peak<=0||peak>=2*1024**3)throw new Error('Container memory peak exceeded budget'); peaks.push({instance:id.slice(0,12),memory_peak_bytes:peak}); } await json('GET','/health/ready',200); await guard(); result={attempts:10,image_bytes:raw.length,success:statuses.filter(s=>s===201).length,rejected_503:statuses.filter(s=>s===503).length,peaks,samples,originals_verified:true}; }catch(error){primary=error;} finally{ finished=true; if(monitor)await monitor; if(touched)try{await command([resolve(root,'scripts/compose.sh'),'run','--rm','--no-deps','fixture-cleanup',prefix]);}catch{cleanupErrors.push('owned_fixture_cleanup');} } if(primary||cleanupErrors.length){await writeFile(resolve(evidence,'failure.json'),JSON.stringify({run_id:prefix,primary:primary instanceof Error?primary.name:primary?'unknown':null,cleanup_errors:cleanupErrors})+'\n');throw new Error('Concurrent image experiment failed; inspect this run');} await writeFile(resolve(evidence,'summary.json'),JSON.stringify({run_id:prefix,complete:true,result},null,2)+'\n',{flag:'wx'}); console.log('PASS concurrent image memory: '+evidence);