Files
QLinker/tools/probe/ws-conn-limit-probe.mjs
xiaowang d42938f52d 采样第 26 章:可靠性四项定案,排除 WS 并发上限,纠正 history count 语义
- 新增 GC-018~GC-022:WS 按连接扇出且无并发上限、断线零补推、事件乱序、
  history 窗口边界稳定少返回一条、real_seq 仅会话内唯一(去重键须含会话类型+会话ID)
- REL-dedup/order/replay/id-consistency 由未采集转为 verified 并挂回归探针;
  REL-replay 的 parseStatus 枚举违规一并修正
- capability-check 支持 reliability 的 kind=verdict/phase 判定行与 expect.fields
  数值/空数组断言,已用构造坏样本自检出 4 项漂移并 FAIL
- 新增 7 个探针(reliability/timeline/ws-conn-limit/ws-reconnect/seq-namespace/
  history-count-scan/history-edge-offbyone),只读探针无写副作用
- 作废旧结论:群 50 条硬上限、WS 并发上限归因、min(count,可读量) 完整性判据
2026-10-30 11:01:59 +08:00

94 lines
5.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 探测 NapCat 正向 WebSocket 的并发连接上限与「第 N 条连接被拒」的确切形态。
//
// 起因:reliability 探针时间线(local/reliability-2026-10-29T10-03-22-262Z.jsonl)显示
// 前两条接收连接 R/R2 正常收到 lifecycle,第三条 R3 首次握手直接 error + close code=1006,
// 且当时活跃连接数正好是 S+R+R2=3。若确有连接数上限,则对 QLinker 的影响是:
// 1) 重连时旧连接未被服务端释放 -> 新连接被拒 -> 表现为主进程「连上了但收不到事件」,
// 比断线更难发现,健康检查必须以 lifecycle 为准(GC-008)而不是 onopen。
// 2) 多实例/双开同一 token 会静默挤占,必须有唯一活跃连接约束。
// 3) 反向判断:如果上限就是 1,则 C1 观测到的「双连接扇出」说明上限 >1,需重新定位 1006 原因。
//
// 本探针零消息副作用:只建连、只等 lifecycle、只关闭,不发送任何消息。
// 用法: NAPCAT_WS_TOKEN=xxx node tools/probe/ws-conn-limit-probe.mjs [--max=6] [--hold=8000]
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const MAX = Number((process.argv.find((a) => a.startsWith('--max=')) || '--max=6').split('=')[1]);
const HOLD = Number((process.argv.find((a) => a.startsWith('--hold=')) || '--hold=8000').split('=')[1]);
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const fs = await import('node:fs');
const path = await import('node:path');
const OUT_DIR = process.env.PROBE_OUT || 'local';
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `ws-conn-limit-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`);
const rec = (o) => { fs.appendFileSync(OUT, JSON.stringify(o) + '\n'); return o; };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const t0 = Date.now();
const at = () => Date.now() - t0;
// 单条连接:只关心「能否完成握手」与「能否收到 lifecycle(= 认证通过并被接受为接收者)」
function open(i) {
return new Promise((resolve) => {
const c = { i, opened: null, authed: null, closed: null, code: null, reason: null, err: null, ws: null };
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
c.ws = ws;
const done = () => { clearTimeout(hard); resolve(c); };
const hard = setTimeout(() => { try { ws.close(); } catch {} done(); }, HOLD + 6000);
ws.onopen = () => { c.opened = at(); };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle' && c.authed === null) {
c.authed = at();
rec({ i, evt: 'lifecycle', at: c.authed, retcode: o.retcode ?? null, status: o.status ?? null });
} else if (o.retcode && o.retcode !== 0) {
rec({ i, evt: 'api_error', at: at(), retcode: o.retcode, message: o.message ?? null });
}
};
ws.onclose = (e) => { c.closed = at(); c.code = e.code ?? null; c.reason = e.reason || null; done(); };
ws.onerror = () => { c.err = at(); rec({ i, evt: 'error', at: c.err }); };
setTimeout(() => { if (c.authed !== null && c.closed === null) done(); }, HOLD);
});
}
console.log(`探测正向 WS 并发连接上限:依次建 ${MAX} 条,每条等待 lifecycle 最多 ${HOLD}ms`);
console.log('(零消息副作用,仅建连/关闭)\n');
const results = [];
for (let i = 1; i <= MAX; i++) {
const c = await open(i);
results.push(c);
const state = c.authed !== null ? `AUTHED(+${c.authed}ms)`
: c.err !== null ? `ERROR(+${c.err}ms) close=${c.code}@+${c.closed}ms`
: c.closed !== null ? `CLOSED code=${c.code}@+${c.closed}ms${c.reason ? ' reason=' + c.reason : ''}`
: 'TIMEOUT(无 lifecycle 无关闭)';
console.log(` 连接 #${i}: opened@${c.opened ?? '-'}ms ${state}`);
rec({ i, evt: 'summary', opened: c.opened, authed: c.authed, closed: c.closed, code: c.code, reason: c.reason, err: c.err });
if (c.authed === null) {
console.log(` ⇒ 第 ${i} 条未通过认证。等待 3s 后继续,观察是否为暂时性(旧连接释放延迟)`);
await sleep(3000);
}
await sleep(500);
}
const authedCount = results.filter((c) => c.authed !== null).length;
console.log(`\n同时保持活跃且认证通过的连接数上限(本观测)= ${authedCount}/${MAX}`);
// 关闭全部,验证「释放后能否重连」——决定重连策略是否必须等待服务端回收
for (const c of results) { try { c.ws && c.ws.close(); } catch {} }
await sleep(2500);
console.log('\n全部关闭后,再建 1 条验证是否可恢复:');
const after = await open(99);
console.log(` 释放后重连: ${after.authed !== null ? '成功 AUTHED(+' + after.authed + 'ms)' : '仍失败 close=' + after.code}`);
rec({ i: 99, evt: 'after_release', authed: after.authed, code: after.code, err: after.err });
try { after.ws && after.ws.close(); } catch {}
console.log('\n===== 结论提示 =====');
console.log(` 若上限 = 1:QLinker 与任何调试客户端不可共存,生产必须保证唯一活跃连接,且重连前须确认旧连接已被服务端释放。`);
console.log(` 若上限 > 1 但 < MAX:存在静默拒连窗口,健康检查必须以 lifecycle 为准(GC-008),onopen 不能作为可用依据。`);
console.log(` 若全部 AUTHED:reliability 中 R3 的 1006 属另一原因(快速重连触发服务端限流/半开未回收),需按错误时机另行定性。`);
console.log('\n结果 -> ' + OUT);
await sleep(300);
process.exit(0);