Files
mtusi2026lab6/student-tests/openobserve-signals.ts
T

14 lines
5.0 KiB
TypeScript

import {mkdir,readFile,writeFile} from 'node:fs/promises';import {resolve} from 'node:path';
const root=resolve(import.meta.dir,'..'),output=resolve(root,'.local/openobserve-signals-'+crypto.randomUUID());await mkdir(output,{mode:0o700});const accounts=JSON.parse(await readFile(resolve(root,'.local/openobserve-accounts.json'),'utf8'));const credential=accounts.query;const auth='Basic '+Buffer.from(credential.email+':'+credential.token).toString('base64');const base='http://127.0.0.1:28906';
async function request(path:string,body?:unknown){const r=await fetch(base+path,{method:body?'POST':'GET',headers:{Authorization:auth,'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(15_000)});const bytes=await r.arrayBuffer();if(bytes.byteLength>2_097_152)throw new Error('native response exceeds limit');if(!r.ok)throw new Error('native bounded query HTTP'+r.status);return JSON.parse(new TextDecoder().decode(bytes));}
async function search(type:string,sql:string){return request('/api/default/_search?type='+type,{query:{sql,start_time:(Date.now()-900_000)*1000,end_time:Date.now()*1000,from:0,size:100}});}
const worker=await search('traces',`SELECT trace_id FROM "messenger" WHERE operation_name='attachment.process' ORDER BY _timestamp DESC LIMIT 1`);const traceId=worker.hits?.[0]?.trace_id;if(!/^[a-f0-9]{32}$/.test(traceId??''))throw new Error('actual worker trace absent');
const trace=await search('traces',`SELECT trace_id, span_id, reference_parent_span_id, operation_name, service_name, CAST(start_time AS VARCHAR) AS start_ns, CAST(end_time AS VARCHAR) AS end_ns, duration, _timestamp FROM "messenger" WHERE trace_id='${traceId}' ORDER BY start_time LIMIT 100`);const rows=trace.hits??[];await writeFile(resolve(output,'TRACE-ROWS.json'),JSON.stringify({traceId,rows},null,2)+'\n',{flag:'wx',mode:0o600});const names=[...new Set(rows.map((r:any)=>r.operation_name))];for(const required of ['attachment.publish','attachment.process'])if(!names.includes(required))throw new Error('cross-process trace chain missing '+required);
if(!rows.some((r:any)=>r.service_name==='messenger-api'&&r.operation_name.startsWith('POST ')))throw new Error('actual API upload span absent');
const spans=new Set(rows.map((r:any)=>r.span_id));const childLinks=rows.filter((r:any)=>r.reference_parent_span_id&&spans.has(r.reference_parent_span_id));if(childLinks.length<2)throw new Error('native parent relations absent');
const times=rows.map((r:any)=>{if(!/^\d{18,20}$/.test(r.start_ns)||!/^\d{18,20}$/.test(r.end_ns))throw new Error('noncanonical native nanosecond field');const ns=BigInt(r.end_ns)-BigInt(r.start_ns),us=Number(ns)/1000;if(ns<0n||Math.abs(us-Number(r.duration))>1.01)throw new Error('native trace duration unit mismatch');if(Math.abs(Number(BigInt(r.start_ns)/1000n)-Number(r._timestamp))>1)throw new Error('native timestamp unit mismatch');return{spanId:r.span_id,parentSpanId:r.reference_parent_span_id,operation:r.operation_name,service:r.service_name,startTimeNs:r.start_ns,endTimeNs:r.end_ns,durationMicroseconds:r.duration};});
if(!times.some((r:any)=>r.durationMicroseconds>0))throw new Error('zero-duration waterfall');
const logs=await search('logs',`SELECT trace_id, span_id, event, service_name, request_id FROM "messenger" WHERE trace_id='${traceId}' LIMIT 100`);if(!logs.hits?.some((l:any)=>l.service_name==='messenger-api')||!logs.hits?.some((l:any)=>l.service_name==='messenger-worker'))throw new Error('correlated API/worker logs missing');if(!logs.hits.some((l:any)=>/^[a-f0-9-]{36}$/.test(l.request_id??'')))throw new Error('response request_id log field absent');
const queries=['sum(http_requests)','sum(jobs_processed)','histogram_quantile(0.95, sum by(le)(http_duration_bucket))','max(queue_depth)','max(database_observer_up)'];const metrics=[];for(const query of queries){const result=await request('/api/default/prometheus/api/v1/query?'+new URLSearchParams({query}));if(result.status!=='success'||!result.data?.result?.length)throw new Error('native PromQL query returned no sample: '+query);const values=result.data.result.map((r:any)=>Number(r.value?.[1]));if(values.some((v:number)=>!Number.isFinite(v)))throw new Error('native PromQL returned nonfinite sample: '+query);metrics.push({query,values});}
const result={checkedAt:new Date().toISOString(),traceId,queryPrincipalRole:'service_account',queryGateway:base,traceStream:'messenger',logStream:'messenger',traceTimeUnits:{start_time:'nanoseconds',end_time:'nanoseconds',duration:'microseconds',_timestamp:'microseconds'},parentField:'reference_parent_span_id',spanCount:rows.length,parentRelations:childLinks.length,spans:times,correlatedLogs:logs.hits.map((l:any)=>({event:l.event,service:l.service_name,traceId:l.trace_id,spanId:l.span_id,requestId:l.request_id??null})),metrics,output};await writeFile(resolve(output,'RESULT.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx',mode:0o600});console.log(JSON.stringify({receipt:resolve(output,'RESULT.json'),traceId,spanCount:rows.length,parentRelations:childLinks.length,operations:names,correlatedLogCount:logs.hits.length,metrics}));