/** * 連線房間共用積木(PvP / 合作 PvE 都用,以「組合」而非繼承共享——避免泛型基底在 strict 模式撞 conn.send 逆變、 * 也避開兩個 hub 已分歧的流程鉤子)。單一職責、無 send、零變異風險,好測試。 */ import { randomUUID } from "node:crypto"; export type Side = "A" | "B"; /** 快速配對佇列(FIFO)。只認 playerId,與訊息型別無關 → 泛型於連線型別 C。 */ export class MatchQueue { private q: C[] = []; has(playerId: string): boolean { return this.q.some((c) => c.playerId === playerId); } enqueue(c: C): void { this.q.push(c); } /** 取最早等待者(取不到回 undefined)。 */ dequeue(): C | undefined { return this.q.shift(); } /** 放回隊首(配對失敗回滾用)。 */ requeue(c: C): void { this.q.unshift(c); } remove(playerId: string): void { const i = this.q.findIndex((c) => c.playerId === playerId); if (i >= 0) this.q.splice(i, 1); } } /** * 重連 token 表:token → (房碼, 側)。開局發 token、斷線憑 token 重綁回原房原側。 * 安全/資源強化: * - **TTL**:token 15 分鐘後失效(lookup 自動視為不存在)→ 縮小「token 外洩後可被冒用」的時間窗(token 為不可猜的 UUID、僅經 wss 下發)。 * - **上限 + 過期清掃**:即使房間因例外/崩潰未呼叫 cleanup(),也不會無限累積(接近上限時掃除過期項,仍滿則淘汰最舊)。 */ export class ReconnectRegistry { private map = new Map(); private static readonly TTL_MS = 15 * 60 * 1000; // 15 分鐘重連窗口 private static readonly MAX = 10000; // 防呆上限(正常營運遠不會到;房間清理會先移除 token) /** 建立並登記一個新 token(消費 nowMs 作為過期基準;省略則用系統時鐘)。 */ create(code: string, side: Side, nowMs: number = Date.now()): string { this.pruneIfNeeded(nowMs); const token = randomUUID(); this.map.set(token, { code, side, exp: nowMs + ReconnectRegistry.TTL_MS }); if (this.map.size > ReconnectRegistry.MAX) { const oldest = this.map.keys().next().value; // Map 保留插入序 → 首個即最舊 if (oldest !== undefined) this.map.delete(oldest); } return token; } lookup(token: string, nowMs: number = Date.now()): { code: string; side: Side } | undefined { const e = this.map.get(token); if (!e) return undefined; if (e.exp <= nowMs) { this.map.delete(token); return undefined; } // 過期 → 視為不存在並順手移除 return { code: e.code, side: e.side }; } remove(token: string): void { this.map.delete(token); } /** 接近上限才掃除過期項(避免每次 create 都 O(n))。 */ private pruneIfNeeded(nowMs: number): void { if (this.map.size < ReconnectRegistry.MAX) return; for (const [k, v] of this.map) if (v.exp <= nowMs) this.map.delete(k); } }