// THE SEEDER'S WEBRTC SCENARIO, RUN AS ITS OWN PROCESS (controller/seeder.test.ts). // // A WebSocket tracker on 127.0.0.1, the seeder, and a leecher that reaches it // over WebRTC (node-datachannel), a few hundred KB of synthetic bytes — the // test that used to run inside the test file. It runs here because twice, on a // loaded machine, the file's process did not finish: once it never exited after // the test passed, once its event loop stopped mid-test (no timer fired for 90 s, // the test's own timeout among them). What a native WebRTC stack does to its // process cannot be bounded from inside it; from the parent it can — the // parent kills this process and fails, saying what it last reported. // // Protocol, one line each on stdout: // RESULT {"ok":true,"wires":[...]} | RESULT {"ok":false,"error":"…"} // OPEN {"resources":[...],"wsPool":[...]} after the teardown // STILL-ALIVE {...} 5 s later, only if it has not exited // It must then exit by itself: everything it opened is closed. import { mkdir, readFile, rm } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import WebTorrent from "webtorrent"; import type { Paths } from "../../lib/paths"; import { runSeeder } from "../../controller/seeder"; import { destroyClient, newClient, seederFixture, seederSettings, until } from "./fixture"; const say = (tag: string, v: unknown) => process.stdout.write(`${tag} ${JSON.stringify(v)}\n`); async function wsPool(): Promise { const dir = path.dirname(fileURLToPath(import.meta.resolve("bittorrent-tracker"))); const mod = (await import(pathToFileURL(path.join(dir, "lib/client/websocket-tracker.js")).href)) as { default: { _socketPool: Record }; }; return Object.keys(mod.default._socketPool); } async function main(): Promise { if (!WebTorrent.WEBRTC_SUPPORT) { say("RESULT", { ok: true, skipped: "no WebRTC in this node" }); return; } const f = await seederFixture((port) => `ws://127.0.0.1:${port}`); const ac = new AbortController(); const log: string[] = []; const seederClient = newClient(); const peer = newClient(); const running = runSeeder({ paths: {} as Paths, settings: seederSettings(), onLog: (l) => log.push(l), signal: ac.signal, deps: { targets: async () => [f.target], pollMs: 1000, policy: { standbyAfterSeconds: 3600, resumeAfterSeconds: 3600 }, client: seederClient, }, }); try { // The leecher announces AFTER the seeder's announce is in. Two peers whose // WebSocket offers cross in flight each answer the other's and each keep // the connection the other dropped — an artefact of starting both in the // same instant, which a browser arriving at a running seeder does not do. await until(() => (f.tracker.swarm(f.made.infoHash)?.complete ?? 0) >= 1, 60_000, "the seeder's announce"); const out = path.join(f.dir, "leech"); await mkdir(out); const tor = peer.add(f.made.torrent, { path: out }); await new Promise((resolve, reject) => { tor.once("done", () => resolve()); tor.once("error", reject); setTimeout(() => reject(new Error(`the leecher did not finish; seeder log: ${log.join(" | ")}`)), 90_000).unref(); }); const same = Buffer.compare(await readFile(path.join(out, f.target.id + ".mp4")), f.bytes) === 0; say("RESULT", same ? { ok: true, wires: tor.wires.map((w) => w.type) } : { ok: false, error: "the leeched bytes differ" }); } catch (err) { say("RESULT", { ok: false, error: (err as Error).message }); } finally { ac.abort(); await running.catch(() => {}); await destroyClient(peer); await destroyClient(seederClient); await f.tracker.close(); await rm(f.dir, { recursive: true, force: true }); } } await main(); say("OPEN", { resources: process.getActiveResourcesInfo(), wsPool: await wsPool() }); setTimeout(() => { const handles = (process as unknown as { _getActiveHandles(): unknown[] })._getActiveHandles().map((h) => { const o = h as { constructor?: { name?: string }; remoteAddress?: string; remotePort?: number; localPort?: number }; return [o.constructor?.name, o.remoteAddress, o.remotePort, o.localPort].filter((x) => x !== undefined).join(" "); }); say("STILL-ALIVE", { resources: process.getActiveResourcesInfo(), handles }); }, 5000).unref();