/** * Host-side table connection (contract 41 client rules TP-4xx/5xx), used by the table page (M19). * Owns both sockets and all credentials (CS-12); the game iframe only sees ordered `state` messages. */ import { io, type Socket } from "socket.io-client"; export interface HostCallbacks { onState(env: any): void; onViewChanged(view: string | null): void; onAck(ack: { cid: number; status: string; code?: string }): void; onStatus(status: string): void; onConnection(state: "connecting" | "online" | "offline"): void; onHello?(h: { server_time_ms: number; view: string | null; ep: number }): void; } const rand = () => Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, "0")).join(""); function ss(): Storage | null { try { return window.sessionStorage; } catch { return null; } } export class TableConnection { readonly ci: string; private cid: number; private ing!: Socket; private egr!: Socket; private view: string | null = null; private vseq = 0; private ep = 0; private buffer = new Map(); private resyncAt = 0; private pending = new Map(); private closed = false; constructor(private tid: string, private origin: string, private getTicket: (ci: string) => Promise, private cb: HostCallbacks) { const s = ss(); const key = `m3.ci.${tid}`; this.ci = s?.getItem(key) ?? rand(); // TP-004: fresh ci per tab per table s?.setItem(key, this.ci); this.cid = Number(s?.getItem(`m3.cid.${tid}.${this.ci}`) ?? 0); } connect() { const auth = (extra: () => object) => (cb: (d: object) => void) => { this.getTicket(this.ci).then((ticket) => cb({ ticket, ...extra() })).catch(() => cb({ ticket: "" })); }; const common = { transports: ["websocket"], reconnectionDelay: 500, reconnectionDelayMax: 4000 }; this.cb.onConnection("connecting"); this.ing = io(this.origin, { ...common, path: "/t/in", auth: auth(() => ({})) }); this.egr = io(this.origin, { ...common, path: "/t/out", auth: auth(() => (this.view ? { resume: { view: this.view, after_vseq: this.vseq } } : {})) }); this.ing.on("connect", () => { // TP-501: re-send pending commands with their original cid for (const [cid, p] of [...this.pending.entries()].sort((a, b) => a[0] - b[0])) this.emitCmd(cid, p.type, p.payload, p.known); this.updateConn(); }); this.ing.on("disconnect", () => this.updateConn()); this.egr.on("connect", () => this.updateConn()); this.egr.on("disconnect", () => this.updateConn()); this.egr.on("hello", (h: any) => { if (h.view !== this.view) this.setView(h.view); this.cb.onHello?.(h); }); this.egr.on("sys", (s: any) => { if (s.kind === "view_changed") this.setView(s.view); if (s.kind === "status") this.cb.onStatus(s.status); }); this.egr.on("m", (env: any) => this.onMessage(env)); this.egr.on("ack", (a: any) => { if (!this.pending.has(a.cid)) return; // TP-504 this.pending.delete(a.cid); this.cb.onAck(a); }); } private updateConn() { if (this.closed) return; this.cb.onConnection(this.ing?.connected && this.egr?.connected ? "online" : "offline"); } private setView(view: string | null) { // TP-405 this.view = view; this.vseq = 0; this.buffer.clear(); this.cb.onViewChanged(view); } private onMessage(env: any) { if (env.view !== this.view) return; // TP-401 if (env.vseq <= this.vseq) return; // TP-402 this.ep = Math.max(this.ep, env.ep); if (env.t === "snap") { // TP-403 this.vseq = env.vseq; this.cb.onState(env); this.drain(); return; } if (this.vseq > 0 && env.vseq === this.vseq + 1) { // TP-404 this.vseq = env.vseq; this.cb.onState(env); this.drain(); return; } this.buffer.set(env.vseq, env); if (this.buffer.size > 256) this.buffer.clear(); const now = Date.now(); if (now - this.resyncAt > 3000) { this.resyncAt = now; this.egr.emit("resync", { view: this.view, after_vseq: this.vseq }); } } private drain() { for (const k of [...this.buffer.keys()]) if (k <= this.vseq) this.buffer.delete(k); while (this.buffer.has(this.vseq + 1)) { const env = this.buffer.get(this.vseq + 1); this.buffer.delete(this.vseq + 1); this.vseq = env.vseq; this.cb.onState(env); } } /** Returns the assigned cid; result arrives via onAck. */ send(type: string, payload: unknown): number { const cid = ++this.cid; ss()?.setItem(`m3.cid.${this.tid}.${this.ci}`, String(cid)); const known = this.view ? { ep: this.ep, view: this.view, vseq: this.vseq } : undefined; this.pending.set(cid, { type, payload, known }); if (this.ing.connected) this.emitCmd(cid, type, payload, known); return cid; } private emitCmd(cid: number, type: string, payload: unknown, known?: unknown) { this.ing.emit("cmd", { tid: this.tid, cid, type, payload, known }, (r: any) => { if (r && !r.ok) { this.pending.delete(cid); this.cb.onAck({ cid, status: "failed", code: r.code }); } }); } close() { this.closed = true; this.ing?.close(); this.egr?.close(); } }