termchat: 断线自动重连 — 服务端常驻监听 + 客户端退避重连
- 服务端不再在接受首个连接后关闭 listener,新连接到来时替换旧连接 (替换语义同时是半开连接的恢复路径) - 客户端断线后指数退避自动重连(500ms 起步、封顶 10s),连上即重置; 支持先于服务端启动;连接阶段 5s 超时防不可达地址卡 SYN 重传 - socket 代数计数:被替换/拆除的旧 socket 的迟到事件全部判废 - 修复潜伏 bug:readline 将 socket error 转发重抛,无 listener 直接 崩进程 —— 原先"连不上报错退出"实为崩溃 - ECONNRESET 过滤(正常断开不再显示吓人报错)、同文本错误去重 (无限重连不刷屏)、TCP keepalive 30s - Phase 新增 reconnecting;UI 适配重连状态显示 - smoke 测试重写为事件驱动 4 场景(基础收发/客户端先行/服务端替换/ 服务端重启+断线排队 flush) Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+171
-29
@@ -1,35 +1,177 @@
|
||||
/** 不依赖 UI 的通信层冒烟测试:本机起 server + client,验证双向收发 */
|
||||
import { createSession, type ChatMessage } from "../src/net.js";
|
||||
/** 不依赖 UI 的通信层冒烟测试:本机起 server + client,验证双向收发与断线自动重连 */
|
||||
import * as net from "node:net";
|
||||
import { createSession, type ChatMessage, type Phase, type Session } from "../src/net.js";
|
||||
|
||||
const port = 19321;
|
||||
const aGot: ChatMessage[] = [];
|
||||
const bGot: ChatMessage[] = [];
|
||||
/* ---------- harness ---------- */
|
||||
|
||||
const a = createSession("server", { port, name: "A" }, {
|
||||
onMessage: (m) => aGot.push(m),
|
||||
onPhase: () => {},
|
||||
});
|
||||
/** 事件日志:失败时 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 b = createSession("client", { host: "127.0.0.1", port, name: "B" }, {
|
||||
onMessage: (m) => bGot.push(m),
|
||||
onPhase: () => {},
|
||||
});
|
||||
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/** 取一个空闲端口(每个场景独立,避免固定端口复跑 EADDRINUSE) */
|
||||
function freePort(): Promise<number> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
// 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(() => {
|
||||
b.send("你好,A!");
|
||||
a.send("收到,B");
|
||||
}, 300);
|
||||
console.error("✗ 全局超时(60s)");
|
||||
for (const e of events) console.error(e);
|
||||
process.exit(1);
|
||||
}, 60_000);
|
||||
|
||||
setTimeout(() => {
|
||||
const texts = (arr: ChatMessage[]) =>
|
||||
arr.filter((m) => m.type === "msg").map((m) => `${m.name}:${m.text}`);
|
||||
const aMsgs = texts(aGot);
|
||||
const bMsgs = texts(bGot);
|
||||
console.log("A 收到:", aMsgs);
|
||||
console.log("B 收到:", bMsgs);
|
||||
const ok = aMsgs.includes("B:你好,A!") && bMsgs.includes("A:收到,B");
|
||||
console.log(ok ? "✅ 双向通信正常" : "❌ 测试失败");
|
||||
a.close();
|
||||
b.close();
|
||||
process.exit(ok ? 0 : 1);
|
||||
}, 1200);
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((err: unknown) => {
|
||||
console.error(`❌ ${err instanceof Error ? err.message : err}`);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user