Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : apps/navigator-web/src/viewer/connection.ts9 * Module : viewer10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Viewer side of the navigator wire protocol: one authenticated WebSocket per open session.43// JSON control messages in both directions, binary JPEG frames from the gateway.44// Reconnects on its own (1 → 10 s backoff) but never asks for control again: that stays a human decision.45import { loadMe } from '../../../shared/api.ts';46import type { ServerMsg, ViewerMsg } from '../types.ts';4748export type ConnState = 'connecting' | 'open' | 'waiting' | 'unauthorized' | 'stopped';49export type Problem = 'decode_failed' | 'bad_frame' | 'bad_json' | 'send_failed' | 'socket_failed' | 'no_pong';50export type Frame = { n: number; w: number; h: number; bitmap: ImageBitmap };51export interface ConnHandlers {52 onMessage(m: ServerMsg): void;53 /** Called with a decoded frame; draw it synchronously, the bitmap is released right after. */54 onFrame(f: Frame): void;55 onState(s: ConnState, retryInMs?: number): void;56 onRtt(ms: number): void;57 onProblem(p: Problem): void;58}59type Pending = { n: number; w: number; h: number; bytes: Uint8Array<ArrayBuffer> };6061const PING_MS = 5000;62const PONG_TIMEOUT_MS = 20000;6364export class NavConnection {65 private ws: WebSocket | null = null;66 private stopped = true;67 private attempt = 0;68 private retryTimer = 0;69 private pingTimer = 0;70 private lastPong = 0;71 private pending: Pending | null = null;72 private decoding = false;7374 constructor(private readonly sessionId: string, private readonly h: ConnHandlers) {}7576 start() {77 if (!this.stopped) return;78 this.stopped = false;79 document.addEventListener('visibilitychange', this.onVisibility);80 this.pingTimer = window.setInterval(this.ping, PING_MS);81 this.open();82 }83 stop() {84 this.stopped = true;85 document.removeEventListener('visibilitychange', this.onVisibility);86 window.clearInterval(this.pingTimer); window.clearTimeout(this.retryTimer);87 const ws = this.ws; this.ws = null; this.pending = null;88 if (ws) { ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null; try { ws.close(); } catch { /* already closed */ } }89 this.h.onState('stopped');90 }91 /** Skip the backoff wait (button "retry now"). */92 retryNow() { if (this.stopped || this.ws) return; window.clearTimeout(this.retryTimer); this.open(); }93 get isOpen() { return !!this.ws && this.ws.readyState === WebSocket.OPEN; }9495 /** Returns false when nothing was sent (socket not open). */96 send(m: ViewerMsg): boolean {97 const ws = this.ws;98 if (!ws || ws.readyState !== WebSocket.OPEN) return false;99 try { ws.send(JSON.stringify(m)); return true; } catch { this.h.onProblem('send_failed'); return false; }100 }101102 private open() {103 window.clearTimeout(this.retryTimer);104 this.h.onState('connecting');105 let ws: WebSocket;106 try { ws = new WebSocket(`${location.protocol === 'https:' ? 'wss://' : 'ws://'}${location.host}/nav/ws?session=${encodeURIComponent(this.sessionId)}`); }107 catch { this.h.onProblem('socket_failed'); this.schedule(); return; }108 ws.binaryType = 'arraybuffer';109 this.ws = ws;110 let opened = false;111 ws.onopen = () => { if (this.ws !== ws) return; opened = true; this.attempt = 0; this.lastPong = performance.now(); this.h.onState('open'); this.ping(); };112 ws.onmessage = (e) => { if (this.ws !== ws) return; if (typeof e.data === 'string') this.onText(e.data); else this.onBinary(e.data as ArrayBuffer); };113 ws.onerror = () => { /* the browser gives no detail; `close` always follows and is reported through onState */ };114 ws.onclose = () => {115 if (this.ws !== ws) return;116 this.ws = null; this.pending = null;117 if (this.stopped) return;118 // A refused handshake looks like any other failure from a browser: ask the API whether we are still signed in.119 if (!opened) void this.afterRefusal(); else this.schedule();120 };121 }122 private async afterRefusal() {123 try { if ((await loadMe()) === null) { if (!this.stopped) this.h.onState('unauthorized'); return; } } catch { /* API unreachable too: keep retrying */ }124 if (!this.stopped && !this.ws) this.schedule();125 }126 private schedule() {127 const delay = Math.min(10000, 1000 * 2 ** this.attempt);128 this.attempt = Math.min(this.attempt + 1, 8);129 this.h.onState('waiting', delay);130 window.clearTimeout(this.retryTimer);131 this.retryTimer = window.setTimeout(() => { if (!this.stopped && !this.ws) this.open(); }, delay);132 }133 /** A socket that stopped answering is dropped by hand; waiting for the TCP timeout would freeze the view. */134 private drop() {135 const ws = this.ws; if (!ws) return;136 this.ws = null; this.pending = null;137 ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;138 try { ws.close(); } catch { /* */ }139 this.h.onProblem('no_pong');140 this.schedule();141 }142143 /** Every 5 s while the tab is visible: keeps the control lease alive and measures the round trip. */144 private ping = () => {145 if (document.hidden || !this.isOpen) return;146 const now = performance.now();147 if (now - this.lastPong > PONG_TIMEOUT_MS) return this.drop();148 this.send({ t: 'ping', n: now });149 };150 private onVisibility = () => { if (!document.hidden && this.isOpen) { this.lastPong = performance.now(); this.ping(); } };151152 private onText(raw: string) {153 let m: ServerMsg;154 try { m = JSON.parse(raw) as ServerMsg; } catch { this.h.onProblem('bad_json'); return; }155 if (!m || typeof m !== 'object' || typeof (m as { t?: unknown }).t !== 'string') { this.h.onProblem('bad_json'); return; }156 if (m.t === 'pong') { const now = performance.now(); this.lastPong = now; if (typeof m.n === 'number') this.h.onRtt(Math.max(0, Math.round(now - m.n))); return; }157 this.h.onMessage(m);158 }159 /** 8-byte header (uint32 BE frame number, uint16 BE width, uint16 BE height) then a JPEG. */160 private onBinary(buf: ArrayBuffer) {161 if (buf.byteLength <= 8) { this.h.onProblem('bad_frame'); return; }162 const dv = new DataView(buf);163 const w = dv.getUint16(4), hh = dv.getUint16(6);164 if (!w || !hh) { this.h.onProblem('bad_frame'); return; }165 // Only the newest undecoded frame is kept: a slow decoder skips frames instead of lagging behind reality.166 this.pending = { n: dv.getUint32(0), w, h: hh, bytes: new Uint8Array(buf, 8) };167 if (!this.decoding) void this.pump();168 }169 private async pump() {170 this.decoding = true;171 try {172 while (this.pending) {173 const f = this.pending; this.pending = null;174 const ws = this.ws;175 let bitmap: ImageBitmap;176 try { bitmap = await createImageBitmap(new Blob([f.bytes], { type: 'image/jpeg' })); }177 catch { this.h.onProblem('decode_failed'); continue; }178 if (this.stopped || this.ws !== ws) { bitmap.close(); continue; }179 try { this.h.onFrame({ n: f.n, w: f.w, h: f.h, bitmap }); } finally { bitmap.close(); }180 this.send({ t: 'ack', frame: f.n });181 }182 } finally { this.decoding = false; }183 }184}185