summaryrefslogtreecommitdiff
path: root/web/src/lib/protocol
diff options
context:
space:
mode:
Diffstat (limited to 'web/src/lib/protocol')
-rw-r--r--web/src/lib/protocol/connection.ts231
-rw-r--r--web/src/lib/protocol/types.ts214
2 files changed, 412 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());
}
}
diff --git a/web/src/lib/protocol/types.ts b/web/src/lib/protocol/types.ts
new file mode 100644
index 0000000..b8ced78
--- /dev/null
+++ b/web/src/lib/protocol/types.ts
@@ -0,0 +1,214 @@
+/**
+ * Client-side mirrors of the server's wire protocol and state JSON
+ * (PLAN.md section 3.5). Field names match the server's `toJson()`
+ * exactly — the server is the source of truth.
+ */
+
+// --- Enums (the server serializes enums as their value index) -------------
+
+/** 0 = chooseInitiative, 1 = playTurns. */
+export type RoundState = 0 | 1;
+/** 0 = notDone, 1 = current, 2 = done. */
+export type TurnsState = 0 | 1 | 2;
+/** MonsterType index: 0 normal, 1 elite, 2 boss, 3 summon. */
+export type MonsterType = 0 | 1 | 2 | 3;
+export type Role = 'player' | 'spectator';
+
+// --- State figures ---------------------------------------------------------
+
+/** The figure base shared by characters and monster standees. */
+export interface FigureState {
+ level: number;
+ health: number;
+ maxHealth: number;
+ chill: number;
+ /** Condition indices (see `Condition`). */
+ conditions: number[];
+ conditionsAddedThisTurn: number[];
+ conditionsAddedPreviousTurn: number[];
+}
+
+export interface CharacterState extends FigureState {
+ /**
+ * Initiative value. `null` when the value is secret for this
+ * connection (the server masks every non-owned character during
+ * chooseInitiative — PLAN.md section 3.4).
+ */
+ initiative: number | null;
+ xp: number;
+ display: string;
+ modifierDeck: unknown;
+ summonList: MonsterInstance[];
+ useFHPerks: boolean;
+ perkList: boolean[];
+}
+
+export interface MonsterInstance extends FigureState {
+ standeeNr: number;
+ move: number;
+ attack: number;
+ range: number;
+ name: string;
+ /** Artwork file name (resolved under /images/). */
+ gfx: string;
+ roundSummoned: number;
+ type: MonsterType;
+ plague: number;
+}
+
+// --- Current-list items ----------------------------------------------------
+
+export interface CharacterItem {
+ id: string;
+ turnState: TurnsState;
+ note: string;
+ characterState: CharacterState;
+ /** Character-class id (discriminator). */
+ characterClass: string;
+ edition: string;
+}
+
+export interface MonsterItem {
+ id: string;
+ turnState: TurnsState;
+ note: string;
+ isActive: boolean;
+ /** Monster model name (discriminator). */
+ type: string;
+ monsterInstances: MonsterInstance[];
+ isAlly: boolean;
+ v: number;
+ level: number;
+}
+
+export interface NoteRowItem {
+ id: string;
+ /** Discriminator flag. */
+ noteRow: true;
+ text: string;
+ color: number;
+ linkedId: string;
+ standeeNr: number;
+}
+
+export type ListItem = CharacterItem | MonsterItem | NoteRowItem;
+
+export function isCharacter(item: ListItem): item is CharacterItem {
+ return 'characterState' in item && 'characterClass' in item;
+}
+export function isMonster(item: ListItem): item is MonsterItem {
+ return 'monsterInstances' in item && 'type' in item;
+}
+export function isNoteRow(item: ListItem): item is NoteRowItem {
+ return (item as NoteRowItem).noteRow === true;
+}
+
+export interface SpecialRule {
+ type: string;
+ note: string;
+ name: string;
+ health: string;
+ condition: string;
+ init: number;
+ level: number;
+ startOfRound: boolean;
+ list: unknown[];
+}
+
+export interface GameState {
+ level: number;
+ solo: boolean;
+ autoScenarioLevel: boolean;
+ difficulty: number;
+ roundState: RoundState;
+ round: number;
+ totalRounds: number;
+ scenario: string;
+ toastMessage: string;
+ scenarioSpecialRules: SpecialRule[];
+ scenarioSectionsAdded: string[];
+ currentCampaign: string;
+ currentList: ListItem[];
+ currentAbilityDecks: unknown[];
+ sanctuaryDeck: unknown;
+ modifierDeck: unknown;
+ modifierDeckAllies: unknown;
+ lootDeck: unknown;
+ unlockedClasses: string[];
+ showAllyDeck: boolean;
+ allyDeckInOGGloom: boolean;
+ /** element index → element-state index. */
+ elementState: Record<string, number>;
+}
+
+// --- Messages --------------------------------------------------------------
+
+export interface GameEvent {
+ type: string;
+ [ key: string ]: unknown;
+}
+
+export interface WelcomeMessage {
+ t: 'welcome';
+ v: number;
+ session: string;
+ role: Role;
+ index: number;
+ description: string | null;
+ event: GameEvent | null;
+ state: GameState;
+ /** character id → owning session id (null when unclaimed). */
+ seats: Record<string, string | null>;
+}
+
+export interface UpdateMessage {
+ t: 'update';
+ index: number;
+ description: string;
+ event: GameEvent;
+ state: GameState;
+}
+
+export interface SeatsMessage {
+ t: 'seats';
+ seats: Record<string, string | null>;
+}
+
+export interface ErrorMessage {
+ t: 'error';
+ code: string;
+ message: string;
+}
+
+export interface PongMessage {
+ t: 'pong';
+}
+
+export type ServerMessage =
+ | WelcomeMessage
+ | UpdateMessage
+ | SeatsMessage
+ | ErrorMessage
+ | PongMessage;
+
+// --- Client → server -------------------------------------------------------
+
+export interface CommandArgs {
+ [ key: string ]: unknown;
+}
+
+/** Outbound command message body (without the `t` field, added by the client). */
+export function commandMessage(name: string, args: CommandArgs = {}) {
+ return { t: 'cmd', name, args } as const;
+}
+export function claimMessage(characterId: string) {
+ return { t: 'claim', characterId } as const;
+}
+export function helloMessage() {
+ return { t: 'hello', v: 1 } as const;
+}
+export function pingMessage() {
+ return { t: 'ping' } as const;
+}
+export const undoMessage = () => ({ t: 'undo' }) as const;
+export const redoMessage = () => ({ t: 'redo' }) as const;