All files / client/src/lib websocket-manager.ts

86.05% Statements 179/208
71.59% Branches 63/88
96.87% Functions 31/32
87.06% Lines 175/201

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513                                      27x                         27x                                     27x   27x 27x 27x 27x 27x 27x     27x 27x     27x     27x     27x     27x     27x       27x             28x 28x               1x 1x             1x 1x               46x 22x 22x 22x 46x                   46x 46x     46x       46x       46x                 47x 1x 1x     46x           46x             46x   46x 46x     46x   46x 47x       47x 45x 45x 45x                   46x 1x     46x 47x   47x 47x     47x 21x 21x 21x 21x       47x 47x 47x 47x                           106x 1x 1x       105x     105x 1x 1x       104x 2x     104x             3x 1x 1x     2x 2x 2x   1x 1x               3x 3x 3x     3x   3x               3x 3x   3x 104x 104x           3x 2x               4x 4x       4x 4x 4x             9x 9x   9x 9x 9x       9x 3x               9x             3x             2x           17x 17x 17x 17x   17x 17x       2x 2x 2x 1x 1x     1x             22x 22x     22x 22x     22x 22x         1x 1x       21x 21x 21x 21x         43x     43x     26x               26x 26x 26x   26x 26x   26x   26x 23x 23x         4x       4x       60x 40x 40x           50x 1x 1x   50x   50x   27x 27x 27x 27x     27x 4x 4x           27x         93x 93x 93x 93x         116x 116x 27x 26x 26x   1x               28x     27x 27x    
/**
 * WebSocket Singleton Manager
 * 
 * Ensures exactly ONE WebSocket connection exists across the entire application.
 * Key features:
 * - Global singleton pattern (module-level instance)
 * - Message buffering with configurable flush interval
 * - Exponential backoff reconnection
 * - Event-based architecture for React integration
 * - Cloudflare Tunnel compatible (standard WebSocket protocol)
 * 
 * CRITICAL: ws.send() NEVER creates a new WebSocket
 * CRITICAL: Only 1 connection → many messages
 */
 
import { Logger } from "@shared/logger";
import type { WSMessage } from "@shared/schema";
import { isArduinoMessage } from "@/types/websocket";
 
const logger = new Logger("WebSocketManager");
 
// Connection states for external consumers
export type ConnectionState = "connecting" | "connected" | "disconnected" | "reconnecting";
 
// Event types emitted by the manager
interface WSManagerEvents {
  stateChange: (state: ConnectionState) => void;
  message: (data: WSMessage) => void;
  error: (error: string) => void;
}
 
// Configuration
const CONFIG = {
  // Message buffer settings
  BUFFER_FLUSH_INTERVAL_MS: 30, // Collect messages for 30ms before sending
  MAX_BUFFER_SIZE: 100,         // Force flush if buffer exceeds this
  
  // Reconnection settings
  RECONNECT_BASE_DELAY_MS: 1000,
  RECONNECT_MAX_DELAY_MS: 30000,
  RECONNECT_MAX_ATTEMPTS: Infinity,
  
  // Connection settings
  CONNECTION_TIMEOUT_MS: 30_000,
  
  // Thundering-herd mitigation: stagger initial connection when embedded in an
  // iframe so that 50+ simultaneous instances don't all hit the server at once.
  IFRAME_STAGGER_MAX_MS: 10_000,
} as const;
 
class WebSocketManager {
  private static instance: WebSocketManager | null = null;
  
  private ws: WebSocket | null = null;
  private state: ConnectionState = "disconnected";
  private reconnectAttempts = 0;
  private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
  private connectionTimeout: ReturnType<typeof setTimeout> | null = null;
  private staggerTimeout: ReturnType<typeof setTimeout> | null = null;
  
  // Message buffer for batching
  private messageBuffer: WSMessage[] = [];
  private bufferFlushTimeout: ReturnType<typeof setTimeout> | null = null;
  
  // Event listeners
  private readonly listeners: Map<keyof WSManagerEvents, Set<Function>> = new Map();
  
  // Prevent duplicate connection attempts
  private isConnecting = false;
  
  // Track if we ever successfully connected (for UI messaging)
  private _hasEverConnected = false;
  
  // Whether initial connection stagger has been applied (one-time only)
  private initialStaggerApplied = false;
  
  // Test isolation: unique ID for E2E tests
  private testRunId: string | null = null;
  
  private constructor() {
    // Private constructor for singleton
    logger.info("WebSocketManager instance created");
  }
  
