Skip to content

fix(realtime): share WebSocket transport and eliminate duplicate polling (#4) - #16

Merged
ayushcmd merged 1 commit into
mainfrom
fix/issue-4-websocket-lifecycle
Dec 1, 2026
Merged

ayushcmd merged 1 commit into
mainfrom
fix/issue-4-websocket-lifecycle

Conversation

@ayushcmd

@ayushcmd ayushcmd commented Dec 1, 2026 •

Copy link
Copy Markdown
Owner

Closes #4

Changes

  • Shared browser-tab price store using React useSyncExternalStore; subscribers share a socket and in-flight HTTP request. Final unsubscribe cancels timers, aborts HTTP and detaches old socket callbacks, including Strict Mode-style remounts.
  • Bounded exponential reconnect backoff with jitter, handshake and valid-data watchdogs, heartbeat reply, and one reconnect timer. A valid quote snapshot pauses fallback polling; disconnect resumes HTTP and marks existing quotes stale. Manual refresh remains available. Ignore superseded HTTP responses.
  • Validate both HTTP and WebSocket quote payloads against the issue fix(prices): Disclose simulated market data and its provenance instead of labeling it live #2 provenance contract. Derive ws/wss from the API origin unless NEXT_PUBLIC_WS_URL is explicitly set.
  • Backend broadcasts use a stable registry snapshot and parallel client delivery; writes are serialized per client with bounded timeouts and failed-client cleanup. Heartbeat on receive inactivity.
  • Add eight deterministic frontend transport tests and five backend concurrency/cleanup tests; integrate frontend tests into existing PR CI; document the transport.

Verification / limitations

  • Source changes inspected, tests added; no independent local build or live browser/network tests executed. Review PR CI (backend unittest, frontend transport tests, TypeScript, build), and verify preview navigation, throttling and offline/reconnect before merging.
  • Frontend tests exercise the same subscription lifecycle as useSyncExternalStore using fake timers/transports; they do not mount React in a real browser. Backend tests use fake sockets; production WebSocket infrastructure and multi-worker deployment behavior are not yet verified.
  • Defaults: 15s handshake, 180s valid-data timeout, 45s HTTP deadline, 60s fallback polling, 3–60s reconnect with jitter, 5s backend send deadline. These are deliberate tradeoffs; upstream refresh optimization remains perf(backend): Coalesce commodity price refreshes and bound upstream yfinance work #5.
  • Quote contract unchanged. Connection health indicates receipt of valid snapshots, not live exchange status.

Do not merge until review is complete.

Summary by CodeRabbit

  • New Features
    • Price updates now use a shared real-time connection, with automatic reconnection and refresh when the connection is unavailable.
    • WebSocket addresses now follow the configured API address unless a separate WebSocket address is provided.
  • Bug Fixes
    • Slow or disconnected clients are less likely to interrupt price updates for others.
    • Invalid or outdated price data is handled more carefully, helping preserve clear stale-data status.
  • Documentation
    • Added guidance on real-time price transport behavior and its limitations.

@vercel

vercel Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
commoditychain Ready Ready Preview Dec 1, 2026 1:15pm UTC

@netlify

netlify Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for commoditychain ready!

Name Link
🔨 Latest commit eedd89c
🔍 Latest deploy log https://app.netlify.com/projects/commoditychain/deploys/6b0ec84251364c5ef5d24bc7
😎 Deploy Preview https://deploy-preview-16--commoditychain.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

Walkthrough

The PR centralizes frontend price transport in a shared connection manager, validates HTTP and WebSocket snapshots, and coordinates polling, reconnects, and timeouts. It also serializes backend WebSocket writes, adds realtime tests, runs them in the workflow, and documents transport behavior.

Changes: Realtime price transport

Layer / File(s) Summary
Price snapshot and transport contract
frontend/src/lib/priceConnection.ts, frontend/src/lib/api.ts, frontend/src/lib/constants.ts, frontend/tests/priceConnection.test.cjs
The frontend adds shared snapshot validation and transport deadlines. Price requests accept an abort signal, and the WebSocket URL fallback derives from the REST API URL. Tests cover accepted and rejected snapshots.
Frontend connection lifecycle
frontend/src/lib/priceConnection.ts, frontend/tests/priceConnection.test.cjs
The connection manager coordinates HTTP fallback, socket health, reconnects, subscriptions, cleanup, and refresh. Tests cover shared connections, polling, timeouts, and reconnect behavior.
Backend WebSocket delivery
backend/routers/websocket.py, backend/tests/test_websocket.py
The backend serializes writes per client and broadcasts concurrently to a snapshot of connected clients. The route uses the manager for initial prices and heartbeats. Tests cover failed and slow clients, serialized writes, and disconnect cleanup.
Hook integration and realtime checks
frontend/src/hooks/usePrices.ts, frontend/package.json, .github/workflows/price-provenance.yml, docs/realtime-transport.md
The hook reads and refreshes the shared connection snapshot. The frontend test script is added to the workflow, and the transport documentation describes the browser and backend behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant usePrices
  participant priceConnection
  participant api.getPrices
  participant PricesWebSocket as WebSocket /ws/prices
  usePrices->>priceConnection: subscribe
  priceConnection->>api.getPrices: request price snapshot
  priceConnection->>PricesWebSocket: open connection
  PricesWebSocket-->>priceConnection: send price snapshot
  priceConnection->>priceConnection: validate and publish snapshot
  priceConnection-->>usePrices: provide external-store snapshot
Loading

Possibly related issues

  • Issue 2: The PR validates HTTP and WebSocket price payloads against provenance fields, but it does not add the dashboard warnings or exports described in that issue.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@ayushcmd
ayushcmd merged commit e608bb5 into main Dec 1, 2026
8 of 9 checks passed

This branch was successfully deployed

1 active deployment
Preview — eedd89c1 Deployed Dec 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(websocket): Stop reconnecting after unmount and coordinate polling with socket state

1 participant