Files
mtusi2026lab6/student-tests/grafana-retry.ts
T

16 lines
9.5 KiB
TypeScript

import{resolve}from'node:path';import{mkdir,readFile,writeFile}from'node:fs/promises';import{createOwnedFaultRunner,OwnedFaultFailure}from'../scripts/lib/owned-fault';import{createAccountHTTP}from'../scripts/lib/openobserve-account-http';
if(process.argv.includes('--check')){console.log('Scoped synthetic retry entrypoint validated without credentials, Docker or mutation');process.exit(0)}if(process.platform!=='linux'||!process.argv.includes('--run-native'))throw Error('Explicit native owned retry operation required');
const root=resolve(import.meta.dir,'..'),project='mtuci-vp6-medvedev',out=resolve(root,'.local/grafana-retry-'+crypto.randomUUID());await mkdir(out,{mode:0o700});await writeFile(resolve(out,'CLAIM.json'),JSON.stringify({root,project,checkedAt:new Date().toISOString(),scope:'one synthetic accepted job; reversible missing staging object; no DB/queue incident repeat'})+'\n',{flag:'wx',mode:0o600});let stage='ownership',failure:string|undefined,failureStage:string|undefined,cleanupFailure:string|undefined,token='',sequence=0,attachmentId='',traceId='';const observations:any[]=[];
function command(args:string[]){const r=Bun.spawnSync(args,{cwd:root,stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw Error('Owned command failed at '+stage);return new TextDecoder().decode(r.stdout).trim()}
function owned(service:string,id?:string){const c=JSON.parse(command(['docker','inspect',id??project+'-'+service+'-1']))[0];if(c.Config.Labels['com.docker.compose.project']!==project||c.Config.Labels['com.docker.compose.project.working_dir']!==root||c.Config.Labels['com.docker.compose.service']!==service)throw Error('Owned resource guard failed');return c}
const worker=owned('worker'),storage=owned('s3');if(!worker.State.Running||!storage.State.Running)throw Error('Owned worker/storage must already be ready');const rawS3=JSON.parse(await readFile(resolve(root,'.local/s3_root'),'utf8')),ip=storage.NetworkSettings.Networks[project+'_private']?.IPAddress;if(!/^\d+\.\d+\.\d+\.\d+$/.test(ip??''))throw Error('Owned storage private address missing');const s3=new Bun.S3Client({endpoint:'http://'+ip+':9000',bucket:rawS3.Bucket,accessKeyId:rawS3.Access,secretAccessKey:rawS3.Secret,region:'us-east-1'});
const identity=process.env.VP6_SECRET_IDENTITY_FILE;if(!identity?.startsWith(root+'/.local/')||!identity.endsWith('/identity.agekey'))throw Error('Explicit owned encryption identity required');async function seal(name:string,bytes:Uint8Array){const r=Bun.spawnSync(['/home/rey/.local/bin/age','--encrypt','-i',identity!],{stdin:bytes,stdout:'pipe',stderr:'pipe'});if(r.exitCode!==0)throw Error('Private archival failed');await writeFile(resolve(out,name+'.age'),r.stdout,{flag:'wx',mode:0o600})}
const correlations=new Map<string,string|null>();const http=createAccountHTTP({request:async input=>{const binary=input.body instanceof Uint8Array,r=await fetch('http://127.0.0.1:28206'+input.path,{method:input.method,headers:{'Content-Type':binary?'image/png':'application/json',Authorization:input.auth??''},body:input.body===undefined?undefined:binary?input.body as Uint8Array<ArrayBuffer>:JSON.stringify(input.body),signal:AbortSignal.timeout(7000)});correlations.set(input.captureId,r.headers.get('X-Request-Id'));return{status:r.status,chunks:r.body??(async function*(){})()}},capture:async c=>{await seal(c.captureId,c.raw);await writeFile(resolve(out,c.captureId+'.meta.json'),JSON.stringify({status:c.status,outcome:c.outcome,complete:c.complete,bytes:c.raw.length})+'\n',{flag:'wx',mode:0o600})}},1048576);
async function api(path:string,method='GET',body?:unknown,auth?:string){const captureId='response-'+String(++sequence).padStart(4,'0'),r=await http({path,method,body,auth:auth??(token?'Bearer '+token:undefined),captureId});return{...r,requestId:correlations.get(captureId)}}
function job(){const sql="SELECT jsonb_build_object('id',j.id,'attachment_id',a.id,'status',a.status,'error_code',a.error_code,'attempt',j.attempt,'completed',j.completed,'traceparent',j.traceparent,'accepted_at',a.accepted_at,'first_ready_at',a.first_ready_at)::text FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id='"+attachmentId+"' AND j.pipeline_version=a.pipeline_version";return JSON.parse(command(['docker','exec',project+'-postgres-1','psql','-X','-U','messenger','-d','messenger','-Atq','-v','ON_ERROR_STOP=1','-c',sql]))}
async function record(kind:string,data:any){observations.push({at:new Date().toISOString(),kind,...data});await writeFile(resolve(out,'observation-'+observations.length+'.json'),JSON.stringify(observations.at(-1),null,2)+'\n',{flag:'wx',mode:0o600})}
try{stage='fixture-auth';const username='retry_'+crypto.randomUUID().slice(0,8),password='Aa1!'+crypto.randomUUID();await seal('fixture-auth',Buffer.from(JSON.stringify({username,password})));if((await api('/api/v1/users','POST',{username,display_name:'Owned retry fixture',password})).status!==201)throw Error('Fixture user create failed');const login=await api('/api/v1/auth/sessions','POST',undefined,'Basic '+Buffer.from(username+':'+password).toString('base64'));if(login.status!==201||typeof login.body?.token!=='string')throw Error('Fixture login failed');token=login.body.token;const chat=await api('/api/v1/chats','POST',{title:'Owned retry trace',member_ids:[login.body.user.id]});if(chat.status!==201)throw Error('Fixture chat failed');const image=await readFile(resolve(root,'tests/fixtures/sample.png'));
await createOwnedFaultRunner({acquire:async()=>({id:worker.Id,image:worker.Image,key:'',bytes:undefined as Uint8Array|undefined,hidden:false}),exercise:async lease=>{try{stage='pause-only-owned-worker';if(owned('worker',lease.id).Image!==lease.image)throw Error('Worker image mismatch');command(['docker','stop','--time','8',lease.id]);stage='accept-one-owned-upload';const accepted=await api('/api/v1/chats/'+chat.body.id+'/attachments?filename=owned-retry.png','POST',image);if(accepted.status!==202||!/^[a-f0-9-]{36}$/.test(accepted.body?.id??''))throw Error('Synthetic upload not accepted');attachmentId=accepted.body.id;const before=job();if(before.status!=='queued'||before.attempt!==0||before.completed)throw Error('Expected durable unpublished owned job');if(!/^00-[a-f0-9]{32}-[a-f0-9]{16}-01$/.test(before.traceparent))throw Error('Accepted W3C trace context missing');traceId=before.traceparent.split('-')[1];await record('accepted',{...before,requestId:accepted.requestId,traceId});lease.key='staging/'+attachmentId;stage='read-exact-owned-staging';lease.bytes=new Uint8Array(await s3.file(lease.key).arrayBuffer());if(!Buffer.from(lease.bytes).equals(image))throw Error('Owned object differs from accepted fixture');await record('object-verified',{bytes:image.length,sha256:new Bun.CryptoHasher('sha256').update(image).digest('hex')});stage='temporary-owned-object-absence';lease.hidden=true;await s3.delete(lease.key);if(await s3.exists(lease.key))throw Error('Transient object fault not established');command(['docker','start',lease.id]);stage='observe-first-durable-retry';let retry:any;for(let i=0;i<150;i++){const current=job();if(current.attempt>=1&&current.status==='queued'&&current.error_code==='processing_failed'&&!current.completed){retry=current;break}if(current.status==='failed')throw Error('Unexpected permanent failure before object recovery');await Bun.sleep(100)}if(!retry)throw Error('Durable retry not observed');await record('durable-retry',retry);stage='restore-exact-owned-object';await s3.write(lease.key,lease.bytes,{type:'image/png'});if(!Buffer.from(await s3.file(lease.key).arrayBuffer()).equals(image))throw Error('Restored object bytes mismatch');lease.hidden=false;await record('object-restored',{bytes:image.length});stage='observe-same-job-ready';let ready:any;for(let i=0;i<300;i++){const current=job();if(current.status==='ready'&&current.completed&&current.attempt>=2){ready=current;break}if(current.status==='failed')throw Error('Retry unexpectedly permanently failed');await Bun.sleep(200)}if(!ready)throw Error('Same accepted job not ready after automatic retry');await record('same-job-ready',ready);const content=await fetch('http://127.0.0.1:28206/api/v1/attachments/'+attachmentId+'/content',{headers:{Authorization:'Bearer '+token}});if(content.status!==200||!Buffer.from(await content.arrayBuffer()).equals(image))throw Error('Recovered original bytes mismatch');}catch(error){failureStage=stage;throw error}},restore:async lease=>{stage='restore-owned-object-and-worker';const current=owned('worker',lease.id);if(current.Image!==lease.image||owned('s3',storage.Id).Image!==storage.Image)throw Error('Restore ownership image mismatch');if(lease.hidden&&lease.bytes){await s3.write(lease.key,lease.bytes,{type:'image/png'});lease.hidden=false}if(!current.State.Running)command(['docker','start',lease.id]);}})();
}catch(e){failureStage??=stage;failure=e instanceof OwnedFaultFailure?'Owned retry operation failed':e instanceof Error?e.message:'Retry failed';if(e instanceof OwnedFaultFailure&&e.cleanup!==undefined)cleanupFailure='Owned object/worker restore failed';}finally{if(token)try{if((await api('/api/v1/auth/sessions/current','DELETE')).status!==204)cleanupFailure='Synthetic session revocation failed'}catch{cleanupFailure='Synthetic session revocation failed'}}
const result={checkedAt:new Date().toISOString(),project,stage,failureStage,attachmentId,traceId,observations,failure,cleanupFailure,passed:!failure&&!cleanupFailure,out};await writeFile(resolve(out,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({out,stage,attachmentId,traceId,failure,cleanupFailure,passed:result.passed}));if(!result.passed)process.exitCode=1;