  /**
   * Get the singleton instance
   */
  public static getInstance(): WebSocketManager {
    WebSocketManager.instance ??= new WebSocketManager();
    return WebSocketManager.instance;
  }
  
  /**
   * Set testRunId for E2E test isolation (test-only feature)
   * Call this before connect() to associate this connection with a specific test
   */
  public setTestRunId(id: string): void {
    this.testRunId = id;
    logger.debug(`[Test Isolation] testRunId set: ${id}`);
  }
  
  /**
   * Clear testRunId (called when E2E test resets)
   */
  public clearTestRunId(): void {
    this.testRunId = null;
    logger.debug(`[Test Isolation] testRunId cleared`);
  }
  
  /**
   * Check if we're inside an iframe and should stagger the initial connection.
   * Returns true if a stagger was scheduled (caller should return early).
   */
  private applyIframeStagger(): boolean {
    if (this.initialStaggerApplied) return false;
    this.initialStaggerApplied = true;
    try {
      const inIframe = globalThis.window !== undefined && globalThis.window !== globalThis.window.parent;
      if (!inIframe) return false;
    } catch {
      // Cross-origin iframe access may throw — connect immediately
      return false;
    }
    // Prefer deterministic stagger from ?iframeIndex=N URL param.
    // This is immune to Chromium's background-timer throttling which defeats
    // Math.random()-based stagger (all timers end up in the same 1-s throttle
    // bucket when Chrome classifies the iframe as "hidden").
    const params = new URLSearchParams(globalThis.location?.search ?? "");
    const iframeIndex = Number.parseInt(params.get("iframeIndex") ?? "", 10);
    const staggerMs = Number.isNaN(iframeIndex)
      ? (crypto.getRandomValues(new Uint32Array(1))[0] / 0xFFFFFFFF) * CONFIG.IFRAME_STAGGER_MAX_MS
      : Math.min(iframeIndex * 250, CONFIG.IFRAME_STAGGER_MAX_MS);
    logger.info(
      `[Iframe] Staggering initial connection by ${Math.round(staggerMs)}ms` +
      (Number.isNaN(iframeIndex) ? " (random)" : ` (iframeIndex=${iframeIndex})`),
    );
    this.staggerTimeout = setTimeout(() => {
      this.staggerTimeout = null;
      this.connect();
    }, staggerMs);
    return true;
  }
 
  /**
   * Initialize and connect WebSocket
   * Safe to call multiple times - will not create duplicate connections
   */
  public connect(): void {
    // Guard: Already connected or connecting
    if (this.ws?.readyState === WebSocket.OPEN) {
      logger.debug("Already connected, skipping connect()");
      return;
    }
    
    Iif (this.isConnecting) {
      logger.debug("Connection already in progress, skipping connect()");
      return;
    }
    
    // Guard: WebSocket in CONNECTING state
    Iif (this.ws?.readyState === WebSocket.CONNECTING) {
      logger.debug("WebSocket already connecting, skipping");
      return;
    }
    
    // Thundering-herd mitigation: stagger the very first connection when
    // embedded in an iframe so 50+ instances don't handshake simultaneously.
    Iif (this.applyIframeStagger()) return;
    
    this.isConnecting = true;
    this.setState("connecting");
    
    // Clean up any existing connection
    this.cleanupConnection();
    
    const protocol = globalThis.location.protocol === "https:" ? "wss:" : "ws:";
    let wsUrl = `${protocol}//${globalThis.location.host}/ws`;
    
    // Check for testRunId from sessionStorage (E2E test isolation)
    // or use previously set testRunId
    if (!this.testRunId && globalThis.window !== undefined) {
      try {
        const storedTestRunId = globalThis.sessionStorage?.getItem("__TEST_RUN_ID__");
        Iif (storedTestRunId) {
          this.testRunId = storedTestRunId;
          logger.debug(`[Test Isolation] Loaded testRunId from sessionStorage: ${this.testRunId}`);
        }
      } catch (err) {
        logger.debug(`Could not read sessionStorage: ${err}`);
      }
    }
    
    // Add testRunId query param for E2E test isolation
    if (this.testRunId) {
      wsUrl += `?testRunId=${encodeURIComponent(this.testRunId)}`;
    }
    
    const testRunSuffix = this.testRunId ? ` [testRunId: ${this.testRunId}]` : "";
    logger.info(`Connecting to WebSocket: ${wsUrl}${testRunSuffix}`);
    
    try {
      this.ws = new WebSocket(wsUrl);
      
      // Set connection timeout
      this.connectionTimeout = setTimeout(() => {
        Eif (this.ws?.readyState === WebSocket.CONNECTING) {
          logger.warn("Connection timeout - closing socket");
          this.ws.close();
          this.handleConnectionFailure("Connection timeout");
        }
      }, CONFIG.CONNECTION_TIMEOUT_MS);
      
      this.ws.onopen = this.handleOpen.bind(this);
      this.ws.onmessage = this.handleMessage.bind(this);
      this.ws.onclose = this.handleClose.bind(this);
      this.ws.onerror = this.handleError.bind(this);
      
    } catch (error) {
      logger.error(`Failed to create WebSocket: ${error}`);
      this.handleConnectionFailure(`Failed to create WebSocket: ${error}`);
    }
  }
  
