Files
MikrotikManager/backend/src/services/traffic-flow-drain-protocol.test.ts
T

50 lines
4.5 KiB
TypeScript

import assert from "node:assert/strict"
import { EventEmitter } from "node:events"
import { AsyncLocalStorage, AsyncResource } from "node:async_hooks"
import { requestExistingWorkerDrain,runExistingWorkerDrain,type FlowDrainPeer } from "./traffic-flow-drain-protocol.js"
const pair=()=>{
const main=new EventEmitter(),worker=new EventEmitter(),sent:unknown[]=[]
const left:FlowDrainPeer={on:(event,fn)=>main.on(event,fn),off:(event,fn)=>main.off(event,fn),postMessage:message=>{sent.push(message);queueMicrotask(()=>worker.emit("message",message))}}
const right:FlowDrainPeer={on:(event,fn)=>worker.on(event,fn),off:(event,fn)=>worker.off(event,fn),postMessage:message=>{sent.push(message);queueMicrotask(()=>main.emit("message",message))}}
return {main,worker,left,right,sent}
}
const receipt={batchId:"11111111-1111-4111-8111-111111111111",buckets:2,facts:1,skippedInet:0}
assert.deepEqual(await requestExistingWorkerDrain(null,async()=>{},[1]),{workerPresent:false,receipt:null})
const happy=pair();let running:Promise<void>|undefined,checks=0,dispatches=0
happy.worker.on("message",message=>{if(message.type==="strict-drain")running=runExistingWorkerDrain(happy.right,message.requestId,async authorize=>{await authorize();dispatches++;await authorize();return receipt})})
assert.deepEqual(await requestExistingWorkerDrain(happy.left,async()=>{checks++},[1]),{workerPresent:true,receipt})
await running;assert.equal(dispatches,1);assert.ok(checks>=5);assert.equal(happy.main.listenerCount("message"),0)
const revoked=pair();let allowed=true,deniedRun:Promise<void>|undefined,writes=0
revoked.worker.on("message",message=>{if(message.type==="strict-drain")deniedRun=runExistingWorkerDrain(revoked.right,message.requestId,async authorize=>{allowed=false;await authorize();writes++;return receipt})})
await assert.rejects(requestExistingWorkerDrain(revoked.left,async()=>{if(!allowed)throw Error("revoked")},[1]),/revoked/)
await deniedRun;assert.equal(writes,0)
const late=pair();let wake:()=>void=()=>{},lateChecks=0,lateRun:Promise<void>|undefined
const gate=new Promise<void>(resolve=>{wake=resolve})
late.worker.on("message",message=>{if(message.type==="strict-drain")lateRun=runExistingWorkerDrain(late.right,message.requestId,async()=>{writes++;return receipt})})
let returned=false
const timed=requestExistingWorkerDrain(late.left,async()=>{lateChecks++;if(lateChecks>1)await gate},[1],20).finally(()=>{returned=true})
const rejected=assert.rejects(timed,/deadline/)
await new Promise<void>(resolve=>setTimeout(resolve,40))
assert.equal(returned,false,"drain retains outstanding authority work before returning")
wake();await rejected;await lateRun;await new Promise<void>(resolve=>setImmediate(resolve))
assert.equal(writes,0);assert.ok(!late.sent.some(message=>typeof message==="object"&&message!==null&&"type" in message&&message.type==="drain-authorized"))
const exited=pair();const waiting=requestExistingWorkerDrain(exited.left,async()=>{},[1],1000);queueMicrotask(()=>exited.main.emit("exit",1));await assert.rejects(waiting,/exited/)
assert.ok(!happy.sent.some(message=>typeof message==="object"&&message!==null&&"type" in message&&["start","stop","shutdown"].includes(String(message.type))))
// Model the real EventEmitter callback boundary of an already-existing Worker:
// replies arrive in its creation context, while each new request owns a live
// distinct caller scope. No SQL or permission outcome is replaced here.
const callers=new AsyncLocalStorage<{name:string;active:boolean}>()
const oldWorker=callers.run({name:"old-worker-owner",active:false},()=>new AsyncResource("existing-worker-reply"))
const scoped=pair(),caller={name:"current-caller",active:true};let scopedRun:Promise<void>|undefined,scopedChecks=0
scoped.right.postMessage=message=>oldWorker.runInAsyncScope(()=>queueMicrotask(()=>scoped.main.emit("message",message)))
scoped.worker.on("message",message=>{if(message.type==="strict-drain")scopedRun=runExistingWorkerDrain(scoped.right,message.requestId,async authorize=>{await authorize();return receipt})})
await callers.run(caller,async()=>{
assert.deepEqual(await requestExistingWorkerDrain(scoped.left,async()=>{assert.equal(callers.getStore(),caller);assert.equal(caller.active,true);scopedChecks++},[1]),{workerPresent:true,receipt})
await scopedRun
})
assert.ok(scopedChecks>=5);assert.equal(scoped.main.listenerCount("message"),0);oldWorker.emitDestroy()
console.log("traffic-flow-drain-protocol.test.ts: existing-peer checkpoints, revoke before dispatch, timeout/late approval suppression, worker exit, cleanup and zero start/stop/restart messages verified; no worker/network/SQL executed")