Files
NODEDC_MISSION_CORE/packages/router-ui/src/evidence.ts
T
DCCONSTRUCTIONS a49fb00b8e feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements
Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
2026-11-11 23:53:46 +03:00

49 lines
8.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type {RouterDevice,RouterReceipt,RouterSnapshot,RouterTransport} from './contracts';
export type EvidenceResource='diagnostics_latest'|'diagnostic'|'bundle'|'events'|'recovery_history'|'recordings'|'recording'|'targets';
export interface EvidenceQuery {resource:EvidenceResource;id:string;after:string;transfer:string;offset:number}
export interface EvidenceRequest {operation_id:string;runtime_id:string;device_id:string;deadline:number;action:'inspect';expected_boot_id:string;query:EvidenceQuery}
export interface EvidenceChunk {operation_id:string;device_id:string;boot_id:string;resource:EvidenceResource;id:string;transfer:string;offset:number;total:number;at:number;data:string}
export interface EvidenceDocument<T=EvidenceData> {schema:'missioncore.router-evidence/v1';resource:EvidenceResource;omitted_fields:number;data:T}
export interface Check {id:string;check_id?:string;state:string;code?:string;title?:string;summary?:string;facts?:string[];scope?:string;impact?:string;cause?:string;checked?:number;checked_utc?:number}
export interface Report {id?:string;boot_id?:string;clock_quality?:string;state?:string;started?:number;finished?:number;started_utc?:number;finished_utc?:number;duration_ms?:number;checks?:Check[];machine_checks?:Check[];service_report?:Report;result_available?:boolean;path?:string;active?:string;selected?:string;path_changed_during_run?:boolean;lan_client_tested?:boolean;snapshot_omitted?:boolean;target_probes?:Probe[];snapshot?:{generated_utc?:number};operation_id?:string}
export interface Probe {target_id?:string;path?:string;sim?:string;state?:string;success?:boolean;reason?:string;stages?:Record<string,{state?:string;duration_ms?:number;code?:string;success?:boolean}>}
export interface VendorEvent {source?:string;sequence?:number;boot?:string;boot_id?:string;epoch?:number;observed_utc?:number;uptime?:number;clock_quality?:string;topic?:string;message?:string;summary?:string;code?:string;recorded_code?:string;category?:string;initiator_kind?:string;actor?:string;operation_id?:string;level?:string;severity?:string}
export interface VendorOperation {operation_id?:string;kind?:string;state?:string;accepted_utc?:number;accepted_boot_id?:string;accepted_uptime?:number;actor?:string;result?:Report}
export interface FlightWAN {slot?:string;up?:boolean|null;operator?:string;sim_present?:boolean|null;network_registration?:{registration_state?:string|null;failure_reason?:string|null};radio?:{rsrp_dbm?:number|null;rsrq_db?:number|null;sinr_db?:number|null;band?:string|null;cell_id?:string|null}}
export interface FlightSample {observed_utc:number;boot_id:string;uptime:number;clock_quality?:string;state:{effective_wan?:string|null;observed?:{active?:string;pending?:boolean;phase?:string;reason?:string};wan?:FlightWAN[];vpn?:{active?:boolean;verified?:boolean};reserve?:{count?:number;distinct_sim_count?:number}}}
export interface Recording {id:string;state:string;started_utc:number;updated_utc?:number;trigger_codes?:string[];samples:number|FlightSample[];truncated?:boolean;cause?:string}
export interface EvidenceData {report?:Report|null;operation_id?:string;state?:string;result?:Report;cursor?:string;events?:VendorEvent[];entries?:VendorEvent[];operations?:VendorOperation[];recordings?:Recording[];id?:string;samples?:FlightSample[];started_utc?:number;updated_utc?:number;trigger_codes?:string[];truncated?:boolean;cause?:string;targets?:{id:string;label?:string}[];captured_snapshot?:{generated_utc?:number};current_snapshot?:{generated_utc?:number};operation?:VendorOperation}
export interface ClientDetails {vpn:{selected:boolean|null;active:boolean|null;verified:boolean|null;sim:string;server:string;watch_state:string;watch_age:number|null;proof_age:number|null;last_success_age:number|null};reserve:{available:boolean|null;running:boolean|null;count:number|null;target:number|null;distinct_sims:number|null;age:number|null;ttl:number|null;phase:string;pairs:{sim:string;server:string;transport:string;age:number|null}[]};pending:boolean|null;fallback:boolean|null;fallback_reason:string;recovery_age:number|null;last_attempt_current:boolean|null}
const errors:Record<string,string>={result_expired:'Этот отчёт уже удалён роутером. Обновите список.',router_conflict:'Роутер перезапущен или журнал изменился. Обновите список.',access_rejected:'У ключа нет доступа к этому отчёту.',unsupported_response:'Формат отчёта не поддерживается.',expired:'Время ожидания истекло. Повторите чтение.',router_unavailable:'Связь с роутером потеряна.'};
export const evidenceError=(code?:string)=>errors[code??'']??'Не удалось получить отчёт. Обновите состояние и повторите чтение.';
export function decodeChunk(c:EvidenceChunk,q:EvidenceQuery,device:string,boot:string):Uint8Array {
if(c.device_id!==device||c.boot_id!==boot||c.resource!==q.resource||c.id!==q.id||c.offset!==q.offset||!Number.isInteger(c.total)||c.total<=0||c.total>2097152||!/^[a-f0-9]{64}$/.test(c.transfer)||(q.transfer&&c.transfer!==q.transfer))throw Error(evidenceError('unsupported_response'));
const bytes=Uint8Array.from(atob(c.data),c=>c.charCodeAt(0));
if(bytes.length!==Math.min(32768,c.total-c.offset)||bytes.length<=0)throw Error(evidenceError('unsupported_response'));
return bytes;
}
export async function readEvidence(transport:RouterTransport,value:RouterSnapshot,device:RouterDevice,resource:EvidenceResource,id:string,after:string,signal:AbortSignal,progress:(fraction:number)=>void):Promise<EvidenceDocument> {
if(!transport.inspect||!value.runtime_id||!device.client_api||value.read_version!==1)throw Error('Обновите версию борта для чтения отчётов.');
const boot=device.client_api.boot_id,q:EvidenceQuery={resource,id,after,transfer:'',offset:0};let output:Uint8Array|null=null,stamp=0;
do {
signal.throwIfAborted();const operation_id='op_'+crypto.randomUUID().replaceAll('-','');
let receipt:RouterReceipt=await transport.inspect({operation_id,runtime_id:value.runtime_id,device_id:device.id,expected_boot_id:boot,deadline:Math.floor(Date.now()/1000)+85,action:'inspect',query:{...q}});
const end=Date.now()+90000;
while(receipt.state==='queued'||receipt.state==='applying'){
signal.throwIfAborted();if(Date.now()>end)throw Error(evidenceError('expired'));
await new Promise(resolve=>setTimeout(resolve,1000));signal.throwIfAborted();receipt=await transport.operation(operation_id);
}
signal.throwIfAborted();if(receipt.state!=='complete'||!receipt.evidence)throw Error(evidenceError(receipt.error));
const c=receipt.evidence;if(c.operation_id!==operation_id)throw Error(evidenceError('unsupported_response'));
const bytes=decodeChunk(c,q,device.id,boot);
if(output&&(output.length!==c.total||stamp!==c.at))throw Error(evidenceError('unsupported_response'));
if(!output){output=new Uint8Array(c.total);stamp=c.at}output.set(bytes,q.offset);q.offset+=bytes.length;q.transfer=c.transfer;progress(q.offset/c.total);
}while(q.offset<output.length);
if(globalThis.crypto?.subtle){const digest=await crypto.subtle.digest('SHA-256',output as Uint8Array<ArrayBuffer>);const hash=Array.from(new Uint8Array(digest),b=>b.toString(16).padStart(2,'0')).join('');if(hash!==q.transfer)throw Error(evidenceError('unsupported_response'));}
const doc=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(output)) as EvidenceDocument;
if(doc.schema!=='missioncore.router-evidence/v1'||doc.resource!==resource||!doc.data||typeof doc.data!=='object')throw Error(evidenceError('unsupported_response'));return doc;
}
export function downloadEvidence(value:unknown,name:string){const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
export function vendorTime(at:number|undefined){return at!=null&&at>0?new Date(at*1000).toLocaleString('ru-RU'):'Время не указано';}
export const checkState=(state:string)=>({ok:'В порядке',worked:'В порядке',error:'Ошибка',fail:'Ошибка',warn:'Требует внимания',unknown:'Не подтверждено',na:'Не проверялось',skip:'Не проверялось'} as Record<string,string>)[state]??'Нет результата';