  /**
   * Send a message through the WebSocket
   * Messages are buffered and sent in batches for efficiency
   */
  public send(message: WSMessage): boolean {
    // CRITICAL: Never create new WebSocket in send()
    if (this.ws?.readyState !== WebSocket.OPEN) {
      logger.warn(`Cannot send - WebSocket not open (state: ${this.ws?.readyState}). Message dropped: ${message.type}`);
      return false;
    }
    
    // Add to buffer
    this.messageBuffer.push(message);
    
    // Force flush if buffer is full
    if (this.messageBuffer.length >= CONFIG.MAX_BUFFER_SIZE) {
      this.flushBuffer();
      return true;
    }
    
    // Schedule flush if not already scheduled
    this.bufferFlushTimeout ??= setTimeout(() => {
      this.flushBuffer();
    }, CONFIG.BUFFER_FLUSH_INTERVAL_MS);
    
    return true;
  }
  
  /**
   * Send immediately without buffering (for critical messages)
   */
  public sendImmediate(message: WSMessage): boolean {
    if (this.ws?.readyState !== WebSocket.OPEN) {
      logger.warn(`Cannot send immediate - WebSocket not open. Message: ${message.type}`);
      return false;
    }
    
    try {
      this.ws.send(JSON.stringify(message));
      return true;
    } catch (error) {
      logger.error(`Failed to send message: ${error}`);
      return false;
    }
  }
  
  /**
   * Flush the message buffer
   */
  private flushBuffer(): void {
    Eif (this.bufferFlushTimeout) {
      clearTimeout(this.bufferFlushTimeout);
      this.bufferFlushTimeout = null;
    }
    
    Iif (this.messageBuffer.length === 0) return;
    
    Iif (this.ws?.readyState !== WebSocket.OPEN) {
      logger.warn(`Cannot flush buffer - WebSocket not open. ${this.messageBuffer.length} messages dropped.`);
      this.messageBuffer = [];
      return;
    }
    
    // Send each message individually (server expects individual messages)
    // But we batch the sends in one synchronous block
    const messages = [...this.messageBuffer];
    this.messageBuffer = [];
    
    for (const msg of messages) {
      try {
        this.ws.send(JSON.stringify(msg));
      } catch (error) {
        logger.error(`Failed to send buffered message: ${error}`);
      }
    }
    
    if (messages.length > 1) {
      logger.debug(`Flushed ${messages.length} buffered messages`);
    }
  }
  
  /**
   * Gracefully disconnect
   */
  public disconnect(): void {
    logger.info("Disconnecting WebSocket");
    Iif (this.staggerTimeout) {
      clearTimeout(this.staggerTimeout);
      this.staggerTimeout = null;
    }
    this.cancelReconnect();
    this.cleanupConnection();
    this.setState("disconnected");
  }
  
  /**
   * Subscribe to events
   */
  public on<K extends keyof WSManagerEvents>(event: K, callback: WSManagerEvents[K]): () => void {
    Eif (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }
    const listeners = this.listeners.get(event);
    Eif (listeners) {
      listeners.add(callback);
    }
    
    // Return unsubscribe function
    return () => {
      this.listeners.get(event)?.delete(callback);
    };
  }
  
  /**
   * Get current connection state
   */
  public getState(): ConnectionState {
    return this.state;
  }
  
  /**
   * Check if connected
   */
  public isConnected(): boolean {
    return this.ws?.readyState === WebSocket.OPEN;
  }
  
  /**
   * Check if ever successfully connected
   */
  public hasEverConnected(): boolean {
    return this._hasEverConnected;
  }
  
  // --- Private methods ---
  
  private handleOpen(): void {
    this.isConnecting = false;
    this.clearConnectionTimeout();
    this.reconnectAttempts = 0;
    this._hasEverConnected = true;
    
    logger.info("WebSocket connected successfully");
    this.setState("connected");
  }
  
