-
Notifications
You must be signed in to change notification settings - Fork 415
FEDEV-3973: WebSocket price and candle streaming to the trading UI #2613
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
divhead
wants to merge
1
commit into
release
Choose a base branch
from
phase-2-ws-prices-2
base: release
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| import IsomorphicWebSocket from "isomorphic-ws"; | ||
|
|
||
| import { FrameMeta, StreamServerFrame, StreamStatus, Unsubscribe, WebSocketCtor, WebSocketLike } from "./types"; | ||
|
|
||
| const DEFAULT_RECONNECT_BASE_MS = 500; | ||
| const DEFAULT_RECONNECT_MAX_MS = 10_000; | ||
|
|
||
| export type ChannelFrame = { data: unknown } & FrameMeta; | ||
| type ChannelListener = (frame: ChannelFrame) => void; | ||
|
|
||
| function resolveWebSocketCtor(injected?: WebSocketCtor): WebSocketCtor { | ||
| return injected ?? (IsomorphicWebSocket as unknown as WebSocketCtor); | ||
| } | ||
|
|
||
| export class WsStreamClient { | ||
| status: StreamStatus = "closed"; | ||
|
|
||
| private ws?: WebSocketLike; | ||
| private readonly url: string; | ||
| private readonly WebSocketImpl: WebSocketCtor; | ||
| private readonly reconnectBaseMs: number; | ||
| private readonly reconnectMaxMs: number; | ||
| private readonly listeners = new Map<string, Set<ChannelListener>>(); | ||
| private readonly statusListeners = new Set<(status: StreamStatus) => void>(); | ||
| private reconnectDelay: number; | ||
| private reconnectTimer?: ReturnType<typeof setTimeout>; | ||
| private closedByUser = false; | ||
|
|
||
| constructor(params: { | ||
| url: string; | ||
| webSocketImpl?: WebSocketCtor; | ||
| reconnectBaseMs?: number; | ||
| reconnectMaxMs?: number; | ||
| }) { | ||
| this.url = params.url; | ||
| this.WebSocketImpl = resolveWebSocketCtor(params.webSocketImpl); | ||
| this.reconnectBaseMs = params.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS; | ||
| this.reconnectMaxMs = params.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS; | ||
| this.reconnectDelay = this.reconnectBaseMs; | ||
| } | ||
|
|
||
| subscribe(channel: string, listener: ChannelListener): Unsubscribe { | ||
| let set = this.listeners.get(channel); | ||
| if (!set) { | ||
| set = new Set(); | ||
| this.listeners.set(channel, set); | ||
| } | ||
| set.add(listener); | ||
|
|
||
| this.ensureConnected(); | ||
| if (this.status === "live") { | ||
| this.sendOp("subscribe", [channel]); | ||
| } | ||
|
|
||
| return () => { | ||
| const current = this.listeners.get(channel); | ||
| if (!current) { | ||
| return; | ||
| } | ||
| current.delete(listener); | ||
| if (current.size === 0) { | ||
| this.listeners.delete(channel); | ||
| if (this.status === "live") { | ||
| this.sendOp("unsubscribe", [channel]); | ||
| } | ||
| } | ||
| if (this.listeners.size === 0) { | ||
| this.close(); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| addStatusListener(listener: (status: StreamStatus) => void): Unsubscribe { | ||
| this.statusListeners.add(listener); | ||
| return () => { | ||
| this.statusListeners.delete(listener); | ||
| }; | ||
| } | ||
|
|
||
| private ensureConnected() { | ||
| if (this.ws || this.reconnectTimer) { | ||
| return; | ||
| } | ||
| this.closedByUser = false; | ||
| this.connect(); | ||
| } | ||
|
|
||
| private connect() { | ||
| this.setStatus(this.status === "closed" ? "connecting" : "reconnecting"); | ||
|
|
||
| let ws: WebSocketLike; | ||
| try { | ||
| ws = new this.WebSocketImpl(this.url); | ||
| } catch { | ||
| this.scheduleReconnect(); | ||
| return; | ||
| } | ||
| this.ws = ws; | ||
|
|
||
| ws.onopen = () => { | ||
| this.reconnectDelay = this.reconnectBaseMs; | ||
| this.setStatus("live"); | ||
| const channels = [...this.listeners.keys()]; | ||
| if (channels.length) { | ||
| this.sendOp("subscribe", channels); | ||
| } | ||
| }; | ||
| ws.onmessage = (ev) => this.onMessage(ev.data); | ||
| ws.onclose = () => this.onClose(); | ||
| ws.onerror = () => { | ||
| // a close event always follows; reconnection is handled there | ||
| }; | ||
| } | ||
|
|
||
| private onMessage(raw: unknown) { | ||
| const text = typeof raw === "string" ? raw : String(raw); | ||
| let frame: StreamServerFrame; | ||
| try { | ||
| frame = JSON.parse(text); | ||
| } catch { | ||
| return; | ||
| } | ||
| if ("op" in frame || frame.type !== "snapshot") { | ||
| return; | ||
| } | ||
| if (frame.data === undefined) { | ||
| return; | ||
| } | ||
| const set = this.listeners.get(frame.ch); | ||
| if (!set) { | ||
| return; | ||
| } | ||
| const payload: ChannelFrame = { | ||
| data: frame.data, | ||
| serverTs: frame.serverTs, | ||
| originTs: frame.originTs, | ||
| receivedAt: Date.now(), | ||
| byteLength: text.length, | ||
| }; | ||
| for (const listener of set) { | ||
| listener(payload); | ||
| } | ||
| } | ||
|
|
||
| private onClose() { | ||
| this.ws = undefined; | ||
| if (this.closedByUser || this.listeners.size === 0) { | ||
| this.setStatus("closed"); | ||
| return; | ||
| } | ||
| this.scheduleReconnect(); | ||
| } | ||
|
|
||
| private scheduleReconnect() { | ||
| this.setStatus("reconnecting"); | ||
| this.reconnectTimer = setTimeout(() => { | ||
| this.reconnectTimer = undefined; | ||
| this.connect(); | ||
| }, this.reconnectDelay); | ||
| this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.reconnectMaxMs); | ||
| } | ||
|
|
||
| private sendOp(op: "subscribe" | "unsubscribe", channels: string[]) { | ||
| try { | ||
| this.ws?.send(JSON.stringify({ op, channels })); | ||
| } catch { | ||
| // socket raced into a non-open state; resubscribe runs on reconnect | ||
| } | ||
| } | ||
|
|
||
| private setStatus(status: StreamStatus) { | ||
| if (this.status === status) { | ||
| return; | ||
| } | ||
| this.status = status; | ||
| for (const listener of this.statusListeners) { | ||
| listener(status); | ||
| } | ||
| } | ||
|
|
||
| close() { | ||
| this.closedByUser = true; | ||
| if (this.reconnectTimer) { | ||
| clearTimeout(this.reconnectTimer); | ||
| this.reconnectTimer = undefined; | ||
| } | ||
| this.listeners.clear(); | ||
| try { | ||
| this.ws?.close(); | ||
| } catch { | ||
| // already closing | ||
| } | ||
| this.ws = undefined; | ||
| this.setStatus("closed"); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Stream URL ignores API failover
Medium Severity
getStreamClientbuilds the WebSocket URL once fromthis.ctx.api.urlorstreamUrlOverrideand caches_streamClient. WithHttpClientWithFallback, HTTP can rotate primaries after failures while the stream stays on the first host, so REST and live prices can diverge after failover.Reviewed by Cursor Bugbot for commit 1ca4a55. Configure here.