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

90 lines
7.3 KiB
TypeScript

import type { CollectorStartPayload } from "./traffic-flow-collector-ipc.js"
import { randomUUID } from "node:crypto"
import { AsyncLocalStorage } from "node:async_hooks"
export interface CollectorDrainReceipt {batchId:string;buckets:number;facts:number;skippedInet:number}
export type FlowDrainToWorker = {type:"authorized-start";requestId:string;payload:CollectorStartPayload}|{type:"authorized-shutdown";requestId:string}|{type:"strict-drain";requestId:string;serverIds:readonly number[]}|{type:"drain-authorized";requestId:string;checkpointId:string;approved:boolean}|{type:"drain-cancel";requestId:string}
export type FlowDrainToMain = {type:"drain-authorize";requestId:string;checkpointId:string}|{type:"drain-result";requestId:string;ok:boolean;receipt:CollectorDrainReceipt|null}
export interface FlowDrainPeer {
postMessage:(message:unknown)=>void
on:(event:"message"|"exit"|"error",listener:(value:unknown)=>void)=>unknown
off:(event:"message"|"exit"|"error",listener:(value:unknown)=>void)=>unknown
}
const record=(value:unknown):value is Record<string,unknown>=>Boolean(value)&&typeof value==="object"
const uuid=(value:unknown):value is string=>typeof value==="string"&&/^[a-f0-9-]{36}$/i.test(value)
const validReceipt=(value:unknown):value is CollectorDrainReceipt|null=>value===null||record(value)&&uuid(value.batchId)&&[value.buckets,value.facts,value.skippedInet].every(count=>Number.isSafeInteger(count)&&Number(count)>=0)
/** Addresses only the supplied peer: strict-drain preserves its listener, while
* explicit authorized-start/shutdown modes fence initialization or retirement.
* This transport never constructs workers or retries/restarts an operation. */
export async function requestExistingWorkerDrain(peer:FlowDrainPeer|null,authorize:()=>Promise<unknown>,serverIds:readonly number[],timeoutMs=30000,operation:"strict-drain"|"authorized-shutdown"|"authorized-start"="strict-drain",payload?:CollectorStartPayload):Promise<{workerPresent:boolean;receipt:CollectorDrainReceipt|null}> {
if(!Array.isArray(serverIds)||serverIds.length>1000||new Set(serverIds).size!==serverIds.length||serverIds.some(id=>!Number.isSafeInteger(id)||id<=0))throw Error("Invalid existing-worker drain scope")
const scope=[...serverIds]
await authorize()
if(!peer)return {workerPresent:false,receipt:null}
if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>30000)throw Error("Invalid worker drain deadline")
const requestId=randomUUID();let active=true,poll:Promise<void>|undefined
const checkpoints=new Set<Promise<void>>()
let timer:ReturnType<typeof setTimeout>|undefined,interval:ReturnType<typeof setInterval>|undefined
let onMessage:(value:unknown)=>void=()=>{},onExit:(value:unknown)=>void=()=>{}
try {
return await new Promise((resolve,reject)=>{
const fail=(error:unknown)=>{if(!active)return;active=false;try{peer.postMessage({type:"drain-cancel",requestId})}catch{};reject(error)}
const check=async()=>{await authorize();if(!active)throw Error("Worker drain request is closed")}
const track=(task:Promise<void>)=>{checkpoints.add(task);void task.finally(()=>checkpoints.delete(task))}
// Existing Worker events carry the Worker's creation context. Execute
// this request's checks in its genuine caller context; the original live
// scope/authority and this request's closed/deadline guards still apply.
onMessage=AsyncLocalStorage.bind((value:unknown)=>{
if(!active||!record(value)||value.requestId!==requestId)return
if(value.type==="drain-authorize"&&uuid(value.checkpointId)){
track(check().then(()=>{if(active)peer.postMessage({type:"drain-authorized",requestId,checkpointId:value.checkpointId,approved:true})}).catch(fail))
}else if(value.type==="drain-result"){
if(value.ok!==true||!validReceipt(value.receipt)){fail(Error("Worker drain outcome is unconfirmed"));return}
const receipt=value.receipt
// A shutdown result already follows its final checkpoint. Resolve
// before exit; the separate shutdown waiter still requires ack + exit.
if(operation!=="strict-drain"){active=false;resolve({workerPresent:true,receipt});return}
track(check().then(()=>{if(active){active=false;resolve({workerPresent:true,receipt})}}).catch(fail))
}
})
onExit=()=>fail(Error("Existing worker exited before drain acknowledgement"))
peer.on("message",onMessage);peer.on("exit",onExit);peer.on("error",onExit)
timer=setTimeout(()=>fail(Error("Worker drain deadline exceeded; no collector restart")),timeoutMs)
interval=setInterval(()=>{if(!active||poll)return;poll=check().catch(fail).finally(()=>{poll=undefined})},100)
try{peer.postMessage(operation==="authorized-start"?{type:operation,requestId,payload}:operation==="authorized-shutdown"?{type:operation,requestId}:{type:operation,requestId,serverIds:scope})}catch(error){fail(error)}
})
}finally{
active=false;if(timer)clearTimeout(timer);if(interval)clearInterval(interval)
peer.off("message",onMessage);peer.off("exit",onExit);peer.off("error",onExit)
await poll
await Promise.all(checkpoints)
}
}
async function requestDrainCheckpoint(peer:FlowDrainPeer,requestId:string,signal:AbortSignal):Promise<void> {
signal.throwIfAborted();const checkpointId=randomUUID()
await new Promise<void>((resolve,reject)=>{
const cleanup=()=>{clearTimeout(timer);peer.off("message",message);signal.removeEventListener("abort",abort)}
const abort=()=>{cleanup();reject(Error("Worker drain authority closed"))}
const message=(value:unknown)=>{if(record(value)&&value.type==="drain-authorized"&&value.requestId===requestId&&value.checkpointId===checkpointId){cleanup();if(value.approved===true)resolve();else reject(Error("Worker drain authority refused"))}}
const timer=setTimeout(()=>{cleanup();reject(Error("Worker drain authority checkpoint timed out"))},5000)
peer.on("message",message);signal.addEventListener("abort",abort,{once:true})
try{peer.postMessage({type:"drain-authorize",requestId,checkpointId})}catch(error){cleanup();reject(error)}
})
signal.throwIfAborted()
}
/** Worker execution uses the same checkpoint closure for a strict owned batch
* or explicit startup/shutdown. Revocation never triggers an anonymous flush. */
export async function runExistingWorkerDrain(peer:FlowDrainPeer,requestId:string,run:(authorize:()=>Promise<void>,signal:AbortSignal)=>Promise<CollectorDrainReceipt|null>,completed?:()=>void,failed?:()=>void):Promise<void> {
if(!uuid(requestId))throw Error("Invalid worker drain request")
const cancellation=new AbortController();let active=true
const onMessage=(value:unknown)=>{if(record(value)&&value.type==="drain-cancel"&&value.requestId===requestId)cancellation.abort()}
peer.on("message",onMessage)
const authorize=async()=>{if(!active)throw Error("Worker drain execution is closed");await requestDrainCheckpoint(peer,requestId,cancellation.signal);if(!active)throw Error("Worker drain execution is closed")}
try{await authorize();const receipt=await run(authorize,cancellation.signal);await authorize();peer.postMessage({type:"drain-result",requestId,ok:true,receipt});completed?.()}
catch{failed?.();peer.postMessage({type:"drain-result",requestId,ok:false,receipt:null})}
finally{active=false;cancellation.abort();peer.off("message",onMessage)}
}