Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/price-provenance.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
84 changes: 55 additions & 29 deletions backend/routers/websocket.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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)
111 changes: 111 additions & 0 deletions backend/tests/test_websocket.py
Original file line number Diff line number Diff line change
@@ -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)
11 changes: 11 additions & 0 deletions docs/realtime-transport.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading