'use strict'; /* * WebSocket push client (docs/PROTOCOL.md). Push is only a HINT: the game is fully playable with the socket down, so * every failure here is silent (no toasts, no thrown errors) and a slow REST poll runs as the fallback. * * connect to ws(s):///ws; first message {"type":"auth","token":"..."}; server answers {"type":"ready","serverTime"} * server pushes {"type":"town","townId"} {"type":"incoming","townId","arriveAt"} {"type":"notification","id","kind"} * {"type":"report","id"} {"type":"message","id"} * client pings {"type":"ping"} every ~25 s and expects {"type":"pong"} within a few seconds, else it reconnects * reconnect: exponential backoff from 1 s to 60 s with jitter, reset by a successful "ready" * * createSocketClient() is pure plumbing with everything injected (WebSocket constructor, timers, token), so * test/client-ws.test.js can drive it. The browser wiring (bind) feeds pushes into api.emit('push', msg) and refetches * the affected screens. The token is never logged and never put in the URL. */ (function (root, factory) { if (typeof module === 'object' && module.exports) module.exports = factory(require('./milcore.js')); else root.UpstreamWs = factory(root.UpstreamMil); }(typeof self !== 'undefined' ? self : this, function (Mil) { function createSocketClient(o) { const WS = o.WebSocket; const setT = o.setTimeout || setTimeout, clearT = o.clearTimeout || clearTimeout; const pingMs = o.pingMs || 25000, pongMs = o.pongTimeoutMs || 8000; const rnd = o.random || Math.random; let sock = null, state = 'idle', attempt = 0, wanted = false, hadReady = false; let retryTimer = null, pingTimer = null, pongTimer = null; function setState(s) { if (s !== state) { state = s; if (o.onState) o.onState(s); } } function clearTimers() { clearT(retryTimer); clearT(pingTimer); clearT(pongTimer); retryTimer = pingTimer = pongTimer = null; } function schedule(minWait) { if (!wanted || retryTimer) return; const wait = Math.max(minWait || 0, Mil.backoffMs(attempt, rnd())); attempt++; retryTimer = setT(() => { retryTimer = null; connect(); }, wait); } function startPing() { clearT(pingTimer); pingTimer = setT(() => { if (!sock || state !== 'open') return; try { sock.send('{"type":"ping"}'); } catch (e) { drop(); return; } clearT(pongTimer); pongTimer = setT(() => drop(), pongMs); // no pong: the connection is dead although nobody told us startPing(); }, pingMs); } function drop(minWait) { const s = sock; sock = null; clearT(pingTimer); clearT(pongTimer); pingTimer = pongTimer = null; if (s) { try { s.onopen = s.onmessage = s.onclose = s.onerror = null; s.close(); } catch (e) { /* already gone */ } } setState(wanted ? 'closed' : 'idle'); schedule(minWait); } // Close codes of docs/PROTOCOL.md: 4401 (token refused), 4400 and 1009 (a client bug) must not be retried in a loop; // 4429 (rate limited) waits at least 30 s; everything else is a plain reconnect. function onClosed(ev) { const code = ev && ev.code; if (code === 4401 || code === 4400 || code === 1009) { wanted = false; clearTimers(); sock = null; setState('idle'); if (o.onFatal) o.onFatal(code); return; } drop(code === 4429 ? 30000 : 0); } function connect() { if (!wanted || sock) return; const token = o.token(); if (!token || !WS) return; let s; try { s = new WS(o.url()); } catch (e) { setState('closed'); schedule(); return; } sock = s; setState('connecting'); s.onopen = () => { try { s.send(JSON.stringify({ type: 'auth', token })); } catch (e) { drop(); } }; s.onmessage = (ev) => { let msg = null; try { msg = JSON.parse(ev.data); } catch (e) { return; } if (!msg || typeof msg.type !== 'string') return; if (msg.type === 'ready') { attempt = 0; const again = hadReady; hadReady = true; setState('open'); startPing(); if (o.onReady) o.onReady(msg, again); return; } if (msg.type === 'pong') { clearT(pongTimer); pongTimer = null; return; } if (o.onMessage) o.onMessage(msg); }; s.onclose = (ev) => { if (sock === s) onClosed(ev); }; s.onerror = () => { /* the close event follows; stay quiet */ }; } return { start() { if (wanted) return; wanted = true; attempt = 0; hadReady = false; connect(); }, stop() { wanted = false; clearTimers(); const s = sock; sock = null; if (s) { try { s.onopen = s.onmessage = s.onclose = s.onerror = null; s.close(); } catch (e) { /* ignore */ } } setState('idle'); }, // Try now (back online, tab visible again): skips the backoff wait. kick() { if (!wanted || sock) return; clearT(retryTimer); retryTimer = null; attempt = 0; connect(); }, get state() { return state; }, get open() { return state === 'open'; }, get attempts() { return attempt; }, }; } // ------------------------------------------------------------------ browser wiring function bind(App, UI, windowRef) { const api = App.api; const wsUrl = () => (windowRef.location.protocol === 'https:' ? 'wss://' : 'ws://') + windowRef.location.host + '/ws'; const client = createSocketClient({ WebSocket: windowRef.WebSocket, url: wsUrl, token: () => api.getToken(), onMessage: (msg) => api.emit('push', msg), // after every ready that follows a gap, refetch what is on screen (PROTOCOL.md): hints sent while we were away are lost onReady: (msg, again) => { poll(true); if (again && App.state.user) { App.refreshTown().catch(() => {}); App.refreshTowns().catch(() => {}); } }, onFatal: () => { /* token refused or a client bug: stay quiet, the REST layer reports a dead token itself */ }, }); App.ws = client; const timers = {}; function debounce(key, fn, ms) { clearTimeout(timers[key]); timers[key] = setTimeout(fn, ms); } // ---- what a push means for the screens (everything is a refetch over REST) api.on('push', (msg) => { if (!App.state.user) return; switch (msg.type) { case 'town': if (msg.townId === App.state.townId) debounce('town', () => App.refreshTown().catch(() => {}), 250); break; case 'incoming': debounce('moves', () => App.refreshMovements().catch(() => {}), 150); UI.toast(App.t('push.incoming'), 'error'); break; case 'report': App.refreshReportsUnread().catch(() => {}); debounce('towns', () => App.refreshTowns().catch(() => {}), 500); // a settle / takeover report changes the POP list App.emit('report', msg); break; case 'notification': App.checkAlerts(); if (msg.kind === 'town_gained' || msg.kind === 'town_lost') App.refreshTowns().catch(() => {}); if (/^(train_done|research_done|movement_returned|reinforcements_sent_home|units_offline|units_decommissioned|transport_arrived|town_gained|town_lost)$/.test(msg.kind || '')) { debounce('town', () => App.refreshTown().catch(() => {}), 400); debounce('moves', () => App.refreshMovements().catch(() => {}), 400); } break; default: break; // 'message' etc. belong to other screens (api.on('push') there) } }); // ---- REST fallback: slow when the socket is open (it only backs the hints up), faster when it is down let lastPoll = 0; function poll(force) { if (!App.state.user || windowRef.document.hidden) return; const gap = client.open ? 180000 : 45000; if (!force && Date.now() - lastPoll < gap) return; lastPoll = Date.now(); App.refreshMovements().catch(() => {}); App.refreshReportsUnread().catch(() => {}); App.refreshTowns().catch(() => {}); App.checkAlerts(); } setInterval(() => poll(false), 15000); // ---- lifecycle App.on('session', (st) => { if (st && st.user) { client.start(); poll(true); } else client.stop(); }); api.on('unauthorized', () => client.stop()); api.on('online', () => client.kick()); windowRef.document.addEventListener('visibilitychange', () => { if (!windowRef.document.hidden && App.state.user) { client.kick(); poll(false); } }); } if (typeof window !== 'undefined' && window.App && window.UI) bind(window.App, window.UI, window); return { createSocketClient, bind }; }));