Files
UHD_Media_Tool/spikes/deno/apps/server/src/node-compat.ts
T
2026-09-27 18:24:08 +08:00

33 lines
2.1 KiB
TypeScript

// Node-only API probe under Deno (things the current server/tasks code uses or is likely to use).
import process from "node:process";
import { Worker, isMainThread, parentPort } from "node:worker_threads";
import { statfs } from "node:fs/promises";
import { spawn } from "node:child_process";
import { parseArgs } from "node:util";
import os from "node:os";
import { AsyncLocalStorage } from "node:async_hooks";
import { createHash, randomUUID } from "node:crypto";
if (!isMainThread) { parentPort!.postMessage({ echo: "from worker", pid: process.pid }); } else {
const r: Record<string, unknown> = {};
r.parseArgs = parseArgs({ args: ["--role", "api"], options: { role: { type: "string" } } }).values;
const s = await statfs("/");
r.statfs = { bsize: s.bsize, bavailGB: Math.round((s.bavail * s.bsize) / 1e9) };
r.os = { cpus: os.cpus().length, freememMB: Math.round(os.freemem() / 1e6), loadavg: os.loadavg().length };
r.memoryUsage = Object.keys(process.memoryUsage()).join(",");
const als = new AsyncLocalStorage<string>();
r.als = await als.run("req-1", async () => { await new Promise((x) => setTimeout(x, 5)); return als.getStore(); });
r.crypto = createHash("sha256").update("x").digest("hex").slice(0, 8) + " " + randomUUID().length;
r.worker = await new Promise((res) => { const w = new Worker(new URL(import.meta.url), { type: "module" } as any); w.once("message", (m) => { res(m); w.terminate(); }); });
const child = spawn("sh", ["-c", "trap 'echo got-TERM; exit 0' TERM; echo ready; sleep 5 & wait"]);
let out = ""; child.stdout.on("data", (d) => { out += d; });
await new Promise((x) => setTimeout(x, 200));
child.kill("SIGTERM");
r.childKill = await new Promise((res) => child.on("exit", (code, sig) => res({ code, sig, out: out.trim().replace(/\n/g, "|") })));
r.execPath = process.execPath;
console.log(JSON.stringify(r, null, 1));
process.on("SIGTERM", () => { console.log("process.on(SIGTERM) handler fired"); process.exit(0); });
setTimeout(() => process.kill(process.pid, "SIGTERM"), 100);
setTimeout(() => { console.log("handler did NOT fire"); process.exit(1); }, 2000);
}