diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-15 13:45:21 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-15 13:45:21 +0100 |
| commit | 4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (patch) | |
| tree | 94e6286e7e22e0467a61b99c18b9ab582fbbe656 /web/src/lib/protocol/connection.ts | |
| parent | 3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (diff) | |
Phase 3: web UI core loop (M3)
Browser game UI on top of the Phase 2 protocol: server-driven, input-only
clients with per-connection secret visibility.
Web (Svelte 5):
- Layout: TopBar (element buttons with use/imbue long-press, title, menu),
MainList (character/monster/note rows), BottomBar (draw/next-round +
level widget with T/H/X/C values).
- CharacterRow with the secret initiative input: own value editable,
server-masked values render as ??, revealed on draw.
- Per-figure StatusMenu: health/max/xp/bless/curse/empower/enfeeble
steppers, condition grid, turn-done — all server commands, player-gated.
- Menu dialogs: select scenario, add section, add/remove character,
set level/difficulty/solo/auto-level, add/remove monster, note row,
action log with rollback, settings (style theme + language).
- Player vs spectator UI gated on the live seat table; reconnecting
banner, error toasts, connection status plumbing.
- i18n: English ported, locale store with localStorage persistence.
- Design tokens + the three style themes (frosthaven/gloomhaven/original).
- Unit tests: level values, game logic (elements/conditions/art/stats),
i18n, the reactive player store, the data client (sections keyed by
scenario number), plus the existing connection/protocol/state tests.
Server:
- Serve the engine's data JSON at /data/ and artwork at /images/ so the
client menus and rows read the same assets the engine loads.
Diffstat (limited to 'web/src/lib/protocol/connection.ts')
| -rw-r--r-- | web/src/lib/protocol/connection.ts | 231 |
1 files changed, 198 insertions, 33 deletions
diff --git a/web/src/lib/protocol/connection.ts b/web/src/lib/protocol/connection.ts index 0826a3c..51305a1 100644 --- a/web/src/lib/protocol/connection.ts +++ b/web/src/lib/protocol/connection.ts @@ -1,57 +1,222 @@ /** - * Client side of the X-Haven wire protocol (PLAN.md section 3.5). + * The X-Haven WebSocket client (PLAN.md section 3.5). * - * Phase 0 scope: connect to `/ws`, send the `hello` handshake, surface the - * `welcome` message and connection status. Reconnect/resync, commands, claims - * and state updates arrive in later phases. + * Responsibilities: + * - the `hello` handshake (the session id rides in the cookie, set by the + * `/session` endpoint / the upgrade request) + * - a keepalive `ping` so the server's dead-connection sweep never closes a + * live tab + * - automatic reconnect with exponential backoff; every (re)connect re-sends + * `hello`, which the server answers with a full `welcome` — that is the + * resync + * - typed dispatch of `welcome` / `update` / `seats` / `error` / `pong` + * - outbound command / claim / undo / redo helpers + * + * The [WebSocket]-compatible transport is injectable so the reconnect and + * resync behaviour can be exercised in unit tests with a fake socket. */ -export interface Welcome { - t: 'welcome'; - v: number; - session: string; - role: 'player' | 'spectator'; - index: number; - description: string | null; - event: unknown; - state: Record<string, unknown>; - seats: Record<string, unknown>; -} +import type { + ErrorMessage, + ServerMessage +} from './types'; +import { claimMessage, helloMessage, pingMessage } from './types'; + +export type ConnectionStatus = + | 'connecting' + | 'open' + | 'reconnecting' + | 'closed'; -export type ConnectionStatus = 'connecting' | 'open' | 'closed'; +/** A `WebSocket`-compatible surface (enough for the tests' fake). */ +export interface Transport { + onopen: ((ev?: unknown) => void) | null; + onclose: ((ev?: unknown) => void) | null; + onerror: ((ev?: unknown) => void) | null; + onmessage: ((ev: { data: unknown }) => void) | null; + send(data: string): void; + close(): void; + readyState: number; // 0 OPEN +} -/** The handshake message sent right after the WebSocket opens. */ -export function buildHello(): Record<string, unknown> { - return { t: 'hello', v: 1 }; +export interface ConnectionOptions { + /** Absolute `ws://` / `wss://` URL. Defaults to the page origin `/ws`. */ + url?: string; + /** Inject a transport factory (tests). Defaults to `new WebSocket(url)`. */ + transport?: (url: string) => Transport; + /** Reconnect base delay in ms (doubles each attempt, capped). */ + reconnectBaseMs?: number; + reconnectMaxMs?: number; + /** Keepalive ping interval in ms. */ + pingIntervalMs?: number; } +const OPEN = 0; + export class GameConnection { - private ws: WebSocket | null = null; + status: ConnectionStatus = 'connecting'; + /** The session id from the last `welcome` (null before the handshake). */ + session: string | null = null; - onWelcome: ((welcome: Welcome) => void) | null = null; onStatus: ((status: ConnectionStatus) => void) | null = null; + /** Every server message, in order (including `pong`). */ + onMessage: ((message: ServerMessage) => void) | null = null; + /** Convenience hook for `error` messages only. */ + onError: ((error: ErrorMessage) => void) | null = null; + + private ws: Transport | null = null; + private readonly options: Required< + Pick< + ConnectionOptions, + 'reconnectBaseMs' | 'reconnectMaxMs' | 'pingIntervalMs' + > + > & + ConnectionOptions; + private readonly url: string; + private intentionalClose = false; + private reconnectDelay = 0; + private reconnectTimer: ReturnType<typeof setTimeout> | null = null; + private pingTimer: ReturnType<typeof setInterval> | null = null; + private disposed = false; + + constructor(options: ConnectionOptions = {}) { + this.options = { + reconnectBaseMs: 500, + reconnectMaxMs: 15_000, + pingIntervalMs: 25_000, + ...options + }; + const explicit = options.url; + if (explicit) { + this.url = explicit; + } else { + const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'; + this.url = `${proto}://${window.location.host}/ws`; + } + } + + private makeTransport(): Transport { + if (this.options.transport) return this.options.transport(this.url); + return new WebSocket(this.url) as unknown as Transport; + } connect(): void { - const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'; - const ws = new WebSocket(`${proto}://${window.location.host}/ws`); + this.intentionalClose = false; + this.openSocket(); + } + + /** Stop connecting and never reconnect (page teardown). */ + disconnect(): void { + this.disposed = true; + this.intentionalClose = true; + this.clearTimers(); + this.ws?.close(); + this.ws = null; + } + + private setStatus(status: ConnectionStatus) { + this.status = status; + this.onStatus?.(status); + } + + private openSocket() { + if (this.disposed) return; + this.setStatus(this.ws === null && this.session === null ? 'connecting' : 'reconnecting'); + const ws = this.makeTransport(); this.ws = ws; ws.onopen = () => { - this.onStatus?.('open'); - ws.send(JSON.stringify(buildHello())); + this.setStatus('open'); + this.sendRaw(helloMessage()); + this.startPing(); }; - ws.onclose = () => this.onStatus?.('closed'); - ws.onerror = () => this.onStatus?.('closed'); - ws.onmessage = (event) => { - const message = JSON.parse(String(event.data)) as { t: string }; + ws.onmessage = (ev) => { + const text = typeof ev.data === 'string' ? ev.data : ''; + let message: ServerMessage; + try { + message = JSON.parse(text) as ServerMessage; + } catch { + return; // ignore non-JSON frames + } if (message.t === 'welcome') { - this.onWelcome?.(message as unknown as Welcome); + this.session = message.session; + // A real resync landed: the connection is healthy, so the + // backoff starts fresh from the base on the next drop. + this.reconnectDelay = 0; + } + this.onMessage?.(message); + if (message.t === 'error') this.onError?.(message); + }; + ws.onclose = () => { + this.stopPing(); + if (this.disposed || this.intentionalClose) { + this.setStatus('closed'); + return; } + this.scheduleReconnect(); }; + // onerror is always followed by onclose in the browser; nothing to do. + ws.onerror = () => {}; } - close(): void { - this.ws?.close(); - this.ws = null; + private scheduleReconnect() { + this.setStatus('reconnecting'); + const delay = this.reconnectDelay || this.options.reconnectBaseMs; + this.reconnectDelay = Math.min( + delay * 2, + this.options.reconnectMaxMs + ); + this.reconnectTimer = setTimeout(() => this.openSocket(), delay); + } + + private clearTimers() { + if (this.reconnectTimer) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + this.stopPing(); + } + + private startPing() { + this.stopPing(); + this.pingTimer = setInterval(() => { + if (this.ws && this.ws.readyState === OPEN) this.sendRaw(pingMessage()); + }, this.options.pingIntervalMs); + } + + private stopPing() { + if (this.pingTimer) { + clearInterval(this.pingTimer); + this.pingTimer = null; + } + } + + private sendRaw(message: object) { + if (this.ws && this.ws.readyState === OPEN) { + this.ws.send(JSON.stringify(message)); + } + } + + /** Execute a registered command (players only on the server side). */ + sendCmd(name: string, args: Record<string, unknown> = {}): void { + this.sendRaw({ t: 'cmd', name, args }); + } + + /** Claim (or re-assert) a character seat. */ + claim(characterId: string): void { + this.sendRaw(claimMessage(characterId)); + } + + undo(): void { + this.sendRaw({ t: 'undo' }); + } + + redo(): void { + this.sendRaw({ t: 'redo' }); + } + + /** Re-request a full resync (the server re-answers with a `welcome`). */ + resync(): void { + this.sendRaw(helloMessage()); } } |
