diff --git a/.github/workflows/price-provenance.yml b/.github/workflows/price-provenance.yml index 93d8ff3..46d1b7f 100644 --- a/.github/workflows/price-provenance.yml +++ b/.github/workflows/price-provenance.yml @@ -38,5 +38,6 @@ jobs: cache: npm cache-dependency-path: frontend/package-lock.json - run: npm ci + - run: npm run test:realtime - run: npm run type-check - run: npm run build diff --git a/backend/routers/websocket.py b/backend/routers/websocket.py index 72f895a..8b5cc7b 100644 --- a/backend/routers/websocket.py +++ b/backend/routers/websocket.py @@ -1,37 +1,63 @@ import asyncio import json import logging + from fastapi import APIRouter, WebSocket, WebSocketDisconnect from services.commodity_service import get_all_prices logger = logging.getLogger(__name__) router = APIRouter(tags=["websocket"]) -BROADCAST_INTERVAL = 60 # seconds +BROADCAST_INTERVAL = 60 +HEARTBEAT_INTERVAL = 30 +SEND_TIMEOUT = 5 +CLOSE_TIMEOUT = 2 class ConnectionManager: def __init__(self): - self._clients: set[WebSocket] = set() + self._clients: dict[WebSocket, asyncio.Lock] = {} async def connect(self, ws: WebSocket): await ws.accept() - self._clients.add(ws) - logger.info("WS client connected — total: %d", len(self._clients)) + self._clients[ws] = asyncio.Lock() + logger.info("WS client connected — total: %d", self.count) def disconnect(self, ws: WebSocket): - self._clients.discard(ws) - logger.info("WS client disconnected — total: %d", len(self._clients)) + self._clients.pop(ws, None) + logger.info("WS client disconnected — total: %d", self.count) - async def broadcast(self, payload: str): - dead: set[WebSocket] = set() - for ws in self._clients: - try: + async def _close_failed(self, ws: WebSocket): + self.disconnect(ws) + try: + await asyncio.wait_for(ws.close(code=1011), timeout=CLOSE_TIMEOUT) + except Exception: + pass + + async def send(self, ws: WebSocket, payload: str) -> bool: + lock = self._clients.get(ws) + if lock is None: + return False + # All writes for a client (initial quote, broadcast, heartbeat) are serialized. + # Bound lock acquisition plus network send, not just the network call. + async def deliver(): + async with lock: + if self._clients.get(ws) is not lock: + return False await ws.send_text(payload) - except Exception: - dead.add(ws) - for ws in dead: - self._clients.discard(ws) + return True + + try: + return await asyncio.wait_for(deliver(), timeout=SEND_TIMEOUT) + except Exception: + await self._close_failed(ws) + return False + + async def broadcast(self, payload: str): + # Snapshot the mutable registry before awaiting. Slow clients do not + # prevent healthy clients from receiving their update. + clients = tuple(self._clients) + await asyncio.gather(*(self.send(ws, payload) for ws in clients)) @property def count(self) -> int: @@ -41,39 +67,39 @@ def count(self) -> int: manager = ConnectionManager() +def _serialize(commodities) -> str: + return json.dumps([c.model_dump() for c in commodities], allow_nan=False) + + async def _broadcast_loop(): - """Background task: fetch prices and push to all WS clients every 60s.""" while True: await asyncio.sleep(BROADCAST_INTERVAL) - if manager.count == 0: + if not manager.count: continue try: - commodities = await get_all_prices() - payload = json.dumps([c.model_dump() for c in commodities]) - await manager.broadcast(payload) + await manager.broadcast(_serialize(await get_all_prices())) logger.debug("Broadcast sent to %d clients", manager.count) except Exception as exc: - logger.error("Broadcast error: %s", exc) + logger.warning("Broadcast failed: %s", type(exc).__name__) @router.websocket("/ws/prices") async def ws_prices(websocket: WebSocket): await manager.connect(websocket) try: - # Send current data immediately on connect - commodities = await get_all_prices() - payload = json.dumps([c.model_dump() for c in commodities]) - await websocket.send_text(payload) - - # Keep connection alive, waiting for disconnect + if not await manager.send(websocket, _serialize(await get_all_prices())): + return while True: try: - await asyncio.wait_for(websocket.receive_text(), timeout=120) + # Client pong or other messages never alter the price snapshot. + await asyncio.wait_for(websocket.receive_text(), timeout=HEARTBEAT_INTERVAL) except asyncio.TimeoutError: - await websocket.send_text('{"ping":true}') + if not await manager.send(websocket, '{"ping":true}'): + break except WebSocketDisconnect: pass except Exception as exc: - logger.warning("WS error: %s", exc) + logger.warning("WS error: %s", type(exc).__name__) + await manager._close_failed(websocket) finally: manager.disconnect(websocket) diff --git a/backend/tests/test_websocket.py b/backend/tests/test_websocket.py new file mode 100644 index 0000000..a77eb67 --- /dev/null +++ b/backend/tests/test_websocket.py @@ -0,0 +1,111 @@ +import asyncio +import json +import unittest +from unittest.mock import AsyncMock, patch + +from fastapi import WebSocketDisconnect +from routers import websocket as ws_router + + +class FakeSocket: + def __init__(self, blocked=False, broken=False): + self.messages = [] + self.accepted = False + self.closed = False + self.entered = asyncio.Event() + self.release = asyncio.Event() + self.blocked = blocked + self.broken = broken + self.sending = False + + async def accept(self): + self.accepted = True + + async def send_text(self, payload): + if self.sending: + raise AssertionError("overlapping sends") + self.sending = True + try: + self.entered.set() + if self.broken: + raise RuntimeError("disconnected") + if self.blocked: + await self.release.wait() + self.messages.append(payload) + finally: + self.sending = False + + async def close(self, code=1000): + self.closed = True + + async def receive_text(self): + raise WebSocketDisconnect(code=1000) + + +class BroadcastTests(unittest.IsolatedAsyncioTestCase): + async def test_registry_changes_during_broadcast(self): + manager = ws_router.ConnectionManager() + first, joined = FakeSocket(blocked=True), FakeSocket() + await manager.connect(first) + task = asyncio.create_task(manager.broadcast("snapshot")) + await first.entered.wait() + await manager.connect(joined) + manager.disconnect(first) + first.release.set() + await task + self.assertEqual(manager.count, 1) + self.assertEqual(joined.messages, []) + await manager.broadcast("next") + self.assertEqual(joined.messages, ["next"]) + + async def test_slow_client_does_not_block_healthy_client(self): + manager = ws_router.ConnectionManager() + slow, fast = FakeSocket(blocked=True), FakeSocket() + await manager.connect(slow) + await manager.connect(fast) + with patch.object(ws_router, "SEND_TIMEOUT", .1): + task = asyncio.create_task(manager.broadcast("snapshot")) + await asyncio.wait_for(fast.entered.wait(), timeout=.05) + self.assertEqual(fast.messages, ["snapshot"]) + await task + self.assertTrue(slow.closed) + self.assertEqual(manager.count, 1) + + async def test_failed_client_removed_and_others_continue(self): + manager = ws_router.ConnectionManager() + bad, good = FakeSocket(broken=True), FakeSocket() + await manager.connect(bad) + await manager.connect(good) + await manager.broadcast("one") + await manager.broadcast("two") + self.assertEqual(good.messages, ["one", "two"]) + self.assertTrue(bad.closed) + self.assertEqual(manager.count, 1) + + async def test_initial_heartbeat_and_broadcast_writes_are_serialized(self): + manager = ws_router.ConnectionManager() + client = FakeSocket(blocked=True) + await manager.connect(client) + first = asyncio.create_task(manager.send(client, "initial")) + await client.entered.wait() + second = asyncio.create_task(manager.broadcast("broadcast")) + await asyncio.sleep(0) + third = asyncio.create_task(manager.send(client, '{"ping":true}')) + client.release.set() + await asyncio.gather(first, second, third) + self.assertEqual(len(client.messages), 3) + self.assertEqual(client.messages[0], "initial") + self.assertIn("broadcast", client.messages) + self.assertIn('{"ping":true}', client.messages) + self.assertFalse(client.closed) + + async def test_route_cleans_up_on_disconnect(self): + manager = ws_router.ConnectionManager() + client = FakeSocket() + with patch.object(ws_router, "manager", manager), patch.object( + ws_router, "get_all_prices", new=AsyncMock(return_value=[]) + ): + await ws_router.ws_prices(client) + self.assertTrue(client.accepted) + self.assertEqual(json.loads(client.messages[0]), []) + self.assertEqual(manager.count, 0) diff --git a/docs/realtime-transport.md b/docs/realtime-transport.md new file mode 100644 index 0000000..74229e7 --- /dev/null +++ b/docs/realtime-transport.md @@ -0,0 +1,11 @@ +# Shared price transport + +The browser now uses one module-scoped price store per tab. All mounted usePrices consumers subscribe through React useSyncExternalStore. First subscriber starts HTTP bootstrap and one socket; last unsubscribe cancels pending requests/timers and detaches/closes the socket. A subsequent mount starts a new generation; obsolete callbacks are ignored. + +- HTTP fallback polls every 60 seconds after completion when socket data is unavailable, with one in-flight request and a 45-second deadline. A manual refresh can request HTTP even when healthy; a valid socket snapshot supersedes it. +- A socket handshake alone is not healthy. The first valid quote snapshot pauses polling and resets exponential backoff (3 seconds base, doubled to 60 seconds, with 20% jitter and hard cap). +- Handshake deadline: 15 seconds. Price-data deadline: 180 seconds, allowing for the 60-second broadcast and slower upstream refresh. Heartbeats do not reset the price-data deadline. Invalid/legacy/simulated payloads are rejected on both transports. Disconnects mark existing provider data stale until refreshed. +- Backend broadcasts snapshot the registry and send concurrently across clients, serially within each client. Each send (including lock acquisition) has a 5-second deadline; failed clients are removed and closed with bounded cleanup. The server emits application heartbeats on 30 seconds of receive inactivity. +- No change to the quote API contract. Cache and socket registry remain process-local. Upstream refresh performance is separately tracked in #5. Browser tab background timer throttling, real network transitions and multi-worker deployment behavior need live testing. + +Tests: `cd frontend && npm run test:realtime` (deterministic fake clock, socket and HTTP tests; models React's subscribe/unsubscribe cycle without mounting a browser); `cd backend && python -m unittest discover -s tests -v` (fake client concurrency and cleanup tests). Both run in the existing PR workflow, alongside TypeScript and Next.js build. Actual browser navigation and network interruption still need preview validation. diff --git a/frontend/package.json b/frontend/package.json index 9f5b122..ab5958c 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -7,7 +7,8 @@ "build": "next build", "start": "next start", "lint": "next lint", - "type-check": "tsc --noEmit" + "type-check": "tsc --noEmit", + "test:realtime": "node --test tests/priceConnection.test.cjs" }, "dependencies": { "d3-geo": "^3.1.1", diff --git a/frontend/src/hooks/usePrices.ts b/frontend/src/hooks/usePrices.ts index 0a63996..938ce3e 100644 --- a/frontend/src/hooks/usePrices.ts +++ b/frontend/src/hooks/usePrices.ts @@ -1,9 +1,18 @@ "use client"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useMemo, useSyncExternalStore } from "react"; import { Commodity, CommodityQuote } from "@/types"; import { api } from "@/lib/api"; import { POLL_INTERVAL_MS, WS_BASE_URL, WS_RECONNECT_DELAY_MS } from "@/lib/constants"; +import { createPriceConnection } from "@/lib/priceConnection"; + +// Module singleton: one transport for all mounted consumers in this browser tab. +const connection = createPriceConnection({ + socket: () => new WebSocket(`${WS_BASE_URL.replace(/\/$/, "")}/ws/prices`), + fetch: signal => api.getPrices(signal), + pollMs: POLL_INTERVAL_MS, + reconnectMs: WS_RECONNECT_DELAY_MS, +}); interface UsePricesReturn { commodities: Commodity[]; @@ -17,95 +26,9 @@ interface UsePricesReturn { } export function usePrices(): UsePricesReturn { - const [records, setRecords] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [isConnected, setIsConnected] = useState(false); - - const wsRef = useRef(null); - const pollRef = useRef(null); - const reconnectRef = useRef(null); - - const acceptPrices = useCallback((data: CommodityQuote[]) => { - // Fail closed for an older API or unmarked simulated data. - setRecords(data.map(c => { - if (c.source !== "yahoo_finance" || !c.sourceTimestamp || c.isSimulated !== false || - !["provider", "stale"].includes(c.dataStatus) || !Number.isFinite(Date.parse(c.sourceTimestamp))) { - return { ...c, price: null, previousClose: null, change: null, changePercent: null, - high24h: null, low24h: null, volume: null, history: [], marketStatus: "unknown", - source: null, sourceTimestamp: null, fetchedAt: null, lastUpdated: null, - dataStatus: "unavailable", isStale: false, isSimulated: false }; - } - if (Date.now() - Date.parse(c.sourceTimestamp) > 30 * 60 * 1000) - return { ...c, dataStatus: "stale", isStale: true }; - return c; - })); - setError(null); - setLoading(false); - }, []); - - const fetchPrices = useCallback(async () => { - try { - const data = await api.getPrices(); - acceptPrices(data); - } catch (err) { - setError("Failed to fetch prices. Showing last-known data if available."); - setRecords(old => old.map(c => c.dataStatus === "unavailable" ? c : { ...c, dataStatus: "stale", isStale: true })); - console.error(err); - } finally { - setLoading(false); - } - }, [acceptPrices]); - - const connectWS = useCallback(() => { - if (wsRef.current?.readyState === WebSocket.OPEN) return; - - try { - const ws = new WebSocket(`${WS_BASE_URL}/ws/prices`); - wsRef.current = ws; - - ws.onopen = () => { - setIsConnected(true); - if (reconnectRef.current) clearTimeout(reconnectRef.current); - }; - - ws.onmessage = (event) => { - try { - const parsed = JSON.parse(event.data); - // Ignore keepalive ping messages - if (!Array.isArray(parsed)) return; - acceptPrices(parsed as CommodityQuote[]); - } catch { - console.warn("WS parse error", event.data); - } - }; - - ws.onerror = () => { - setIsConnected(false); - }; - - ws.onclose = () => { - setIsConnected(false); - reconnectRef.current = setTimeout(connectWS, WS_RECONNECT_DELAY_MS); - }; - } catch { - setIsConnected(false); - reconnectRef.current = setTimeout(connectWS, WS_RECONNECT_DELAY_MS); - } - }, [acceptPrices]); - - useEffect(() => { - fetchPrices(); - connectWS(); - - pollRef.current = setInterval(fetchPrices, POLL_INTERVAL_MS); - - return () => { - if (pollRef.current) clearInterval(pollRef.current); - if (reconnectRef.current) clearTimeout(reconnectRef.current); - wsRef.current?.close(); - }; - }, [fetchPrices, connectWS]); + const { records, loading, error, isConnected } = useSyncExternalStore( + connection.subscribe, connection.getSnapshot, connection.getServerSnapshot, + ); const commodities = useMemo(() => records.filter((c): c is Commodity => c.dataStatus !== "unavailable" && [c.price, c.previousClose, c.change, c.changePercent] @@ -129,6 +52,6 @@ export function usePrices(): UsePricesReturn { error, lastUpdated, isConnected, - refresh: fetchPrices, + refresh: connection.refresh, }; } \ No newline at end of file diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 73f7f8c..bc0d947 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -47,7 +47,7 @@ function parseNewsFeed(value: unknown, commodity: string): NewsFeed { } export const api = { - getPrices: () => get("/api/prices"), + getPrices: (signal?: AbortSignal) => get("/api/prices", signal), getCommodity: (id: string) => get(`/api/prices/${id}`), getTicker: () => get[]>("/api/ticker"), getNews: async (commodity = "all", signal?: AbortSignal) => diff --git a/frontend/src/lib/constants.ts b/frontend/src/lib/constants.ts index fd1dede..b8a9942 100644 --- a/frontend/src/lib/constants.ts +++ b/frontend/src/lib/constants.ts @@ -83,4 +83,5 @@ export const CATEGORY_LABELS: Record = { export const POLL_INTERVAL_MS = 60_000; export const WS_RECONNECT_DELAY_MS = 3_000; export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000"; -export const WS_BASE_URL = process.env.NEXT_PUBLIC_WS_URL ?? "ws://localhost:8000"; +// Derive the socket origin from the REST origin unless an explicit override is configured. +export const WS_BASE_URL = process.env.NEXT_PUBLIC_WS_URL ?? API_BASE_URL.replace(/^http/i, "ws"); diff --git a/frontend/src/lib/priceConnection.ts b/frontend/src/lib/priceConnection.ts new file mode 100644 index 0000000..ced7ee0 --- /dev/null +++ b/frontend/src/lib/priceConnection.ts @@ -0,0 +1,267 @@ +import type { CommodityQuote } from "../types"; + +export interface PriceSnapshot { + records: CommodityQuote[]; + loading: boolean; + error: string | null; + isConnected: boolean; +} + +export const INITIAL_PRICE_SNAPSHOT: PriceSnapshot = { + records: [], loading: true, error: null, isConnected: false, +}; + +type Timer = ReturnType; +interface Options { + socket: () => WebSocket; + fetch: (signal: AbortSignal) => Promise; + pollMs: number; + reconnectMs: number; + random?: () => number; + now?: () => number; + setTimer?: (callback: () => void, ms: number) => Timer; + clearTimer?: (timer: Timer) => void; +} + +const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); +const date = (v: unknown): v is string => typeof v === "string" && Number.isFinite(Date.parse(v)); +const nullableNumber = (v: unknown) => v === null || finite(v); +const numericFields = ["price", "previousClose", "change", "changePercent", "high24h", "low24h", "volume"]; + +// Both transports must pass the same validation. No legacy, unmarked or synthetic quotes. +export function parsePriceSnapshot(value: unknown, now = Date.now()): CommodityQuote[] | null { + if (!Array.isArray(value) || !value.length) return null; + const ids = new Set(); + const records: CommodityQuote[] = []; + for (const raw of value) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const c = raw as Record; + if (typeof c.id !== "string" || !c.id || ids.has(c.id) || + !["name", "ticker", "unit", "currency"].every(k => typeof c[k] === "string" && c[k]) || + !["energy", "metals", "agriculture", "other"].includes(String(c.category)) || + !["open", "closed", "pre-market", "unknown"].includes(String(c.marketStatus)) || + !numericFields.every(k => nullableNumber(c[k])) || + !Array.isArray(c.history) || !c.history.every(p => p && typeof p === "object" && + date(p.timestamp) && finite(p.price)) || + c.isSimulated !== false || typeof c.isStale !== "boolean") return null; + if (c.dataStatus === "unavailable") { + if (c.source !== null || c.sourceTimestamp !== null || c.fetchedAt !== null || + c.lastUpdated !== null || c.isStale || c.history.length || + !numericFields.every(k => c[k] === null)) return null; + } else { + if ((c.dataStatus !== "provider" && c.dataStatus !== "stale") || + c.source !== "yahoo_finance" || !date(c.sourceTimestamp) || !date(c.fetchedAt) || + c.lastUpdated !== c.sourceTimestamp || !finite(c.price) || + Date.parse(c.sourceTimestamp) > now + 5 * 60_000 || + Date.parse(c.fetchedAt) > now + 5 * 60_000 || + c.isStale !== (c.dataStatus === "stale")) return null; + } + ids.add(c.id); + const q = raw as CommodityQuote; + records.push(q.sourceTimestamp && now - Date.parse(q.sourceTimestamp) > 30 * 60_000 + ? { ...q, dataStatus: "stale", isStale: true } : q); + } + return records; +} + +const MAX_RECONNECT_MS = 60_000; +const HANDSHAKE_MS = 15_000; +// Quotes are broadcast every 60s; a slow upstream refresh can take longer. +const DATA_DEADLINE_MS = 180_000; +const HTTP_DEADLINE_MS = 45_000; + +export function createPriceConnection(options: Options) { + const schedule = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms)); + const clear = options.clearTimer ?? (timer => clearTimeout(timer)); + const now = options.now ?? Date.now; + const random = options.random ?? Math.random; + const listeners = new Set<() => void>(); + let snapshot = INITIAL_PRICE_SNAPSHOT; + let active = false; + let socket: WebSocket | null = null; + let healthy = false; + let attempt = 0; + let reconnect: Timer | undefined; + let poll: Timer | undefined; + let watchdog: Timer | undefined; + let httpDeadline: Timer | undefined; + let request: AbortController | null = null; + + function publish(next: Partial) { + snapshot = { ...snapshot, ...next }; + for (const listener of [...listeners]) listener(); + } + + function clearPoll() { + if (poll !== undefined) clear(poll); + poll = undefined; + } + + function clearWatchdog() { + if (watchdog !== undefined) clear(watchdog); + watchdog = undefined; + } + + function cancelRequest() { + const current = request; + request = null; + if (httpDeadline !== undefined) clear(httpDeadline); + httpDeadline = undefined; + current?.abort(); + } + + function schedulePoll() { + clearPoll(); + if (active && !healthy) poll = schedule(() => { + poll = undefined; + void fetchPrices(); + }, options.pollMs); + } + + function markFailure() { + publish({ loading: false, error: "Failed to fetch prices. Showing last-known data if available.", + records: snapshot.records.map(c => c.dataStatus === "unavailable" ? c + : { ...c, dataStatus: "stale", isStale: true }) }); + } + + function accept(records: CommodityQuote[]) { + publish({ records, loading: false, error: null, isConnected: healthy }); + } + + async function fetchPrices() { + if (!active || request) return; + clearPoll(); + const controller = new AbortController(); + request = controller; + httpDeadline = schedule(() => { + if (request !== controller) return; + cancelRequest(); + if (!healthy) markFailure(); + schedulePoll(); + }, HTTP_DEADLINE_MS); + try { + const value = await options.fetch(controller.signal); + if (!active || request !== controller) return; + const records = parsePriceSnapshot(value, now()); + if (!records) throw new Error("Invalid price response"); + accept(records); + } catch { + if (active && request === controller && !healthy) markFailure(); + } finally { + if (request === controller) { + cancelRequest(); + schedulePoll(); + } + } + } + + function disposeSocket() { + clearWatchdog(); + const current = socket; + socket = null; + healthy = false; + if (current) { + current.onopen = current.onmessage = current.onerror = current.onclose = null; + try { current.close(); } catch { /* already closing */ } + } + } + + function scheduleReconnect() { + if (!active || reconnect !== undefined) return; + const base = Math.min(MAX_RECONNECT_MS, options.reconnectMs * 2 ** Math.min(attempt++, 10)); + const delay = Math.min(MAX_RECONNECT_MS, Math.round(base * (0.8 + random() * 0.4))); + reconnect = schedule(() => { + reconnect = undefined; + connect(); + }, delay); + } + + function disconnected(current?: WebSocket) { + if (!active || (current && socket !== current)) return; + const wasHealthy = healthy; + disposeSocket(); + publish({ isConnected: false, + ...(wasHealthy ? { records: snapshot.records.map(c => c.dataStatus === "unavailable" ? c : + { ...c, dataStatus: "stale" as const, isStale: true }) } : {}) }); + void fetchPrices(); + scheduleReconnect(); + } + + function armWatchdog(current: WebSocket, ms: number) { + clearWatchdog(); + watchdog = schedule(() => { + watchdog = undefined; + disconnected(current); + }, ms); + } + + function connect() { + if (!active || socket) return; + try { + const current = options.socket(); + socket = current; + armWatchdog(current, HANDSHAKE_MS); + current.onopen = () => { + if (!active || socket !== current) return; + // A handshake is not proof of valid price data. + armWatchdog(current, DATA_DEADLINE_MS); + }; + current.onmessage = event => { + if (!active || socket !== current || typeof event.data !== "string") return; + let value: unknown; + try { value = JSON.parse(event.data); } catch { return; } + if (value && typeof value === "object" && !Array.isArray(value) && + (value as { ping?: unknown }).ping === true) { + try { current.send('{"pong":true}'); } catch { disconnected(current); } + // Heartbeats do not extend the price-data deadline. + return; + } + const records = parsePriceSnapshot(value, now()); + if (!records) return; + healthy = true; + attempt = 0; + clearPoll(); + cancelRequest(); // a late HTTP response cannot overwrite this socket snapshot + armWatchdog(current, DATA_DEADLINE_MS); + accept(records); + }; + current.onerror = () => disconnected(current); + current.onclose = () => disconnected(current); + } catch { + disconnected(); + } + } + + function stop() { + active = false; + if (reconnect !== undefined) clear(reconnect); + reconnect = undefined; + clearPoll(); + cancelRequest(); + disposeSocket(); + attempt = 0; + snapshot = INITIAL_PRICE_SNAPSHOT; + } + + function subscribe(listener: () => void) { + // Wrap each subscriber to make each unsubscribe independent. + const subscription = () => listener(); + listeners.add(subscription); + if (!active) { + active = true; + void fetchPrices(); + connect(); + } + return () => { + listeners.delete(subscription); + if (!listeners.size && active) stop(); + }; + } + + return { + subscribe, + getSnapshot: () => snapshot, + getServerSnapshot: () => INITIAL_PRICE_SNAPSHOT, + refresh: () => { void fetchPrices(); }, + }; +} diff --git a/frontend/tests/priceConnection.test.cjs b/frontend/tests/priceConnection.test.cjs new file mode 100644 index 0000000..e4ae726 --- /dev/null +++ b/frontend/tests/priceConnection.test.cjs @@ -0,0 +1,156 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const ts = require("typescript"); + +// Compile this dependency-free transport module with the existing TypeScript dependency. +const file = path.join(__dirname, "../src/lib/priceConnection.ts"); +const compiled = ts.transpileModule(fs.readFileSync(file, "utf8"), { + compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.CommonJS }, +}).outputText; +const mod = { exports: {} }; +new Function("module", "exports", compiled)(mod, mod.exports); +const { createPriceConnection, parsePriceSnapshot } = mod.exports; + +const NOW = Date.parse("2026-01-10T12:00:00Z"); +function quote(overrides = {}) { + return { id: "gold", name: "Gold", ticker: "GC=F", unit: "per troy oz", + category: "metals", currency: "USD", price: 100, previousClose: 99, + change: 1, changePercent: 1, high24h: 102, low24h: 98, volume: null, + marketStatus: "unknown", lastUpdated: new Date(NOW).toISOString(), + source: "yahoo_finance", sourceTimestamp: new Date(NOW).toISOString(), + fetchedAt: new Date(NOW).toISOString(), dataStatus: "provider", isStale: false, + isSimulated: false, history: [{ timestamp: "2026-01-09", price: 99 }], ...overrides }; +} + +function harness() { + let clock = 0, seq = 0; + const timers = new Map(), sockets = [], requests = []; + function tick(ms) { + const target = clock + ms; + for (;;) { + const next = [...timers.entries()].filter(([, t]) => t.at <= target) + .sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0]; + if (!next) break; + timers.delete(next[0]); clock = next[1].at; next[1].fn(); + } + clock = target; + } + function socket() { + const ws = { + closed: false, sent: [], onopen: null, onmessage: null, onerror: null, onclose: null, + close() { this.closed = true; this.onclose?.(); }, + send(data) { this.sent.push(data); }, + open() { this.onopen?.(); }, + message(data) { this.onmessage?.({ data: typeof data === "string" ? data : JSON.stringify(data) }); }, + fail() { this.onerror?.(); this.onclose?.(); }, + }; + sockets.push(ws); return ws; + } + const store = createPriceConnection({ + socket, fetch: signal => new Promise((resolve, reject) => requests.push({ signal, resolve, reject })), + pollMs: 60000, reconnectMs: 3000, random: () => .5, now: () => NOW + clock, + setTimer: (fn, ms) => { const id = ++seq; timers.set(id, { fn, at: clock + ms }); return id; }, + clearTimer: id => timers.delete(id), + }); + return { store, timers, sockets, requests, tick }; +} +const flush = async () => { await Promise.resolve(); await Promise.resolve(); }; + +test("subscribers share one transport; final cleanup cancels timers and requests", async () => { + const h = harness(); + const a = h.store.subscribe(() => {}), b = h.store.subscribe(() => {}); + assert.equal(h.sockets.length, 1); assert.equal(h.requests.length, 1); + a(); assert.equal(h.sockets[0].closed, false); + const lateClose = h.sockets[0].onclose; + b(); assert.equal(h.sockets[0].closed, true); + assert.equal(h.requests[0].signal.aborted, true); assert.equal(h.timers.size, 0); + lateClose(); h.tick(180000); assert.equal(h.sockets.length, 1); +}); + +test("Strict Mode-style unsubscribe/remount ignores old socket and HTTP callbacks", async () => { + const h = harness(); + const off = h.store.subscribe(() => {}); + const lateMessage = h.sockets[0].onmessage, lateClose = h.sockets[0].onclose; + off(); const again = h.store.subscribe(() => {}); + assert.equal(h.sockets.length, 2); assert.equal(h.requests.length, 2); + lateMessage({ data: JSON.stringify([quote({ price: 999 })]) }); lateClose(); + h.requests[0].resolve([quote({ price: 999 })]); await flush(); + assert.equal(h.store.getSnapshot().records.length, 0); + h.sockets[1].open(); h.sockets[1].message([quote()]); + assert.equal(h.store.getSnapshot().records[0].price, 100); + assert.equal(h.requests[1].signal.aborted, true); again(); +}); + +test("valid data pauses polling, ignores late HTTP results, and responds to heartbeat", async () => { + const h = harness(), off = h.store.subscribe(() => {}); + const ws = h.sockets[0]; ws.open(); + assert.equal(h.store.getSnapshot().isConnected, false); + ws.message([quote()]); assert.equal(h.store.getSnapshot().isConnected, true); + assert.equal(h.requests[0].signal.aborted, true); + h.requests[0].resolve([quote({ price: 999 })]); await flush(); + assert.equal(h.store.getSnapshot().records[0].price, 100); + ws.message({ ping: true }); assert.deepEqual(ws.sent, ['{"pong":true}']); + h.tick(120000); assert.equal(h.requests.length, 1); + off(); +}); + +test("socket outage resumes polling and reconnects; valid recovery pauses polling again", async () => { + const h = harness(), off = h.store.subscribe(() => {}); + h.sockets[0].open(); h.sockets[0].message([quote()]); h.sockets[0].fail(); + assert.equal(h.store.getSnapshot().isConnected, false); + assert.equal(h.store.getSnapshot().records[0].isStale, true); + assert.equal(h.requests.length, 2); + h.requests[1].resolve([quote({ price: 101 })]); await flush(); + assert.equal(h.store.getSnapshot().records[0].price, 101); + h.tick(3000); assert.equal(h.sockets.length, 2); + h.sockets[1].open(); h.sockets[1].message([quote({ price: 102 })]); + h.tick(60000); assert.equal(h.requests.length, 2); + assert.equal(h.store.getSnapshot().isConnected, true); off(); +}); + +test("reconnect backoff increases, caps at 60s and resets after valid data", () => { + const h = harness(), off = h.store.subscribe(() => {}); + for (const delay of [3000, 6000, 12000, 24000, 48000, 60000, 60000]) { + const count = h.sockets.length; h.sockets.at(-1).fail(); + h.tick(delay - 1); assert.equal(h.sockets.length, count); + h.tick(1); assert.equal(h.sockets.length, count + 1); + } + h.sockets.at(-1).open(); h.sockets.at(-1).message([quote()]); + const count = h.sockets.length; h.sockets.at(-1).fail(); h.tick(3000); + assert.equal(h.sockets.length, count + 1); off(); +}); + +test("invalid data and heartbeat cannot keep a silent price connection healthy", () => { + const h = harness(), off = h.store.subscribe(() => {}); + const ws = h.sockets[0]; ws.open(); ws.message([quote()]); + h.tick(90000); ws.message({ ping: true }); ws.message([quote({ isSimulated: true })]); + ws.message("not JSON"); h.tick(90000); + assert.equal(ws.closed, true); assert.equal(h.store.getSnapshot().isConnected, false); + assert.equal(h.requests.length, 2); off(); +}); + +test("handshake and HTTP deadlines abort hung operations; manual refresh is coalesced", () => { + const h = harness(), off = h.store.subscribe(() => {}); + h.store.refresh(); h.store.refresh(); assert.equal(h.requests.length, 1); + h.tick(15000); assert.equal(h.sockets[0].closed, true); + h.tick(30000); assert.equal(h.requests[0].signal.aborted, true); + assert.equal(h.store.getSnapshot().loading, false); + assert.ok(h.store.getSnapshot().error); off(); +}); + +test("validator rejects malformed or legacy data and keeps explicit unavailable and stale states", () => { + assert.equal(parsePriceSnapshot([null], NOW), null); + assert.equal(parsePriceSnapshot([quote({ source: undefined })], NOW), null); + assert.equal(parsePriceSnapshot([quote({ history: [null] })], NOW), null); + assert.equal(parsePriceSnapshot([quote(), quote()], NOW), null); + assert.equal(parsePriceSnapshot([quote({ price: Infinity })], NOW), null); + assert.equal(parsePriceSnapshot([quote({ isSimulated: true })], NOW), null); + const older = new Date(NOW - 3600000).toISOString(); + assert.equal(parsePriceSnapshot([quote({ lastUpdated: older, sourceTimestamp: older })], NOW)[0].isStale, true); + const unavailable = quote({ price: null, previousClose: null, change: null, changePercent: null, + high24h: null, low24h: null, volume: null, source: null, sourceTimestamp: null, + fetchedAt: null, lastUpdated: null, history: [], dataStatus: "unavailable" }); + assert.equal(parsePriceSnapshot([unavailable], NOW)[0].price, null); +});