Files
MikrotikManager/scripts/performance/optimizer-probes-profile.mjs
T

29 lines
2.8 KiB
JavaScript

// Pure calculation in a child process: no API, database, browser or network operations.
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
const variant=process.argv[2] ?? 'equal';
const probeCount=Number(process.argv[3] ?? 20);
if(!Number.isInteger(probeCount)||probeCount<20||probeCount>1000)throw new Error('Probe count must be an integer from 20 to 1000');
if(!['equal','varied','freshness'].includes(variant)) throw new Error('Use equal, varied or freshness');
const code = `
const fs=require('node:fs'),ts=require('typescript');
const source=ts.transpileModule(fs.readFileSync('lib/route-optimizer-data.ts','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
const mod={exports:{}};new Function('exports','require','module',source)(mod.exports,require,mod);
const {buildLiveOptimizerData,DEFAULT_ROUTE_AI_OPTIMIZER_SETTINGS}=mod.exports;
const common={host:'192.0.2.1',enabled:true,status:'online',latency:10,country:'RU',site:'TEST',model:'CHR'};
const rows=[{...common,id:1,name:'Home',type:'home-router',wanUplinks:Array.from({length:7},(_,i)=>({id:'wan'+i,name:'WAN'+i,isp:'ISP',iface:'ether'+i,ip:'198.51.100.1',maxDl:100,maxUl:100}))},{...common,id:2,name:'Jump',type:'jump-host'}];
const probes=Array.from({length:${probeCount}},(_,i)=>({id:'p'+i,srcServerId:'1',dstServerId:'2',srcInterface:'',dstInterface:'',enabled:true,lastPingRttMs:10,lastPingLossPct:0,lastTxAvgMbps:100,lastRxAvgMbps:100,lastPingAt:null}));
if(${JSON.stringify(variant)}==='varied') probes.forEach((p,i)=>{if(i<13)p.lastRxAvgMbps=null;if(i<6)p.lastTxAvgMbps=null});
if(${JSON.stringify(variant)}==='freshness') probes.forEach((p,i)=>{p.lastPingAt=new Date(Date.now()-(${probeCount}-i)*3600000).toISOString()});
const start=performance.now();const result=buildLiveOptimizerData(rows,[],DEFAULT_ROUTE_AI_OPTIMIZER_SETTINGS,probes);
console.log(JSON.stringify({elapsedMs:performance.now()-start,legs:result.homes[0].wanJhLegs.length,probeIds:result.homes[0].wanJhLegs.map(leg=>leg.observed.probeId)}));
`;
const start=performance.now();
const result=spawnSync(process.execPath,['-e',code],{cwd:process.cwd(),timeout:10000,encoding:'utf8',windowsHide:true});
const profile={variant,wanCount:7,probeCount,timeoutMs:10000,elapsedMs:Math.round(performance.now()-start),status:result.status,timedOut:result.error?.code==='ETIMEDOUT',result:result.stdout.trim(),error:result.stderr.trim()};
console.log(JSON.stringify(profile,null,2));
if(result.error && !profile.timedOut) throw result.error;
if(result.status !== 0 && !profile.timedOut) process.exitCode=1;
if(result.status===0){const measured=JSON.parse(result.stdout);assert.deepEqual(measured.probeIds,Array.from({length:7},(_,i)=>'p'+(variant==='equal'?i:variant==='freshness'?i+probeCount-7:i+13)))}