/** 不依赖 UI 的通信层冒烟测试:本机起 server + client,验证双向收发与断线自动重连 */ import * as net from "node:net"; import { createSession, type ChatMessage, type Phase, type Session } from "../src/net.js"; /* ---------- harness ---------- */ /** 事件日志:失败时 dump 全部时序,方便排障 */ const events: string[] = []; const t0 = Date.now(); const log = (s: string): void => { const line = `[${((Date.now() - t0) / 1000).toFixed(2)}s] ${s}`; events.push(line); console.log(` ${line}`); }; const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)); /** 取一个空闲端口(每个场景独立,避免固定端口复跑 EADDRINUSE) */ function freePort(): Promise { return new Promise((resolve) => { const srv = net.createServer(); srv.listen(0, "127.0.0.1", () => { const { port } = srv.address() as net.AddressInfo; srv.close(() => resolve(port)); }); }); } /** 轮询等待条件成立;超时 dump 事件日志后抛错 */ async function waitFor(desc: string, pred: () => boolean, timeoutMs = 10_000): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { if (pred()) { log(`✓ ${desc}`); return; } await sleep(50); } console.error(`✗ 超时等待:${desc}`); console.error("--- 事件日志 ---"); for (const e of events) console.error(e); throw new Error(`waitFor 超时:${desc}`); } /** 建会话并记录消息/状态,便于断言与排障 */ interface Wrapped { session: Session; msgs: ChatMessage[]; sysTexts: string[]; phases: Phase[]; } function wrap(who: string, role: "server" | "client", port: number, name: string): Wrapped { const msgs: ChatMessage[] = []; const sysTexts: string[] = []; const phases: Phase[] = []; const session = createSession(role, { host: "127.0.0.1", port, name }, { onMessage: (m) => { if (m.type === "msg") { msgs.push(m); log(`${who} ⇐ ${m.name}:${m.text}`); } else { sysTexts.push(m.text); log(`${who} · ${m.text}`); } }, onPhase: (p) => { phases.push(p); log(`${who} phase → ${p}`); }, }); return { session, msgs, sysTexts, phases }; } const hasMsg = (w: Wrapped, name: string, text: string): boolean => w.msgs.some((m) => m.name === name && m.text === text); const hasSys = (w: Wrapped, s: string): boolean => w.sysTexts.some((t) => t.includes(s)); const bothConnected = (a: Wrapped, b: Wrapped): boolean => a.session.phase === "connected" && b.session.phase === "connected"; /* ---------- 场景(谓词一律写终态,不依赖中间顺序) ---------- */ async function main(): Promise { // S0 基础回归:连接 + 双向收发 console.log("— S0 基础回归 —"); { const port = await freePort(); const a = wrap("A", "server", port, "A"); const b = wrap("B", "client", port, "B"); await waitFor("S0 双方 connected", () => bothConnected(a, b)); b.session.send("你好,A!"); a.session.send("收到,B"); await waitFor("S0 双向送达", () => hasMsg(a, "B", "你好,A!") && hasMsg(b, "A", "收到,B")); a.session.close(); b.session.close(); } // S1 客户端先行:服务端没起,一直重试不退出;服务端后启动即连上 console.log("— S1 客户端先行 —"); { const port = await freePort(); const b = wrap("B", "client", port, "B"); await sleep(1500); // 回环 ECONNREFUSED 即时,期间已完成多次失败重试 if (b.phases.includes("closed")) throw new Error("S1:客户端不应进 closed"); if (b.session.phase !== "waiting") throw new Error("S1:未连上过应停在 waiting"); const fails = b.sysTexts.filter((t) => t.startsWith("Connection failed")).length; if (fails !== 1) throw new Error(`S1:同文本错误应去重为 1 次,实际 ${fails}`); log("S1 重试中,错误提示已去重为 1 次"); const a = wrap("A", "server", port, "A"); await waitFor("S1 服务端后启动,双方 connected", () => bothConnected(a, b), 15_000); b.session.send("迟到的问候"); await waitFor("S1 送达", () => hasMsg(a, "B", "迟到的问候")); a.session.close(); b.session.close(); } // S2 服务端替换 + 客户端重连:第三个连接插进来,服务端换掉旧连接 console.log("— S2 服务端替换 + 客户端重连 —"); { const port = await freePort(); const a = wrap("A", "server", port, "A"); const b = wrap("B", "client", port, "B"); await waitFor("S2 双方 connected", () => bothConnected(a, b)); b.session.send("替换前的消息"); await waitFor("S2 A 收到首条", () => hasMsg(a, "B", "替换前的消息")); const c = net.connect({ host: "127.0.0.1", port }); c.on("error", () => {}); // 挂 no-op,防 unhandled error 崩测试 // B 被服务端替换 → 断线进 reconnecting(这就是替换语义的可观测证明) await waitFor("S2 B 被替换进 reconnecting", () => b.session.phase === "reconnecting"); if (a.session.phase !== "connected") throw new Error("S2:A 此刻应仍 connected(挂着新连接)"); c.destroy(); // 裸连接退场,给 B 让路 await waitFor("S2 B 重连成功,双方 connected", () => bothConnected(a, b), 15_000); if (!hasSys(a, "Peer reconnected")) throw new Error("S2:A 应收到 Peer reconnected"); b.session.send("重连后的消息"); a.session.send("收到,欢迎回来"); await waitFor("S2 双向送达", () => hasMsg(a, "B", "重连后的消息") && hasMsg(b, "A", "收到,欢迎回来")); a.session.close(); b.session.close(); } // S3 服务端重启 + 断线排队:服务端退出重起,排队消息重连后送达 console.log("— S3 服务端重启 + 断线排队 —"); { const port = await freePort(); const a = wrap("A", "server", port, "A"); const b = wrap("B", "client", port, "B"); await waitFor("S3 双方 connected", () => bothConnected(a, b)); a.session.close(); // 模拟服务端退出 await waitFor("S3 B 进 reconnecting", () => b.session.phase === "reconnecting"); b.session.send("offline-1"); b.session.send("offline-2"); // 此刻无 socket,进 queue await sleep(300); // 给端口释放留时间 const a2 = wrap("A2", "server", port, "A"); await waitFor("S3 B 重连上新服务端", () => bothConnected(a2, b), 15_000); await waitFor("S3 排队消息 flush 到 A2", () => hasMsg(a2, "B", "offline-1") && hasMsg(a2, "B", "offline-2")); a2.session.send("新链路问候"); await waitFor("S3 新链路送达", () => hasMsg(b, "A", "新链路问候")); a2.session.close(); b.session.close(); } console.log("✅ 全部 4 个场景通过"); } /* 全局看门狗:任何场景挂死则 dump 日志退出 */ setTimeout(() => { console.error("✗ 全局超时(60s)"); for (const e of events) console.error(e); process.exit(1); }, 60_000); main() .then(() => process.exit(0)) .catch((err: unknown) => { console.error(`❌ ${err instanceof Error ? err.message : err}`); process.exit(1); });