  private handleMessage(event: MessageEvent): void {
    try {
      const raw = JSON.parse(event.data);
      if (!isArduinoMessage(raw)) {
        logger.error(`Invalid WebSocket message schema: ${JSON.stringify(raw)}`);
        return;
      }
 
      this.emit("message", raw);
    } catch (error) {
      logger.error(`Invalid WebSocket message: ${error}. Raw: ${event.data}`);
    }
  }
  
  private handleClose(event: CloseEvent): void {
    this.isConnecting = false;
    this.clearConnectionTimeout();
    
    // Code 1001 is normal closure - log at DEBUG level, others at INFO
    const logLevel = event.code === 1001 ? 'debug' : 'info';
    logger[logLevel](`WebSocket closed: code=${event.code}, reason=${event.reason || "none"}`);
    
    // Only reconnect if we didn't explicitly disconnect
    Eif (this.state !== "disconnected") {
      this.scheduleReconnect();
    }
  }
  
  private handleError(event: Event): void {
    logger.error(`WebSocket error: ${event.type}`);
    this.emit("error", "WebSocket connection error");
  }
  
  private handleConnectionFailure(reason: string): void {
    this.isConnecting = false;
    this.clearConnectionTimeout();
    this.emit("error", reason);
    this.scheduleReconnect();
  }
  
  private scheduleReconnect(): void {
    // Guard: Don't reconnect if explicitly disconnected
    Iif (this.state === "disconnected") return;
    
    // Guard: Already have a reconnect scheduled
    if (this.reconnectTimeout) return;
    
    // Guard: Max attempts reached
    Iif (this.reconnectAttempts >= CONFIG.RECONNECT_MAX_ATTEMPTS) {
      logger.warn(`Max reconnect attempts (${CONFIG.RECONNECT_MAX_ATTEMPTS}) reached. Giving up.`);
      this.setState("disconnected");
      this.emit("error", "Max reconnection attempts reached. Please refresh the page.");
      return;
    }
    
    // Calculate delay with exponential backoff + jitter
    const baseDelay = CONFIG.RECONNECT_BASE_DELAY_MS * Math.pow(2, this.reconnectAttempts);
    const jitter = (crypto.getRandomValues(new Uint32Array(1))[0] / 0xFFFFFFFF) * 1000; // 0-1s random jitter
    const delay = Math.min(baseDelay + jitter, CONFIG.RECONNECT_MAX_DELAY_MS);
    
    this.reconnectAttempts++;
    this.setState("reconnecting");
    
    logger.debug(`Scheduling reconnect in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts})`);
    
    this.reconnectTimeout = setTimeout(() => {
      this.reconnectTimeout = null;
      this.connect();
    }, delay);
  }
  
  private cancelReconnect(): void {
    Iif (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
      this.reconnectTimeout = null;
    }
    this.reconnectAttempts = 0;
  }
  
  private clearConnectionTimeout(): void {
    if (this.connectionTimeout) {
      clearTimeout(this.connectionTimeout);
      this.connectionTimeout = null;
    }
  }
  
  private cleanupConnection(): void {
    // Flush any remaining buffered messages
    if (this.bufferFlushTimeout) {
      clearTimeout(this.bufferFlushTimeout);
      this.bufferFlushTimeout = null;
    }
    this.messageBuffer = [];
    
    if (this.ws) {
      // Remove all event handlers to prevent memory leaks
      this.ws.onopen = null;
      this.ws.onmessage = null;
      this.ws.onclose = null;
      this.ws.onerror = null;
      
      // Only close if not already closed/closing
      if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
        try {
          this.ws.close(1000, "Client disconnect");
        } catch {
          // Ignore close errors
        }
      }
      
      this.ws = null;
    }
  }
  
  private setState(newState: ConnectionState): void {
    Eif (this.state !== newState) {
      logger.debug(`State change: ${this.state} → ${newState}`);
      this.state = newState;
      this.emit("stateChange", newState);
    }
  }
  
  private emit<K extends keyof WSManagerEvents>(event: K, ...args: Parameters<WSManagerEvents[K]>): void {
    const callbacks = this.listeners.get(event);
    if (callbacks) {
      callbacks.forEach(cb => {
        try {
          cb(...args);
        } catch (error) {
          logger.error(`Error in event handler for ${event}: ${error}`);
        }
      });
    }
  }
}
 
// Export singleton getter for clean imports
export const getWebSocketManager = (): WebSocketManager => WebSocketManager.getInstance();
 
// Export for debugging in browser console
Eif (globalThis.window !== undefined) {
  (globalThis as any).__wsManager = getWebSocketManager;
}