Files
mtusi2026lab6/student-tests/openobserve-persisted.ts

8 lines
3.8 KiB
TypeScript

import{readFile,mkdir,writeFile}from'node:fs/promises';import{resolve}from'node:path';
const root=resolve(import.meta.dir,'..'),fixture=JSON.parse(await readFile(resolve(root,'evidence/openobserve/native-signals-sa.json'),'utf8')),after=process.argv[2]==='--after';const output=after?resolve(process.argv[3]??''):resolve(root,'.local/openobserve-persisted-'+crypto.randomUUID());if(!output.startsWith(root+'/.local/openobserve-persisted-'))throw new Error('owned persistence receipt path required');if(!after)await mkdir(output,{mode:0o700});
const a=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8')).query,auth='Basic '+Buffer.from(a.email+':'+a.token).toString('base64');const begin=fixture.spans.reduce((n:bigint,s:any)=>BigInt(s.startTimeNs)<n?BigInt(s.startTimeNs):n,BigInt(fixture.spans[0].startTimeNs)),end=fixture.spans.reduce((n:bigint,s:any)=>BigInt(s.endTimeNs)>n?BigInt(s.endTimeNs):n,0n),startMicros=Number(begin/1000n)-1_000_000,endMicros=Number(end/1000n)+1_000_000;if(!Number.isSafeInteger(startMicros)||!Number.isSafeInteger(endMicros)||startMicros<=0||endMicros<=startMicros||endMicros-startMicros>3_600_000_000)throw new Error('exact persisted fixture window invalid');
async function request(path:string,body?:unknown){const response=await fetch('http://127.0.0.1:28906'+path,{method:body?'POST':'GET',headers:{Authorization:auth,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(12_000)});const raw=new Uint8Array(await response.arrayBuffer());if(raw.length>1_048_576)throw new Error('persistence response cap');if(response.status!==200)throw new Error('native persisted read HTTP'+response.status);return JSON.parse(new TextDecoder().decode(raw));}
const trace=await request('/api/default/_search?type=traces',{query:{sql:`SELECT trace_id,span_id,reference_parent_span_id,operation_name FROM "messenger" WHERE trace_id='${fixture.traceId}' ORDER BY span_id LIMIT 100`,start_time:startMicros,end_time:endMicros,size:100}});if(trace.hits?.length!==fixture.spanCount||new Set(trace.hits.map((s:any)=>s.span_id)).size!==fixture.spanCount)throw new Error('persisted exact trace span set absent');const logs=await request('/api/default/_search?type=logs',{query:{sql:`SELECT trace_id,span_id,event,service_name,request_id FROM "messenger" WHERE trace_id='${fixture.traceId}' ORDER BY span_id,event LIMIT 100`,start_time:startMicros,end_time:endMicros,size:100}});if(logs.hits?.length!==fixture.correlatedLogs.length)throw new Error('persisted exact correlated logs absent');
const queryTimeSeconds=String(end/1_000_000_000n+5n),metric=await request('/api/default/prometheus/api/v1/query?'+new URLSearchParams({query:'sum(http_requests)',time:queryTimeSeconds}));if(metric.status!=='success'||!metric.data?.result?.length)throw new Error('persisted point-in-time metric absent');const stable={traceId:fixture.traceId,startMicros,endMicros,queryTimeSeconds,spans:trace.hits,logs:logs.hits,metrics:metric.data};const hash=new Bun.CryptoHasher('sha256').update(JSON.stringify(stable)).digest('hex');let preserved:null|boolean=null;if(after){const before=JSON.parse(await readFile(resolve(output,'BEFORE.json'),'utf8'));preserved=before.hash===hash;if(!preserved)throw new Error('persisted trace/log/metric fingerprint changed');}
const result={checkedAt:new Date().toISOString(),phase:after?'after':'before',hash,preserved,spanCount:trace.hits.length,logCount:logs.hits.length,metricValue:metric.data.result[0].value,stable,output};await writeFile(resolve(output,after?'AFTER.json':'BEFORE.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,after?'AFTER.json':'BEFORE.json'),phase:result.phase,hash,preserved,spanCount:result.spanCount,logCount:result.logCount,metricValue:result.metricValue}));