119 lines
8.7 KiB
TypeScript
119 lines
8.7 KiB
TypeScript
/** Production constructor/bind callback component tests. Real local Worker and
|
|
* UDP handle; engine/SQL dependencies are inert. No PG or remote device. */
|
|
import assert from "node:assert/strict"
|
|
import { spawn } from "node:child_process"
|
|
import { createSocket, type Socket } from "node:dgram"
|
|
import { readFileSync } from "node:fs"
|
|
import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"
|
|
import { basename, dirname, isAbsolute, join, relative } from "node:path"
|
|
import { fileURLToPath, pathToFileURL } from "node:url"
|
|
import { test } from "node:test"
|
|
import ts from "typescript"
|
|
|
|
test("actual production Worker constructor inherits parent CLI heap flags and TSX bootstrap imports", async () => {
|
|
const text = readFileSync(new URL("./traffic-flow-ingest.ts", import.meta.url), "utf8")
|
|
const source = ts.createSourceFile("traffic-flow-ingest.ts", text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS)
|
|
const constructors: ts.NewExpression[] = []
|
|
const visit = (node: ts.Node) => { if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "Worker") constructors.push(node); ts.forEachChild(node, visit) }
|
|
visit(source); assert.equal(constructors.length, 1)
|
|
const constructor = constructors[0].getText(source)
|
|
const workspace = await realpath(fileURLToPath(new URL("../../../", import.meta.url)))
|
|
const parentDirectory = join(workspace, "tmp")
|
|
await mkdir(parentDirectory, { recursive: true })
|
|
const parent = await realpath(parentDirectory), parentRelative = relative(workspace, parent)
|
|
assert(parentRelative && !parentRelative.startsWith("..") && !isAbsolute(parentRelative))
|
|
const directory = await mkdtemp(join(parent, "mm-flow-worker-platform-"))
|
|
try {
|
|
const typed = join(directory, "typed.mts"), worker = join(directory, "worker.mjs"), parent = join(directory, "parent.mjs")
|
|
await writeFile(typed, "export const typedValue: number = 7;\n")
|
|
await writeFile(worker, `import {parentPort} from 'node:worker_threads';
|
|
import {getHeapStatistics} from 'node:v8'; import {tsImport} from 'tsx/esm/api';
|
|
const typed=await tsImport(${JSON.stringify(pathToFileURL(typed).href)},import.meta.url);
|
|
parentPort.postMessage({typed:typed.typedValue,heap:getHeapStatistics().heap_size_limit,argv:process.execArgv});parentPort.close();`)
|
|
await writeFile(parent, `import assert from 'node:assert/strict';import {Worker} from 'node:worker_threads';import {getHeapStatistics} from 'node:v8';
|
|
const trafficFlowWorkerFileUrl=()=>new URL(${JSON.stringify(pathToFileURL(worker).href)});
|
|
const worker=${constructor};
|
|
const timer=setTimeout(()=>{worker.terminate();process.exitCode=1},10000);
|
|
worker.once('error',error=>{clearTimeout(timer);console.error(error);process.exitCode=1});
|
|
worker.once('message',value=>{assert.equal(value.typed,7);assert.equal(value.heap,getHeapStatistics().heap_size_limit);
|
|
assert(value.argv.includes('--import'));console.log(JSON.stringify({node:process.version,...value}));});
|
|
worker.once('exit',code=>{clearTimeout(timer);if(code!==0)process.exitCode=1});`)
|
|
const result = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
|
|
const child = spawn(process.execPath, ["--max-old-space-size=192", "--max-semi-space-size=16", "--import", "tsx", parent], { cwd: fileURLToPath(new URL("../../../", import.meta.url)), stdio: ["ignore", "pipe", "pipe"], windowsHide: true })
|
|
let stdout = "", stderr = ""
|
|
let timedOut = false
|
|
const timer = setTimeout(() => { timedOut = true; child.kill() }, 15000)
|
|
child.stdout.on("data", value => { stdout += value }); child.stderr.on("data", value => { stderr += value })
|
|
child.once("error", error => { clearTimeout(timer); reject(error) })
|
|
child.once("exit", code => { clearTimeout(timer); if (timedOut) reject(Error("Owned Worker probe timeout")); else resolve({ code, stdout, stderr }) })
|
|
})
|
|
assert.equal(result.code, 0, result.stderr)
|
|
const report = JSON.parse(result.stdout.trim()); assert.equal(report.typed, 7)
|
|
assert(report.argv.includes("--max-old-space-size=192")); assert(report.argv.includes("--max-semi-space-size=16"))
|
|
console.log("Owned platform inheritance:", JSON.stringify({ node: report.node, heapLimitBytes: report.heap, actualWorker: true, tsxTypedImport: true, targetNode22Accepted: false, wholeInstallationRamAccepted: false }))
|
|
} finally {
|
|
const target = await realpath(directory)
|
|
assert.equal(dirname(target), parent)
|
|
assert(basename(target).startsWith("mm-flow-worker-platform-"))
|
|
await rm(target, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
function bindingFixture(real: boolean, bufferFails = false) {
|
|
const text = readFileSync(new URL("./traffic-flow-collector-worker.ts", import.meta.url), "utf8")
|
|
const start = text.slice(text.indexOf("async function startListener("), text.indexOf("\nfunction startFlowFlushTimer("))
|
|
const script = ts.transpileModule(start, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
|
let current: Socket | undefined, callback: (() => void) | undefined, receiveCalls = 0, heartbeats = 0, requested = 0, actual: number | undefined
|
|
const fake = { on() { return this }, bind(_port: number, _host: string, done: () => void) { callback = done }, setRecvBufferSize(bytes: number) { receiveCalls++; requested = bytes; if (bufferFails) throw Error("platform clamp/refusal") } }
|
|
const create = () => {
|
|
if (!real) return fake
|
|
const socket = createSocket("udp4"), set = socket.setRecvBufferSize.bind(socket)
|
|
current = socket
|
|
socket.setRecvBufferSize = bytes => {
|
|
socket.address(); receiveCalls++; requested = bytes
|
|
try { if (bufferFails) throw Error("platform fallback"); set(bytes) }
|
|
finally { actual = socket.getRecvBufferSize() }
|
|
}
|
|
return socket
|
|
}
|
|
const adapter = new Function("deps", `
|
|
let socket=null,bound=false,address=null,shuttingDown=false,startingAuthorized=false;
|
|
const createSocket=deps.create;const randomUUID=()=>"owned-platform-socket";const clearFlowTemplateCache=()=>{};const setEngineError=()=>{};const send=()=>{};
|
|
const configureEngine=()=>{};const applyExporterMap=()=>{};const stopListener=()=>{};
|
|
const setFlowEngineLifecycleAuthorization=()=>{};const quiesceListener=()=>{};const flushPending=async()=>{};
|
|
const startFlowFlushTimer=()=>{};const heartbeat=deps.heartbeat;const ingestDatagram=()=>{};
|
|
${script}
|
|
return {start:startListener,retire:()=>{socket=null},shutdown:()=>{shuttingDown=true},bound:()=>bound};
|
|
`)({ create, heartbeat: () => { heartbeats++ } }) as { start: (payload: unknown) => Promise<void>; retire: () => void; shutdown: () => void; bound: () => boolean }
|
|
return { ...adapter, finishBind: () => { assert(callback); callback() }, socket: () => current, counts: () => ({ receiveCalls, heartbeats, requested, actual }) }
|
|
}
|
|
const payload = { listenHost: "127.0.0.1", listenPort: 0, topN: 20, retentionHours: 24, exporterMap: {} }
|
|
|
|
test("real localhost UDP handle requests receive buffer after bind and reads actual OS value", async () => {
|
|
for (const bufferFails of [false, true]) {
|
|
const f = bindingFixture(true, bufferFails)
|
|
await f.start(payload)
|
|
const socket = f.socket(); assert(socket)
|
|
try {
|
|
if (!f.bound()) await new Promise<void>((resolve, reject) => {
|
|
const timer = setTimeout(() => reject(Error("Owned localhost bind timeout")), 3000)
|
|
socket.once("listening", () => { clearTimeout(timer); resolve() }); socket.once("error", error => { clearTimeout(timer); reject(error) })
|
|
})
|
|
assert.equal(f.bound(), true); assert.equal(f.counts().receiveCalls, 1); assert.equal(f.counts().requested, 8 * 1024 * 1024)
|
|
assert.equal(typeof f.counts().actual, "number"); assert(f.counts().actual! > 0)
|
|
console.log("Owned UDP receive buffer:", JSON.stringify({ requestedBytes: f.counts().requested, actualBytes: f.counts().actual, injectedPlatformRefusal: bufferFails, platform: process.platform, targetLinuxAccepted: false }))
|
|
} finally { await new Promise<void>(resolve => socket.close(resolve)) }
|
|
}
|
|
})
|
|
|
|
test("retired/shutdown bind callbacks never configure a stale socket, platform refusal retains bound listener", async () => {
|
|
for (const mode of ["retired", "shutdown"] as const) {
|
|
const f = bindingFixture(false); await f.start(payload)
|
|
assert.equal(f.counts().receiveCalls, 0)
|
|
if (mode === "retired") f.retire(); else f.shutdown()
|
|
f.finishBind(); assert.equal(f.counts().receiveCalls, 0); assert.equal(f.bound(), false); assert.equal(f.counts().heartbeats, 0)
|
|
}
|
|
const fallback = bindingFixture(false, true); await fallback.start(payload); fallback.finishBind()
|
|
assert.equal(fallback.bound(), true); assert.equal(fallback.counts().receiveCalls, 1); assert.equal(fallback.counts().heartbeats, 1)
|
|
})
|