gloomberb 0.20.9 → 0.20.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
- package/src/api-client/auth.ts +6 -0
- package/src/api-client/data.ts +1 -0
- package/src/api-client/earnings.ts +15 -0
- package/src/api-client/index.ts +14 -3
- package/src/api-client/socket-connection.ts +355 -0
- package/src/api-client/socket-features.ts +75 -0
- package/src/api-client/socket-frames.ts +161 -0
- package/src/api-client/socket-listeners.ts +207 -0
- package/src/api-client/socket-quotes.ts +332 -0
- package/src/api-client/socket.ts +150 -983
- package/src/api-client/types/account.ts +10 -0
- package/src/api-client/types/billing.ts +10 -0
- package/src/api-client/types/econ.ts +19 -7
- package/src/api-client/types/market.ts +7 -0
- package/src/api-client/types/screener.ts +2 -0
- package/src/brokers/signed-in/adapter.ts +19 -5
- package/src/brokers/signed-in/client.ts +13 -1
- package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
- package/src/cli/commands/market.ts +18 -8
- package/src/cli/commands/overview.ts +26 -7
- package/src/cli/commands/ticker.ts +40 -15
- package/src/cli/desktop-pane-shot.ts +39 -0
- package/src/cli/errors.ts +20 -3
- package/src/cli/fx-pair.ts +11 -2
- package/src/cli/history-rows.ts +34 -3
- package/src/cli/index.ts +1 -1
- package/src/cli/listing-arg.ts +51 -13
- package/src/cli/pane-functions/headless.ts +4 -2
- package/src/cli/pane-functions/index.ts +1 -0
- package/src/cli/pane-functions/resolver.ts +2 -1
- package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
- package/src/cli/pane-functions/screenshot-types.ts +4 -0
- package/src/components/chart/composite/chart-layout.ts +7 -4
- package/src/components/chart/composite/composite-chart.tsx +6 -16
- package/src/components/chart/composite/toolbar.tsx +258 -82
- package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
- package/src/components/chart/native/kitty/manager.ts +2 -0
- package/src/components/chart/native/surface/manager.ts +211 -11
- package/src/components/command-bar/list/model.ts +13 -0
- package/src/components/command-bar/panel/index.tsx +2 -13
- package/src/components/command-bar/panel/layout.ts +1 -7
- package/src/components/command-bar/panel/runtime.ts +0 -1
- package/src/components/command-bar/panel/types.ts +0 -2
- package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
- package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
- package/src/components/command-bar/surface/index.tsx +10 -5
- package/src/components/command-bar/workflow/alert.ts +21 -7
- package/src/components/data-table/column-menu.tsx +89 -0
- package/src/components/data-table/sort-menu.tsx +9 -2
- package/src/components/data-table/table-pane.ts +3 -1
- package/src/components/data-table/view.tsx +33 -6
- package/src/components/form-modal/content.tsx +10 -0
- package/src/components/index.ts +1 -1
- package/src/components/layout/pane/footer/index.tsx +25 -11
- package/src/components/layout/pane/footer/model.ts +88 -21
- package/src/components/layout/pane/sidebar.tsx +125 -15
- package/src/components/layout/shell/active-drag.ts +18 -13
- package/src/components/layout/shell/drag/magnets.ts +34 -18
- package/src/components/metric-treemap/heat-surface.tsx +2 -1
- package/src/components/metric-treemap/index.tsx +3 -2
- package/src/components/ticker/list-table-view.tsx +5 -0
- package/src/components/ui/confirm-dialog.tsx +253 -7
- package/src/components/ui/data-table/column-order.ts +180 -0
- package/src/components/ui/data-table/index.tsx +13 -2
- package/src/components/ui/data-table/opentui/index.tsx +267 -23
- package/src/components/ui/data-table/opentui/model.ts +43 -4
- package/src/components/ui/data-table/types.ts +56 -0
- package/src/components/ui/data-table/use-column-order.ts +135 -0
- package/src/components/ui/index.ts +1 -1
- package/src/components/ui/list-view.tsx +4 -3
- package/src/components/ui/status.tsx +9 -6
- package/src/components/ui/table-layout.ts +120 -0
- package/src/docs/snapshot.json +39 -2
- package/src/i18n/es.ts +14 -0
- package/src/i18n/ja.ts +14 -0
- package/src/i18n/ko.ts +14 -0
- package/src/i18n/zh-cn.ts +14 -0
- package/src/i18n/zh-tw.ts +14 -0
- package/src/market-data/coordinator/index.ts +4 -3
- package/src/market-data/coordinator/quotes.ts +12 -4
- package/src/market-data/fx-closes.ts +14 -2
- package/src/market-data/market/change-basis.ts +35 -1
- package/src/market-data/market/status.ts +37 -0
- package/src/market-data/performance.ts +4 -1
- package/src/market-data/quotes/freshness.ts +12 -0
- package/src/market-data/quotes/live-valuation.ts +26 -3
- package/src/market-data/quotes/regular-session-valuation.ts +1 -1
- package/src/market-data/realized-volatility.ts +3 -0
- package/src/market-data/us-bond-market.ts +115 -0
- package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
- package/src/plugins/builtin/account-management/keyboard.ts +3 -0
- package/src/plugins/builtin/account-management/model.ts +1 -0
- package/src/plugins/builtin/account-management/pane.tsx +51 -5
- package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
- package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
- package/src/plugins/builtin/broker-manager/index.tsx +6 -6
- package/src/plugins/builtin/broker-manager/model.ts +15 -6
- package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
- package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
- package/src/plugins/builtin/broker-manager/table.ts +10 -4
- package/src/plugins/builtin/chat/sidebar.tsx +33 -16
- package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
- package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
- package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
- package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
- package/src/plugins/builtin/correlation/compute.ts +4 -3
- package/src/plugins/builtin/earnings/board-model.ts +33 -0
- package/src/plugins/builtin/earnings/board-table.ts +50 -11
- package/src/plugins/builtin/earnings/board.tsx +29 -13
- package/src/plugins/builtin/earnings/calendar.tsx +15 -3
- package/src/plugins/builtin/earnings/client.ts +4 -1
- package/src/plugins/builtin/earnings/headless.ts +27 -14
- package/src/plugins/builtin/econ/calendar-source.ts +3 -0
- package/src/plugins/builtin/equity-screener/live.ts +74 -18
- package/src/plugins/builtin/equity-screener/model.ts +19 -4
- package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
- package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
- package/src/plugins/builtin/equity-screener/results.ts +22 -2
- package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
- package/src/plugins/builtin/futures/index.tsx +15 -1
- package/src/plugins/builtin/futures/table.tsx +1 -1
- package/src/plugins/builtin/fx-matrix/index.tsx +2 -0
- package/src/plugins/builtin/help/index.tsx +1 -1
- package/src/plugins/builtin/holders/pane.tsx +30 -20
- package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
- package/src/plugins/builtin/iv-history/events.ts +5 -0
- package/src/plugins/builtin/iv-history/headless.ts +19 -12
- package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
- package/src/plugins/builtin/macro-day/headless.ts +27 -8
- package/src/plugins/builtin/macro-day/model.ts +17 -4
- package/src/plugins/builtin/macro-day/releases.ts +36 -15
- package/src/plugins/builtin/market-halts/model.ts +3 -2
- package/src/plugins/builtin/market-movers/headless.ts +2 -1
- package/src/plugins/builtin/market-movers/index.tsx +3 -2
- package/src/plugins/builtin/market-movers/model.ts +75 -22
- package/src/plugins/builtin/market-movers/screener.ts +2 -1
- package/src/plugins/builtin/market-movers/table.ts +7 -5
- package/src/plugins/builtin/options/view.tsx +2 -0
- package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
- package/src/plugins/builtin/pe-band/model.ts +4 -0
- package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
- package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
- package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
- package/src/plugins/builtin/portfolio-list/pane/index.tsx +15 -1
- package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
- package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
- package/src/plugins/builtin/portfolio-list/table.tsx +18 -1
- package/src/plugins/builtin/rate-path/pane.tsx +2 -0
- package/src/plugins/builtin/research/analyst-headless.ts +9 -1
- package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
- package/src/plugins/builtin/research/client.ts +25 -1
- package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
- package/src/plugins/builtin/research/event-model.ts +3 -13
- package/src/plugins/builtin/research/event-sources.ts +3 -1
- package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
- package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
- package/src/plugins/builtin/seasonality/pane.tsx +2 -1
- package/src/plugins/builtin/short-interest/headless.ts +2 -0
- package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
- package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
- package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
- package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
- package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
- package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
- package/src/plugins/builtin/vol-surface/heat-grid.tsx +2 -1
- package/src/plugins/builtin/vol-surface/pane.tsx +2 -1
- package/src/plugins/builtin/world-indices/index.tsx +5 -1
- package/src/plugins/builtin/yield-curve/headless.ts +5 -1
- package/src/plugins/builtin/yield-curve/index.tsx +7 -1
- package/src/portfolio/column-values.ts +47 -14
- package/src/portfolio/return-metrics.ts +4 -2
- package/src/renderers/dom/data-table/column-drag.ts +147 -0
- package/src/renderers/dom/data-table/index.tsx +22 -0
- package/src/renderers/dom/data-table/row.tsx +27 -5
- package/src/renderers/dom/host/image-surface.tsx +19 -9
- package/src/renderers/dom/host/input.tsx +4 -0
- package/src/renderers/dom/styles.css +22 -0
- package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
- package/src/renderers/opentui/chart-surface.tsx +1 -0
- package/src/renderers/opentui/frame-hits.ts +33 -0
- package/src/renderers/opentui/host.tsx +2 -0
- package/src/renderers/opentui/native-surface.ts +14 -21
- package/src/renderers/opentui/test-utils.tsx +3 -0
- package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
- package/src/sources/provider-errors.ts +12 -0
- package/src/sources/provider-router/index.ts +12 -4
- package/src/state/app/context/index.tsx +22 -0
- package/src/state/pane-session.ts +145 -0
- package/src/test-support/app-store.ts +24 -1
- package/src/tickers/search/home-listing.ts +44 -1
- package/src/tickers/search/index.ts +5 -2
- package/src/tickers/search/ranking.ts +7 -7
- package/src/tickers/us-listing.ts +11 -5
- package/src/time-series/base-series.ts +7 -1
- package/src/time-series/fundamentals/current-valuation.ts +8 -0
- package/src/time-series/fundamentals/series.ts +6 -0
- package/src/time-series/live-quotes.ts +3 -9
- package/src/time-series/resolve.ts +1 -0
- package/src/types/financials.ts +20 -0
- package/src/types/headless.ts +9 -0
- package/src/ui/host.tsx +20 -0
- package/src/ui/pointer-drag.ts +11 -2
- package/src/utils/exchanges.ts +13 -8
- package/src/utils/fundamentals.ts +14 -3
- package/src/utils/price-earnings.ts +17 -10
- package/src/utils/price-history-integrity.ts +15 -0
- package/src/utils/reason-codes.ts +79 -0
- package/src/utils/share-multiples.cases.json +1667 -0
- package/src/utils/share-multiples.ts +384 -0
- package/src/utils/untrusted-text.ts +11 -0
package/src/api-client/socket.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { logFailure } from "../utils/log-failure";
|
|
2
1
|
import type { TapeFeedEvent } from "./tape";
|
|
3
2
|
import type {
|
|
4
3
|
AuthUser,
|
|
@@ -12,99 +11,28 @@ import type {
|
|
|
12
11
|
ScannerKind,
|
|
13
12
|
TeamNotification,
|
|
14
13
|
} from "./types";
|
|
15
|
-
import {
|
|
16
|
-
normalizeChatChannelStateFrame,
|
|
17
|
-
normalizeChatMessage,
|
|
18
|
-
normalizeChatNotification,
|
|
19
|
-
normalizeChatReactions,
|
|
20
|
-
normalizeTeamNotification,
|
|
21
|
-
} from "./normalizers";
|
|
22
|
-
import { debugLog, previewList, previewLongLists } from "../utils/debug-log";
|
|
14
|
+
import { debugLog } from "../utils/debug-log";
|
|
23
15
|
import { canonicalExchange, normalizeSymbol } from "../utils/exchanges";
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
} from "
|
|
16
|
+
import { connectionHealth, type ConnectionHealthRegistry } from "../core/connection-health";
|
|
17
|
+
import { SocketConnection } from "./socket-connection";
|
|
18
|
+
import { SocketFeatures } from "./socket-features";
|
|
19
|
+
import { dispatchSocketFrame, type SocketFrameRoutes, type SocketReadyFrame } from "./socket-frames";
|
|
20
|
+
import { SocketListeners } from "./socket-listeners";
|
|
21
|
+
import { QuoteStreamSubscriptions } from "./socket-quotes";
|
|
22
|
+
|
|
23
|
+
export { CHAT_ATTACHMENTS_FEATURE, TERMINAL_RELAY_FEATURE } from "./socket-features";
|
|
24
|
+
export { SOCKET_CONNECT_TIMEOUT_MS, SOCKET_PING_ANSWER_MS, SOCKET_QUIET_PING_MS } from "./socket-connection";
|
|
32
25
|
|
|
33
|
-
const QUOTE_SUBSCRIPTION_FLUSH_MS = 25;
|
|
34
|
-
/** How long a connection may take to open before the attempt is dropped and tried again. */
|
|
35
|
-
export const SOCKET_CONNECT_TIMEOUT_MS = 10_000;
|
|
36
|
-
/**
|
|
37
|
-
* An open connection that has sent nothing for this long is asked whether it
|
|
38
|
-
* is still there: a `ping`, which the server answers with a `pong`.
|
|
39
|
-
*/
|
|
40
|
-
export const SOCKET_QUIET_PING_MS = 10_000;
|
|
41
|
-
/**
|
|
42
|
-
* A connection that has not answered a ping in this long, nothing else come
|
|
43
|
-
* back meanwhile, is taken for dead (a half-open link: a laptop that slept, a
|
|
44
|
-
* network that changed under it). It is dropped and opened again; until then
|
|
45
|
-
* prices it streamed read as stale. Only an unanswered ping drops it: silence
|
|
46
|
-
* alone does not, since a check that runs late (a hidden tab's throttled
|
|
47
|
-
* timers, a wake from sleep) finds any connection silent.
|
|
48
|
-
*/
|
|
49
|
-
export const SOCKET_PING_ANSWER_MS = 10_000;
|
|
50
|
-
/** How often an open connection's silence is checked; it never needs to be exact. */
|
|
51
|
-
const SOCKET_SILENCE_CHECK_MS = 2_500;
|
|
52
|
-
/**
|
|
53
|
-
* Protocol features this client can read. A server lists the ones it offers
|
|
54
|
-
* in "ready"; the client opts into the shared ones, so an older server never
|
|
55
|
-
* sees a request it does not understand.
|
|
56
|
-
*/
|
|
57
|
-
const MARKET_BATCH_FEATURE = "market.batch";
|
|
58
|
-
/** Chat frames carry `attachments`; without it the server writes images into the text. */
|
|
59
|
-
export const CHAT_ATTACHMENTS_FEATURE = "chat.attachments";
|
|
60
|
-
/** The app can run terminal tools relayed from a remote assistant; it still announces itself first. */
|
|
61
|
-
export const TERMINAL_RELAY_FEATURE = "terminal.relay";
|
|
62
|
-
const CLIENT_SOCKET_FEATURES = [MARKET_BATCH_FEATURE, CHAT_ATTACHMENTS_FEATURE, TERMINAL_RELAY_FEATURE] as const;
|
|
63
|
-
/**
|
|
64
|
-
* The server streams perpetual listings (`BTC:HYPERLIQUID`) from their venues. Until a server offers it, they are
|
|
65
|
-
* kept off market.subscribe: an older one would read `BTC` on HYPERLIQUID as a stock symbol.
|
|
66
|
-
*/
|
|
67
|
-
const MARKET_PERPS_FEATURE = "market.perps";
|
|
68
|
-
/**
|
|
69
|
-
* The most perpetual listings the app streams at once, across every pane: on screen and selected first. The server
|
|
70
|
-
* takes up to 100 from one connection (fewer signed out); the rest keep their fetched readings.
|
|
71
|
-
*/
|
|
72
|
-
const PERP_STREAM_BUDGET = 60;
|
|
73
|
-
/** On screen and selected first, then by weight; equal ones keep the order they were asked in. */
|
|
74
|
-
const perpStreamRank = (target: QuoteStreamTarget) => (target.selected ? 2 : 0) + (target.visible ? 1 : 0);
|
|
75
|
-
const isPerpTarget = (target: QuoteStreamTarget) => !!perpetualListing(target.symbol, target.exchange);
|
|
76
26
|
const cloudApiLog = debugLog.createLogger("cloud-api");
|
|
77
27
|
|
|
78
|
-
type ChannelListener = (message: ChatMessage) => void;
|
|
79
28
|
type ChatNotificationListener = (notification: ChatNotification) => void;
|
|
80
29
|
type ChatChannelStateListener = (state: ChatChannelState) => void;
|
|
81
30
|
type ChatPresenceListener = (onlineCount: number) => void;
|
|
82
31
|
type ChatReactionsListener = (update: ChatReactionsUpdate) => void;
|
|
83
32
|
type TeamNotificationListener = (notification: TeamNotification) => void;
|
|
84
33
|
type CloudEventListener = (data: unknown) => void;
|
|
85
|
-
type QuoteListener = (
|
|
86
|
-
target: QuoteStreamTarget,
|
|
87
|
-
quote: CloudQuotePayload,
|
|
88
|
-
) => void;
|
|
89
|
-
type QuoteSubscription = {
|
|
90
|
-
target: QuoteStreamTarget;
|
|
91
|
-
listener: QuoteListener;
|
|
92
|
-
};
|
|
93
34
|
type ScannerListener = (event: ScannerFeedEvent) => void;
|
|
94
35
|
|
|
95
|
-
const SCANNER_MESSAGE_KINDS: Record<string, ScannerKind> = {
|
|
96
|
-
"scanner.hilo": "hilo",
|
|
97
|
-
"scanner.flow": "flow",
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
function mergeQuoteStreamSubscriptions(
|
|
101
|
-
subscriptions: Iterable<QuoteSubscription>,
|
|
102
|
-
): QuoteStreamTarget | null {
|
|
103
|
-
return mergeQuoteSubscriptionTargets(
|
|
104
|
-
[...subscriptions].map((subscription) => subscription.target),
|
|
105
|
-
);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
36
|
type CloudApiSocketDelegate = {
|
|
109
37
|
getBaseUrl: () => string;
|
|
110
38
|
getSocketAuthToken: () => string | null;
|
|
@@ -130,81 +58,51 @@ type ChatChannelConnection = {
|
|
|
130
58
|
close: () => void;
|
|
131
59
|
};
|
|
132
60
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
61
|
+
/**
|
|
62
|
+
* The app's realtime link to Gloom Cloud: quotes, chat, team and scanner
|
|
63
|
+
* feeds over one WebSocket. It keeps the connection open while anything
|
|
64
|
+
* listens and decides what each subscription needs from it; the connection
|
|
65
|
+
* itself, inbound frames, quote batching, feature negotiation and the listener
|
|
66
|
+
* registries live in the `socket-*` modules beside it.
|
|
67
|
+
*/
|
|
141
68
|
export class CloudApiSocket {
|
|
142
|
-
private
|
|
143
|
-
private
|
|
144
|
-
private
|
|
145
|
-
|
|
146
|
-
private
|
|
147
|
-
/** Checks the open connection's silence (SOCKET_QUIET_PING_MS, SOCKET_PING_ANSWER_MS). */
|
|
148
|
-
private silenceTimer: ReturnType<typeof setInterval> | null = null;
|
|
149
|
-
/** When the open connection last sent anything, and when the ping still unanswered went out. */
|
|
150
|
-
private lastFrameAt = 0;
|
|
151
|
-
private pingedAt: number | null = null;
|
|
152
|
-
|
|
153
|
-
private readonly channelListeners = new Map<string, Set<ChannelListener>>();
|
|
154
|
-
private readonly chatMentionCandidatesListeners = new Set<() => void>();
|
|
155
|
-
private readonly chatNotificationListeners =
|
|
156
|
-
new Set<ChatNotificationListener>();
|
|
157
|
-
private readonly chatChannelStateListeners =
|
|
158
|
-
new Set<ChatChannelStateListener>();
|
|
159
|
-
private readonly chatPresenceListeners = new Set<ChatPresenceListener>();
|
|
160
|
-
private readonly chatReactionsListeners = new Set<ChatReactionsListener>();
|
|
161
|
-
private readonly teamNotificationListeners =
|
|
162
|
-
new Set<TeamNotificationListener>();
|
|
163
|
-
private readonly cloudEventListeners = new Map<
|
|
164
|
-
string,
|
|
165
|
-
Set<CloudEventListener>
|
|
166
|
-
>();
|
|
167
|
-
private nextQuoteSubscriptionId = 1;
|
|
168
|
-
private readonly quoteSubscriptions = new Map<
|
|
169
|
-
string,
|
|
170
|
-
Map<number, QuoteSubscription>
|
|
171
|
-
>();
|
|
172
|
-
private readonly quoteTargets = new Map<string, QuoteStreamTarget>();
|
|
173
|
-
private readonly pendingQuoteSubscribes = new Map<
|
|
174
|
-
string,
|
|
175
|
-
QuoteStreamTarget
|
|
176
|
-
>();
|
|
177
|
-
private readonly pendingQuoteUnsubscribes = new Map<
|
|
178
|
-
string,
|
|
179
|
-
QuoteStreamTarget
|
|
180
|
-
>();
|
|
181
|
-
private quoteSubscriptionFlushTimer: ReturnType<typeof setTimeout> | null =
|
|
182
|
-
null;
|
|
183
|
-
/** The connection that already opted into server features; a reconnect negotiates again. */
|
|
184
|
-
private featuresRequestedFor: WebSocket | null = null;
|
|
185
|
-
/** What the last "ready" frame offered; kept across reconnects so a blip does not hide features. */
|
|
186
|
-
private offeredFeatures: ReadonlySet<string> = new Set();
|
|
187
|
-
/**
|
|
188
|
-
* The connection whose server offered perpetual markets. Asked of every connection: a reconnect may reach an older
|
|
189
|
-
* server, which would read `BTC` on HYPERLIQUID as a stock symbol.
|
|
190
|
-
*/
|
|
191
|
-
private perpsOfferedOn: WebSocket | null = null;
|
|
192
|
-
/** The perpetual listings this connection streams, within PERP_STREAM_BUDGET. */
|
|
193
|
-
private streamedPerps = new Map<string, QuoteStreamTarget>();
|
|
194
|
-
private readonly offeredFeatureListeners = new Set<() => void>();
|
|
195
|
-
private readonly connectionListeners = new Set<(event: "ready" | "closed") => void>();
|
|
196
|
-
private readonly tapeListeners = new Map<string, { symbol: string; exchange: string; listeners: Set<(event: TapeFeedEvent) => void> }>();
|
|
197
|
-
private readonly scannerListeners = new Map<
|
|
198
|
-
ScannerKind,
|
|
199
|
-
Set<ScannerListener>
|
|
200
|
-
>();
|
|
201
|
-
/** Latest fan-out payload, so a pane opened mid-stream does not wait for the next tick. */
|
|
202
|
-
private readonly scannerSnapshots = new Map<ScannerKind, ScannerFeedEvent>();
|
|
69
|
+
private readonly listeners = new SocketListeners();
|
|
70
|
+
private readonly connection: SocketConnection;
|
|
71
|
+
private readonly quotes: QuoteStreamSubscriptions;
|
|
72
|
+
private readonly features: SocketFeatures;
|
|
73
|
+
private readonly frameRoutes: SocketFrameRoutes;
|
|
203
74
|
|
|
204
75
|
constructor(
|
|
205
76
|
private readonly delegate: CloudApiSocketDelegate,
|
|
206
|
-
|
|
207
|
-
) {
|
|
77
|
+
health: ConnectionHealthRegistry = connectionHealth,
|
|
78
|
+
) {
|
|
79
|
+
this.connection = new SocketConnection(delegate, health, {
|
|
80
|
+
wanted: () => this.shouldKeepSocketOpen(),
|
|
81
|
+
logCounts: () => ({
|
|
82
|
+
quoteTargets: this.quotes.size,
|
|
83
|
+
channelTargets: this.listeners.chatChannels.size,
|
|
84
|
+
}),
|
|
85
|
+
opened: () => this.replaySubscriptions(),
|
|
86
|
+
received: (raw) => void this.handleSocketMessage(raw),
|
|
87
|
+
interrupted: () => this.listeners.tape.emitAll({ type: "disconnected", reason: "Stream disconnected; observed window may contain gaps" }),
|
|
88
|
+
closed: () => this.listeners.connection.emit("closed"),
|
|
89
|
+
});
|
|
90
|
+
const send = (payload: Record<string, unknown>) => this.connection.send(payload);
|
|
91
|
+
this.quotes = new QuoteStreamSubscriptions({
|
|
92
|
+
openSocket: () => this.connection.openSocket(),
|
|
93
|
+
send,
|
|
94
|
+
});
|
|
95
|
+
this.features = new SocketFeatures({
|
|
96
|
+
send,
|
|
97
|
+
perpsOffered: (socket) => this.quotes.setPerpsConnection(socket),
|
|
98
|
+
});
|
|
99
|
+
this.frameRoutes = {
|
|
100
|
+
listeners: this.listeners,
|
|
101
|
+
ready: (frame) => this.handleReady(frame),
|
|
102
|
+
unverified: () => this.handleUnverified(),
|
|
103
|
+
quote: (frame) => this.quotes.deliver(frame),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
208
106
|
|
|
209
107
|
syncAuthState(options: { reconnect?: boolean } = {}): void {
|
|
210
108
|
if (!this.shouldKeepSocketOpen()) {
|
|
@@ -214,32 +112,12 @@ export class CloudApiSocket {
|
|
|
214
112
|
if (options.reconnect) {
|
|
215
113
|
this.teardown();
|
|
216
114
|
}
|
|
217
|
-
this.
|
|
115
|
+
this.connection.ensureOpen();
|
|
218
116
|
}
|
|
219
117
|
|
|
220
118
|
teardown(): void {
|
|
221
|
-
this.
|
|
222
|
-
|
|
223
|
-
clearTimeout(this.reconnectTimer);
|
|
224
|
-
this.reconnectTimer = null;
|
|
225
|
-
}
|
|
226
|
-
this.stopWatching();
|
|
227
|
-
const ws = this.ws;
|
|
228
|
-
this.ws = null;
|
|
229
|
-
if (ws) {
|
|
230
|
-
this.emitConnection("closed");
|
|
231
|
-
cloudApiLog.info("teardown websocket");
|
|
232
|
-
this.health.reportSocketState(
|
|
233
|
-
GLOOM_CLOUD_SOCKET_CONNECTION_ID,
|
|
234
|
-
"idle",
|
|
235
|
-
"Socket closed locally",
|
|
236
|
-
);
|
|
237
|
-
}
|
|
238
|
-
try {
|
|
239
|
-
ws?.close();
|
|
240
|
-
} catch {
|
|
241
|
-
// Intentional ignore: Closing an already closed socket needs no further cleanup.
|
|
242
|
-
}
|
|
119
|
+
this.listeners.tape.emitAll({ type: "reset", reason: "Stream session changed" });
|
|
120
|
+
this.connection.close();
|
|
243
121
|
}
|
|
244
122
|
|
|
245
123
|
connectChannel(
|
|
@@ -257,14 +135,10 @@ export class CloudApiSocket {
|
|
|
257
135
|
};
|
|
258
136
|
}
|
|
259
137
|
|
|
260
|
-
const listeners
|
|
261
|
-
|
|
262
|
-
const firstListener = listeners.size === 0;
|
|
263
|
-
listeners.add(onMessage);
|
|
264
|
-
this.channelListeners.set(channelId, listeners);
|
|
265
|
-
this.ensureSocket();
|
|
138
|
+
const firstListener = this.listeners.chatChannels.add(channelId, onMessage);
|
|
139
|
+
this.connection.ensureOpen();
|
|
266
140
|
if (firstListener) {
|
|
267
|
-
this.
|
|
141
|
+
this.connection.send({ type: "chat.subscribe", channelId });
|
|
268
142
|
}
|
|
269
143
|
|
|
270
144
|
return {
|
|
@@ -284,30 +158,22 @@ export class CloudApiSocket {
|
|
|
284
158
|
}
|
|
285
159
|
},
|
|
286
160
|
close: () => {
|
|
287
|
-
const
|
|
288
|
-
if (
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
this.channelListeners.delete(channelId);
|
|
292
|
-
this.sendSocketMessage({ type: "chat.unsubscribe", channelId });
|
|
293
|
-
}
|
|
294
|
-
if (!this.shouldKeepSocketOpen()) {
|
|
295
|
-
this.teardown();
|
|
161
|
+
const removal = this.listeners.chatChannels.remove(channelId, onMessage);
|
|
162
|
+
if (removal === "unknown-key") return;
|
|
163
|
+
if (removal === "last") {
|
|
164
|
+
this.connection.send({ type: "chat.unsubscribe", channelId });
|
|
296
165
|
}
|
|
166
|
+
this.releaseSocket();
|
|
297
167
|
},
|
|
298
168
|
};
|
|
299
169
|
}
|
|
300
170
|
|
|
301
171
|
subscribeChatNotifications(listener: ChatNotificationListener): () => void {
|
|
302
|
-
this.
|
|
303
|
-
return () => {
|
|
304
|
-
this.chatNotificationListeners.delete(listener);
|
|
305
|
-
};
|
|
172
|
+
return this.listeners.chatNotifications.add(listener);
|
|
306
173
|
}
|
|
307
174
|
|
|
308
175
|
subscribeChatMentionCandidatesChanged(listener: () => void): () => void {
|
|
309
|
-
this.
|
|
310
|
-
return () => { this.chatMentionCandidatesListeners.delete(listener); };
|
|
176
|
+
return this.listeners.chatMentionCandidates.add(listener);
|
|
311
177
|
}
|
|
312
178
|
|
|
313
179
|
/**
|
|
@@ -315,92 +181,53 @@ export class CloudApiSocket {
|
|
|
315
181
|
* notifications, it never opens the socket by itself.
|
|
316
182
|
*/
|
|
317
183
|
subscribeChatChannelState(listener: ChatChannelStateListener): () => void {
|
|
318
|
-
this.
|
|
319
|
-
return () => {
|
|
320
|
-
this.chatChannelStateListeners.delete(listener);
|
|
321
|
-
};
|
|
184
|
+
return this.listeners.chatChannelState.add(listener);
|
|
322
185
|
}
|
|
323
186
|
|
|
324
187
|
/** A message's reactions changed in a channel this socket reads. */
|
|
325
188
|
subscribeChatReactions(listener: ChatReactionsListener): () => void {
|
|
326
|
-
this.
|
|
327
|
-
return () => {
|
|
328
|
-
this.chatReactionsListeners.delete(listener);
|
|
329
|
-
};
|
|
189
|
+
return this.listeners.chatReactions.add(listener);
|
|
330
190
|
}
|
|
331
191
|
|
|
332
192
|
subscribeChatPresence(listener: ChatPresenceListener): () => void {
|
|
333
|
-
this.
|
|
334
|
-
return () => {
|
|
335
|
-
this.chatPresenceListeners.delete(listener);
|
|
336
|
-
};
|
|
193
|
+
return this.listeners.chatPresence.add(listener);
|
|
337
194
|
}
|
|
338
195
|
|
|
339
196
|
/** Whether the server's last "ready" frame offered this protocol feature. */
|
|
340
197
|
serverOffers(feature: string): boolean {
|
|
341
|
-
return this.
|
|
198
|
+
return this.features.offers(feature);
|
|
342
199
|
}
|
|
343
200
|
|
|
344
201
|
subscribeServerFeatures(listener: () => void): () => void {
|
|
345
|
-
this.
|
|
346
|
-
return () => {
|
|
347
|
-
this.offeredFeatureListeners.delete(listener);
|
|
348
|
-
};
|
|
202
|
+
return this.features.subscribe(listener);
|
|
349
203
|
}
|
|
350
204
|
|
|
351
205
|
/** "ready" after each server hello (features negotiated), "closed" when that connection ends. */
|
|
352
206
|
subscribeConnection(listener: (event: "ready" | "closed") => void): () => void {
|
|
353
|
-
this.
|
|
354
|
-
return () => {
|
|
355
|
-
this.connectionListeners.delete(listener);
|
|
356
|
-
};
|
|
207
|
+
return this.listeners.connection.add(listener);
|
|
357
208
|
}
|
|
358
209
|
|
|
359
210
|
/** Sends one frame on the open connection; false when there is none. */
|
|
360
211
|
sendFrame(payload: Record<string, unknown>): boolean {
|
|
361
|
-
|
|
362
|
-
try {
|
|
363
|
-
this.ws.send(JSON.stringify(payload));
|
|
364
|
-
return true;
|
|
365
|
-
} catch (error) {
|
|
366
|
-
logFailure("cloud-socket", "WebSocket frame send failed")(error);
|
|
367
|
-
return false;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
private emitConnection(event: "ready" | "closed"): void {
|
|
372
|
-
for (const listener of this.connectionListeners) listener(event);
|
|
212
|
+
return this.connection.sendFrame(payload);
|
|
373
213
|
}
|
|
374
214
|
|
|
375
215
|
subscribeTeamNotifications(listener: TeamNotificationListener): () => void {
|
|
376
|
-
this.
|
|
216
|
+
const remove = this.listeners.teamNotifications.add(listener);
|
|
377
217
|
this.syncAuthState();
|
|
378
218
|
return () => {
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
this.teardown();
|
|
382
|
-
}
|
|
219
|
+
remove();
|
|
220
|
+
this.releaseSocket();
|
|
383
221
|
};
|
|
384
222
|
}
|
|
385
223
|
|
|
386
224
|
/** Subscribes to a server push frame by type, e.g. a team layout update. */
|
|
387
225
|
subscribeCloudEvent(type: string, listener: CloudEventListener): () => void {
|
|
388
|
-
|
|
389
|
-
this.cloudEventListeners.get(type) ?? new Set<CloudEventListener>();
|
|
390
|
-
listeners.add(listener);
|
|
391
|
-
this.cloudEventListeners.set(type, listeners);
|
|
226
|
+
this.listeners.cloudEvents.add(type, listener);
|
|
392
227
|
this.syncAuthState();
|
|
393
228
|
return () => {
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
current.delete(listener);
|
|
397
|
-
if (current.size === 0) {
|
|
398
|
-
this.cloudEventListeners.delete(type);
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
if (!this.shouldKeepSocketOpen()) {
|
|
402
|
-
this.teardown();
|
|
403
|
-
}
|
|
229
|
+
this.listeners.cloudEvents.remove(type, listener);
|
|
230
|
+
this.releaseSocket();
|
|
404
231
|
};
|
|
405
232
|
}
|
|
406
233
|
|
|
@@ -412,800 +239,140 @@ export class CloudApiSocket {
|
|
|
412
239
|
scanner: ScannerKind,
|
|
413
240
|
listener: ScannerListener,
|
|
414
241
|
): () => void {
|
|
415
|
-
const listeners
|
|
416
|
-
|
|
417
|
-
const firstListener = listeners.size === 0;
|
|
418
|
-
listeners.add(listener);
|
|
419
|
-
this.scannerListeners.set(scanner, listeners);
|
|
420
|
-
this.ensureSocket();
|
|
242
|
+
const firstListener = this.listeners.scanners.add(scanner, listener);
|
|
243
|
+
this.connection.ensureOpen();
|
|
421
244
|
if (firstListener) {
|
|
422
|
-
this.
|
|
245
|
+
this.connection.send({ type: "scanner.subscribe", scanner });
|
|
423
246
|
} else {
|
|
424
|
-
const snapshot = this.
|
|
247
|
+
const snapshot = this.listeners.scanners.snapshot(scanner);
|
|
425
248
|
if (snapshot) listener(snapshot);
|
|
426
249
|
}
|
|
427
250
|
|
|
428
251
|
return () => {
|
|
429
|
-
const
|
|
430
|
-
if (
|
|
431
|
-
if (
|
|
432
|
-
this.
|
|
433
|
-
this.scannerSnapshots.delete(scanner);
|
|
434
|
-
this.sendSocketMessage({ type: "scanner.unsubscribe", scanner });
|
|
435
|
-
}
|
|
436
|
-
if (!this.shouldKeepSocketOpen()) {
|
|
437
|
-
this.teardown();
|
|
252
|
+
const removal = this.listeners.scanners.remove(scanner, listener);
|
|
253
|
+
if (removal !== "removed" && removal !== "last") return;
|
|
254
|
+
if (removal === "last") {
|
|
255
|
+
this.connection.send({ type: "scanner.unsubscribe", scanner });
|
|
438
256
|
}
|
|
257
|
+
this.releaseSocket();
|
|
439
258
|
};
|
|
440
259
|
}
|
|
441
260
|
|
|
442
261
|
subscribeTape(symbol: string, exchange: string, listener: (event: TapeFeedEvent) => void): () => void {
|
|
443
262
|
const target = { symbol: normalizeSymbol(symbol), exchange: canonicalExchange(exchange) };
|
|
444
|
-
const
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
entry.listeners.add(listener);
|
|
448
|
-
this.tapeListeners.set(key, entry);
|
|
449
|
-
this.ensureSocket();
|
|
450
|
-
if (!existing) this.sendSocketMessage({ type: "tape.subscribe", ...target });
|
|
263
|
+
const firstListener = this.listeners.tape.add(target, listener);
|
|
264
|
+
this.connection.ensureOpen();
|
|
265
|
+
if (firstListener) this.connection.send({ type: "tape.subscribe", ...target });
|
|
451
266
|
return () => {
|
|
452
|
-
const
|
|
453
|
-
if (
|
|
454
|
-
if (
|
|
455
|
-
|
|
456
|
-
this.sendSocketMessage({ type: "tape.unsubscribe", ...target });
|
|
457
|
-
}
|
|
458
|
-
if (!this.shouldKeepSocketOpen()) this.teardown();
|
|
267
|
+
const removal = this.listeners.tape.remove(target, listener);
|
|
268
|
+
if (removal !== "removed" && removal !== "last") return;
|
|
269
|
+
if (removal === "last") this.connection.send({ type: "tape.unsubscribe", ...target });
|
|
270
|
+
this.releaseSocket();
|
|
459
271
|
};
|
|
460
272
|
}
|
|
461
273
|
|
|
462
|
-
private emitTapeStatus(event: Exclude<TapeFeedEvent, { type: "data" }>): void {
|
|
463
|
-
for (const entry of this.tapeListeners.values()) for (const listener of entry.listeners) listener(event);
|
|
464
|
-
}
|
|
465
|
-
|
|
466
274
|
subscribeQuotes(
|
|
467
275
|
targets: QuoteStreamTarget[],
|
|
468
276
|
onQuote: (target: QuoteStreamTarget, quote: CloudQuotePayload) => void,
|
|
469
277
|
): () => void {
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
targets
|
|
474
|
-
.filter(
|
|
475
|
-
(target) =>
|
|
476
|
-
typeof target.symbol === "string" &&
|
|
477
|
-
target.symbol.trim().length > 0,
|
|
478
|
-
)
|
|
479
|
-
.map((target) => {
|
|
480
|
-
const normalized = {
|
|
481
|
-
symbol: normalizeSymbol(target.symbol),
|
|
482
|
-
exchange: canonicalExchange(target.exchange),
|
|
483
|
-
surface: target.surface,
|
|
484
|
-
visible: target.visible,
|
|
485
|
-
selected: target.selected,
|
|
486
|
-
weight: target.weight,
|
|
487
|
-
} satisfies QuoteStreamTarget;
|
|
488
|
-
return [
|
|
489
|
-
marketKey(normalized.symbol, normalized.exchange),
|
|
490
|
-
normalized,
|
|
491
|
-
] as const;
|
|
492
|
-
}),
|
|
493
|
-
).values(),
|
|
494
|
-
];
|
|
495
|
-
|
|
496
|
-
const newSubscriptions: QuoteStreamTarget[] = [];
|
|
497
|
-
const updatedSubscriptions: QuoteStreamTarget[] = [];
|
|
498
|
-
for (const target of uniqueTargets) {
|
|
499
|
-
const key = marketKey(target.symbol, target.exchange);
|
|
500
|
-
const subscriptions =
|
|
501
|
-
this.quoteSubscriptions.get(key) ??
|
|
502
|
-
new Map<number, QuoteSubscription>();
|
|
503
|
-
const previousTarget = this.quoteTargets.get(key);
|
|
504
|
-
subscriptions.set(subscriptionId, { target, listener: onQuote });
|
|
505
|
-
this.quoteSubscriptions.set(key, subscriptions);
|
|
506
|
-
const mergedTarget =
|
|
507
|
-
mergeQuoteStreamSubscriptions(subscriptions.values()) ?? target;
|
|
508
|
-
if (!previousTarget) {
|
|
509
|
-
newSubscriptions.push(target);
|
|
510
|
-
} else if (
|
|
511
|
-
!this.areQuoteStreamTargetsEquivalent(previousTarget, mergedTarget)
|
|
512
|
-
) {
|
|
513
|
-
updatedSubscriptions.push(mergedTarget);
|
|
514
|
-
}
|
|
515
|
-
this.quoteTargets.set(key, mergedTarget);
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
this.ensureSocket();
|
|
519
|
-
const subscriptionsToSend = [...newSubscriptions, ...updatedSubscriptions];
|
|
520
|
-
if (subscriptionsToSend.length > 0) {
|
|
521
|
-
cloudApiLog.info("register quote listeners", {
|
|
522
|
-
count: subscriptionsToSend.length,
|
|
523
|
-
symbols: previewList(subscriptionsToSend, (target) =>
|
|
524
|
-
marketKey(target.symbol, target.exchange),
|
|
525
|
-
),
|
|
526
|
-
});
|
|
527
|
-
this.queueQuoteSubscribes(subscriptionsToSend);
|
|
528
|
-
}
|
|
529
|
-
|
|
278
|
+
const subscription = this.quotes.subscribe(targets, onQuote);
|
|
279
|
+
this.connection.ensureOpen();
|
|
280
|
+
subscription.announce();
|
|
530
281
|
return () => {
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
for (const target of uniqueTargets) {
|
|
535
|
-
const key = marketKey(target.symbol, target.exchange);
|
|
536
|
-
const subscriptions = this.quoteSubscriptions.get(key);
|
|
537
|
-
if (!subscriptions || !subscriptions.delete(subscriptionId)) continue;
|
|
538
|
-
const previousTarget = this.quoteTargets.get(key);
|
|
539
|
-
if (subscriptions.size === 0) {
|
|
540
|
-
this.quoteSubscriptions.delete(key);
|
|
541
|
-
if (previousTarget) removedTargets.push(previousTarget);
|
|
542
|
-
this.quoteTargets.delete(key);
|
|
543
|
-
continue;
|
|
544
|
-
}
|
|
545
|
-
const mergedTarget = mergeQuoteStreamSubscriptions(
|
|
546
|
-
subscriptions.values(),
|
|
547
|
-
);
|
|
548
|
-
if (!mergedTarget) continue;
|
|
549
|
-
this.quoteTargets.set(key, mergedTarget);
|
|
550
|
-
if (
|
|
551
|
-
previousTarget &&
|
|
552
|
-
!this.areQuoteStreamTargetsEquivalent(previousTarget, mergedTarget)
|
|
553
|
-
) {
|
|
554
|
-
updatedTargets.push(mergedTarget);
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
if (updatedTargets.length > 0) {
|
|
559
|
-
this.queueQuoteSubscribes(updatedTargets);
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
if (removedTargets.length > 0) {
|
|
563
|
-
cloudApiLog.info("remove quote listeners", {
|
|
564
|
-
count: removedTargets.length,
|
|
565
|
-
symbols: previewList(removedTargets, (target) =>
|
|
566
|
-
marketKey(target.symbol, target.exchange),
|
|
567
|
-
),
|
|
568
|
-
});
|
|
569
|
-
this.queueQuoteUnsubscribes(removedTargets);
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
if (!this.shouldKeepSocketOpen()) {
|
|
573
|
-
this.teardown();
|
|
574
|
-
}
|
|
282
|
+
subscription.release();
|
|
283
|
+
this.releaseSocket();
|
|
575
284
|
};
|
|
576
285
|
}
|
|
577
286
|
|
|
578
287
|
dispose(): void {
|
|
579
288
|
cloudApiLog.info("dispose api client", {
|
|
580
|
-
quoteTargets: this.
|
|
581
|
-
channelTargets: this.
|
|
289
|
+
quoteTargets: this.quotes.size,
|
|
290
|
+
channelTargets: this.listeners.chatChannels.size,
|
|
582
291
|
});
|
|
583
|
-
this.
|
|
584
|
-
this.
|
|
585
|
-
this.
|
|
586
|
-
this.
|
|
587
|
-
this.chatChannelStateListeners.clear();
|
|
588
|
-
this.chatPresenceListeners.clear();
|
|
589
|
-
this.chatReactionsListeners.clear();
|
|
590
|
-
this.teamNotificationListeners.clear();
|
|
591
|
-
this.cloudEventListeners.clear();
|
|
592
|
-
this.quoteSubscriptions.clear();
|
|
593
|
-
this.quoteTargets.clear();
|
|
594
|
-
this.pendingQuoteSubscribes.clear();
|
|
595
|
-
this.pendingQuoteUnsubscribes.clear();
|
|
596
|
-
this.tapeListeners.clear();
|
|
597
|
-
this.scannerListeners.clear();
|
|
598
|
-
this.scannerSnapshots.clear();
|
|
599
|
-
if (this.quoteSubscriptionFlushTimer) {
|
|
600
|
-
clearTimeout(this.quoteSubscriptionFlushTimer);
|
|
601
|
-
this.quoteSubscriptionFlushTimer = null;
|
|
602
|
-
}
|
|
603
|
-
this.reconnectDelayMs = 1000;
|
|
292
|
+
this.listeners.clear();
|
|
293
|
+
this.features.clearListeners();
|
|
294
|
+
this.quotes.clear();
|
|
295
|
+
this.connection.resetBackoff();
|
|
604
296
|
this.teardown();
|
|
605
297
|
}
|
|
606
298
|
|
|
607
299
|
async handleSocketMessage(raw: string): Promise<void> {
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
parsed = JSON.parse(raw);
|
|
611
|
-
} catch (error) {
|
|
612
|
-
logFailure("cloud-socket", "WebSocket message decoding failed")(error);
|
|
613
|
-
return;
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
if (parsed?.type === "ready") {
|
|
617
|
-
recordServerClockSample(parsed.serverTime);
|
|
618
|
-
this.negotiateSocketFeatures(parsed.features);
|
|
619
|
-
if (parsed.user) {
|
|
620
|
-
cloudApiLog.info("websocket ready", {
|
|
621
|
-
emailVerified: parsed.user.emailVerified === true,
|
|
622
|
-
});
|
|
623
|
-
this.delegate.updateCurrentUserFromSocket(
|
|
624
|
-
parsed.user as Partial<AuthUser>,
|
|
625
|
-
);
|
|
626
|
-
}
|
|
627
|
-
this.emitConnection("ready");
|
|
628
|
-
return;
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
if (parsed?.type === "auth.unverified") {
|
|
632
|
-
cloudApiLog.warn("websocket marked unverified");
|
|
633
|
-
if (
|
|
634
|
-
this.delegate.isUsingWebSocketToken() &&
|
|
635
|
-
this.delegate.clearWebSocketTokenForFallback()
|
|
636
|
-
) {
|
|
637
|
-
this.reconnectDelayMs = 1000;
|
|
638
|
-
cloudApiLog.warn(
|
|
639
|
-
"cleared websocket token after auth rejection; falling back to session token",
|
|
640
|
-
);
|
|
641
|
-
this.teardown();
|
|
642
|
-
this.scheduleReconnect();
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
this.delegate.markCurrentUserUnverified();
|
|
646
|
-
if (this.quoteTargets.size > 0 || this.scannerListeners.size > 0 || this.tapeListeners.size > 0) {
|
|
647
|
-
return;
|
|
648
|
-
}
|
|
649
|
-
this.teardown();
|
|
650
|
-
return;
|
|
651
|
-
}
|
|
300
|
+
dispatchSocketFrame(raw, this.frameRoutes);
|
|
301
|
+
}
|
|
652
302
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
[]) {
|
|
661
|
-
listener(message);
|
|
662
|
-
}
|
|
663
|
-
return;
|
|
303
|
+
private handleReady(frame: SocketReadyFrame): void {
|
|
304
|
+
this.features.negotiate(this.connection.socket, frame.features);
|
|
305
|
+
if (frame.user) {
|
|
306
|
+
cloudApiLog.info("websocket ready", {
|
|
307
|
+
emailVerified: frame.user.emailVerified === true,
|
|
308
|
+
});
|
|
309
|
+
this.delegate.updateCurrentUserFromSocket(frame.user);
|
|
664
310
|
}
|
|
311
|
+
this.listeners.connection.emit("ready");
|
|
312
|
+
}
|
|
665
313
|
|
|
314
|
+
private handleUnverified(): void {
|
|
315
|
+
cloudApiLog.warn("websocket marked unverified");
|
|
666
316
|
if (
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
typeof parsed.data?.messageId === "string"
|
|
317
|
+
this.delegate.isUsingWebSocketToken() &&
|
|
318
|
+
this.delegate.clearWebSocketTokenForFallback()
|
|
670
319
|
) {
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
reactions: normalizeChatReactions(parsed.data.reactions),
|
|
675
|
-
};
|
|
676
|
-
for (const listener of this.chatReactionsListeners) {
|
|
677
|
-
listener(update);
|
|
678
|
-
}
|
|
679
|
-
return;
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
if (parsed?.type === "chat.notification" && parsed.data) {
|
|
683
|
-
const notification = normalizeChatNotification(
|
|
684
|
-
parsed.data as ChatNotification,
|
|
320
|
+
this.connection.resetBackoff();
|
|
321
|
+
cloudApiLog.warn(
|
|
322
|
+
"cleared websocket token after auth rejection; falling back to session token",
|
|
685
323
|
);
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
}
|
|
689
|
-
return;
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
if (parsed?.type === "chat.mentions_changed") {
|
|
693
|
-
for (const listener of this.chatMentionCandidatesListeners) listener();
|
|
694
|
-
return;
|
|
695
|
-
}
|
|
696
|
-
if (parsed?.type === "chat.channel_state") {
|
|
697
|
-
const state = normalizeChatChannelStateFrame(parsed.data);
|
|
698
|
-
if (state) {
|
|
699
|
-
for (const listener of this.chatChannelStateListeners) {
|
|
700
|
-
listener(state);
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
return;
|
|
704
|
-
}
|
|
705
|
-
|
|
706
|
-
if (parsed?.type === "team.notification" && parsed.data) {
|
|
707
|
-
const notification = normalizeTeamNotification(
|
|
708
|
-
parsed.data as TeamNotification,
|
|
709
|
-
);
|
|
710
|
-
for (const listener of this.teamNotificationListeners) {
|
|
711
|
-
listener(notification);
|
|
712
|
-
}
|
|
713
|
-
return;
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
if (
|
|
717
|
-
parsed?.type === "chat.presence" &&
|
|
718
|
-
typeof parsed.onlineCount === "number"
|
|
719
|
-
) {
|
|
720
|
-
for (const listener of this.chatPresenceListeners) {
|
|
721
|
-
listener(parsed.onlineCount);
|
|
722
|
-
}
|
|
723
|
-
return;
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
if (parsed?.type === "tape.snapshot" && parsed.data && typeof parsed.data.symbol === "string" && typeof parsed.data.exchange === "string") {
|
|
727
|
-
const entry = this.tapeListeners.get(marketKey(parsed.data.symbol, parsed.data.exchange));
|
|
728
|
-
for (const listener of entry?.listeners ?? []) listener({ type: "data", payload: parsed.data });
|
|
729
|
-
return;
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
const scannerKind =
|
|
733
|
-
typeof parsed?.type === "string"
|
|
734
|
-
? SCANNER_MESSAGE_KINDS[parsed.type]
|
|
735
|
-
: undefined;
|
|
736
|
-
if (scannerKind) {
|
|
737
|
-
const { type: _type, ...payload } = parsed;
|
|
738
|
-
this.emitScannerEvent(scannerKind, { type: "data", payload });
|
|
739
|
-
return;
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
if (parsed?.type === "scanner.denied") {
|
|
743
|
-
const denied = SCANNER_MESSAGE_KINDS[`scanner.${parsed.scanner}`];
|
|
744
|
-
if (denied) {
|
|
745
|
-
this.emitScannerEvent(denied, {
|
|
746
|
-
type: "denied",
|
|
747
|
-
reason:
|
|
748
|
-
typeof parsed.reason === "string" ? parsed.reason : "pro_required",
|
|
749
|
-
});
|
|
750
|
-
}
|
|
324
|
+
this.teardown();
|
|
325
|
+
this.connection.scheduleReconnect();
|
|
751
326
|
return;
|
|
752
327
|
}
|
|
753
|
-
|
|
754
|
-
if (
|
|
755
|
-
this.dispatchMarketQuote(parsed);
|
|
328
|
+
this.delegate.markCurrentUserUnverified();
|
|
329
|
+
if (this.hasMarketStreams()) {
|
|
756
330
|
return;
|
|
757
331
|
}
|
|
758
|
-
|
|
759
|
-
if (parsed?.type === "market.quotes") {
|
|
760
|
-
recordServerClockSample(parsed.at);
|
|
761
|
-
if (!Array.isArray(parsed.quotes)) return;
|
|
762
|
-
// One synchronous pass: every item lands before the next data frame.
|
|
763
|
-
for (const item of parsed.quotes) this.dispatchMarketQuote(item);
|
|
764
|
-
return;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
if (typeof parsed?.type === "string") {
|
|
768
|
-
const listeners = this.cloudEventListeners.get(parsed.type);
|
|
769
|
-
if (listeners && listeners.size > 0) {
|
|
770
|
-
for (const listener of listeners) {
|
|
771
|
-
listener(parsed.data);
|
|
772
|
-
}
|
|
773
|
-
return;
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
/** Delivers one market.quote frame, or one item of a market.quotes batch, to its listeners. */
|
|
779
|
-
private dispatchMarketQuote(frame: any): void {
|
|
780
|
-
if (!frame?.quote || typeof frame.symbol !== "string") return;
|
|
781
|
-
const subscriptions = this.quoteSubscriptions.get(marketKey(frame.symbol, frame.exchange));
|
|
782
|
-
if (!subscriptions) return;
|
|
783
|
-
const quote: CloudQuotePayload = {
|
|
784
|
-
...(frame.quote as CloudQuotePayload),
|
|
785
|
-
...(frame.delivery === "stream" || frame.delivery === "poll"
|
|
786
|
-
? { delivery: frame.delivery }
|
|
787
|
-
: {}),
|
|
788
|
-
...(typeof frame.stale === "boolean" ? { stale: frame.stale } : {}),
|
|
789
|
-
};
|
|
790
|
-
for (const subscription of subscriptions.values()) {
|
|
791
|
-
subscription.listener(subscription.target, quote);
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
private negotiateSocketFeatures(offered: unknown): void {
|
|
796
|
-
this.recordOfferedFeatures(offered);
|
|
797
|
-
if (!Array.isArray(offered) || this.featuresRequestedFor === this.ws) return;
|
|
798
|
-
const features = CLIENT_SOCKET_FEATURES.filter((feature) => offered.includes(feature));
|
|
799
|
-
if (features.length === 0) return;
|
|
800
|
-
this.featuresRequestedFor = this.ws;
|
|
801
|
-
this.sendSocketMessage({ type: "client.features", features });
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
private recordOfferedFeatures(offered: unknown): void {
|
|
805
|
-
const next = new Set(
|
|
806
|
-
Array.isArray(offered)
|
|
807
|
-
? offered.filter((feature): feature is string => typeof feature === "string")
|
|
808
|
-
: [],
|
|
809
|
-
);
|
|
810
|
-
const changed = next.size !== this.offeredFeatures.size
|
|
811
|
-
|| [...next].some((feature) => !this.offeredFeatures.has(feature));
|
|
812
|
-
this.offeredFeatures = next;
|
|
813
|
-
// Perpetual listings held back since the socket opened go out once this connection's server offers them.
|
|
814
|
-
const perpsOffered = next.has(MARKET_PERPS_FEATURE) ? this.ws : null;
|
|
815
|
-
if (perpsOffered !== this.perpsOfferedOn) {
|
|
816
|
-
this.perpsOfferedOn = perpsOffered;
|
|
817
|
-
this.streamedPerps.clear();
|
|
818
|
-
this.syncPerpSubscriptions();
|
|
819
|
-
}
|
|
820
|
-
if (!changed) return;
|
|
821
|
-
for (const listener of this.offeredFeatureListeners) listener();
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
/**
|
|
825
|
-
* The ws(s) form of the API base URL, or null when the base is not an
|
|
826
|
-
* http(s) URL. The web build derives it from `location.origin`, which is the
|
|
827
|
-
* string "null" on an opaque page, and `null/api` must not become a socket URL.
|
|
828
|
-
*/
|
|
829
|
-
private getWebSocketBaseUrl(): string | null {
|
|
830
|
-
const baseUrl = this.delegate.getBaseUrl();
|
|
831
|
-
if (!/^https?:\/\//.test(baseUrl)) return null;
|
|
832
|
-
const wsProtocol = baseUrl.startsWith("https") ? "wss" : "ws";
|
|
833
|
-
return baseUrl.replace(/^https?/, wsProtocol);
|
|
332
|
+
this.teardown();
|
|
834
333
|
}
|
|
835
334
|
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
): void {
|
|
840
|
-
this.scannerSnapshots.set(scanner, event);
|
|
841
|
-
for (const listener of this.scannerListeners.get(scanner) ?? []) {
|
|
842
|
-
listener(event);
|
|
843
|
-
}
|
|
335
|
+
/** Quotes, scanners and tapes stream signed out too, so they keep the connection without a verified account. */
|
|
336
|
+
private hasMarketStreams(): boolean {
|
|
337
|
+
return this.quotes.size > 0 || this.listeners.scanners.size > 0 || this.listeners.tape.size > 0;
|
|
844
338
|
}
|
|
845
339
|
|
|
846
340
|
private shouldKeepSocketOpen(): boolean {
|
|
847
|
-
if (this.
|
|
848
|
-
return true;
|
|
341
|
+
if (this.hasMarketStreams()) return true;
|
|
849
342
|
return (
|
|
850
343
|
this.delegate.hasSessionCredential() &&
|
|
851
344
|
this.delegate.hasVerifiedUser() &&
|
|
852
|
-
(this.
|
|
853
|
-
this.
|
|
854
|
-
this.
|
|
345
|
+
(this.listeners.chatChannels.size > 0 ||
|
|
346
|
+
this.listeners.teamNotifications.size > 0 ||
|
|
347
|
+
this.listeners.cloudEvents.size > 0)
|
|
855
348
|
);
|
|
856
349
|
}
|
|
857
350
|
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
if (!socketBaseUrl) {
|
|
863
|
-
this.failSocketOpen(`Not a usable Gloom Cloud URL: ${this.delegate.getBaseUrl()}`);
|
|
864
|
-
return;
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
const socketToken = this.delegate.getSocketAuthToken();
|
|
868
|
-
const usingWebSocketToken = this.delegate.isUsingWebSocketToken();
|
|
869
|
-
const url = socketToken
|
|
870
|
-
? `${socketBaseUrl}/cloud/ws?token=${encodeURIComponent(socketToken)}`
|
|
871
|
-
: `${socketBaseUrl}/cloud/ws`;
|
|
872
|
-
cloudApiLog.info("open websocket", {
|
|
873
|
-
hasToken: !!socketToken,
|
|
874
|
-
tokenSource: usingWebSocketToken ? "websocket" : "session",
|
|
875
|
-
quoteTargets: this.quoteTargets.size,
|
|
876
|
-
channelTargets: this.channelListeners.size,
|
|
877
|
-
});
|
|
878
|
-
this.health.reportSocketState(
|
|
879
|
-
GLOOM_CLOUD_SOCKET_CONNECTION_ID,
|
|
880
|
-
"connecting",
|
|
881
|
-
socketBaseUrl,
|
|
882
|
-
);
|
|
883
|
-
let ws: WebSocket;
|
|
884
|
-
try {
|
|
885
|
-
ws = new WebSocket(url);
|
|
886
|
-
} catch (error) {
|
|
887
|
-
this.failSocketOpen(error instanceof Error ? error.message : String(error));
|
|
888
|
-
return;
|
|
889
|
-
}
|
|
890
|
-
this.ws = ws;
|
|
891
|
-
let opened = false;
|
|
892
|
-
// A link that swallows the handshake never says so: the attempt is dropped and tried again.
|
|
893
|
-
this.connectTimer = setTimeout(() => {
|
|
894
|
-
this.connectTimer = null;
|
|
895
|
-
if (this.ws === ws) this.dropUnansweredSocket(ws, "Connecting timed out");
|
|
896
|
-
}, SOCKET_CONNECT_TIMEOUT_MS);
|
|
897
|
-
|
|
898
|
-
ws.onopen = () => {
|
|
899
|
-
if (this.ws !== ws) return;
|
|
900
|
-
opened = true;
|
|
901
|
-
this.watchSilence();
|
|
902
|
-
this.delegate.onServiceAnswered?.();
|
|
903
|
-
cloudApiLog.info("websocket open");
|
|
904
|
-
this.health.reportSocketState(
|
|
905
|
-
GLOOM_CLOUD_SOCKET_CONNECTION_ID,
|
|
906
|
-
"open",
|
|
907
|
-
socketBaseUrl,
|
|
908
|
-
);
|
|
909
|
-
this.reconnectDelayMs = 1000;
|
|
910
|
-
// The full set goes out now; queued diffs from before the open are part of it.
|
|
911
|
-
this.pendingQuoteSubscribes.clear();
|
|
912
|
-
this.pendingQuoteUnsubscribes.clear();
|
|
913
|
-
this.flushSubscriptions();
|
|
914
|
-
};
|
|
915
|
-
|
|
916
|
-
ws.onmessage = (event) => {
|
|
917
|
-
if (this.ws !== ws) return;
|
|
918
|
-
this.lastFrameAt = Date.now();
|
|
919
|
-
this.pingedAt = null;
|
|
920
|
-
this.delegate.onServiceAnswered?.();
|
|
921
|
-
void this.handleSocketMessage(String(event.data));
|
|
922
|
-
};
|
|
923
|
-
|
|
924
|
-
ws.onclose = (event) => {
|
|
925
|
-
const activeSocket = this.ws === ws;
|
|
926
|
-
if (this.ws === ws) {
|
|
927
|
-
this.ws = null;
|
|
928
|
-
this.stopWatching();
|
|
929
|
-
this.emitTapeStatus({ type: "disconnected", reason: "Stream disconnected; observed window may contain gaps" });
|
|
930
|
-
}
|
|
931
|
-
const closeEvent = event as CloseEvent | undefined;
|
|
932
|
-
cloudApiLog.warn("websocket closed", {
|
|
933
|
-
quoteTargets: this.quoteTargets.size,
|
|
934
|
-
channelTargets: this.channelListeners.size,
|
|
935
|
-
code: closeEvent?.code,
|
|
936
|
-
reason: closeEvent?.reason,
|
|
937
|
-
tokenSource: usingWebSocketToken ? "websocket" : "session",
|
|
938
|
-
});
|
|
939
|
-
if (!activeSocket) return;
|
|
940
|
-
this.emitConnection("closed");
|
|
941
|
-
this.health.reportSocketState(
|
|
942
|
-
GLOOM_CLOUD_SOCKET_CONNECTION_ID,
|
|
943
|
-
"closed",
|
|
944
|
-
closeEvent?.reason ||
|
|
945
|
-
(closeEvent?.code ? `Closed (${closeEvent.code})` : "Socket closed"),
|
|
946
|
-
);
|
|
947
|
-
if (
|
|
948
|
-
usingWebSocketToken &&
|
|
949
|
-
this.delegate.clearWebSocketTokenForFallback()
|
|
950
|
-
) {
|
|
951
|
-
this.reconnectDelayMs = 1000;
|
|
952
|
-
cloudApiLog.warn(
|
|
953
|
-
"cleared websocket token after socket close; falling back to session token",
|
|
954
|
-
);
|
|
955
|
-
}
|
|
956
|
-
if (!this.shouldKeepSocketOpen()) return;
|
|
957
|
-
this.scheduleReconnect();
|
|
958
|
-
};
|
|
959
|
-
|
|
960
|
-
ws.onerror = () => {
|
|
961
|
-
if (this.ws !== ws) return;
|
|
962
|
-
// A socket that was open, cut by a server restart or a proxy, fires its
|
|
963
|
-
// error just before its close: the close reports it, so the stream gets
|
|
964
|
-
// the grace a clean close does. One that never opened is a failed
|
|
965
|
-
// connect, and one open but silent is dropped by the ping check.
|
|
966
|
-
if (opened) return;
|
|
967
|
-
this.health.reportSocketState(
|
|
968
|
-
GLOOM_CLOUD_SOCKET_CONNECTION_ID,
|
|
969
|
-
"error",
|
|
970
|
-
"WebSocket error",
|
|
971
|
-
);
|
|
972
|
-
// Reconnect is handled by onclose.
|
|
973
|
-
};
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
/** From the open: the connection's silence is checked until it closes. */
|
|
977
|
-
private watchSilence(): void {
|
|
978
|
-
this.stopWatching();
|
|
979
|
-
this.lastFrameAt = Date.now();
|
|
980
|
-
this.pingedAt = null;
|
|
981
|
-
this.silenceTimer = setInterval(() => this.checkSilence(), SOCKET_SILENCE_CHECK_MS);
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
private stopWatching(): void {
|
|
985
|
-
if (this.connectTimer) clearTimeout(this.connectTimer);
|
|
986
|
-
if (this.silenceTimer) clearInterval(this.silenceTimer);
|
|
987
|
-
this.connectTimer = null;
|
|
988
|
-
this.silenceTimer = null;
|
|
989
|
-
}
|
|
990
|
-
|
|
991
|
-
/**
|
|
992
|
-
* A connection that went quiet is pinged; one that leaves the ping
|
|
993
|
-
* unanswered for SOCKET_PING_ANSWER_MS is half open, and is dropped and
|
|
994
|
-
* opened again. Anything it sends answers the ping.
|
|
995
|
-
*/
|
|
996
|
-
private checkSilence(): void {
|
|
997
|
-
const ws = this.ws;
|
|
998
|
-
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
|
999
|
-
const now = Date.now();
|
|
1000
|
-
if (this.pingedAt != null) {
|
|
1001
|
-
if (now - this.pingedAt >= SOCKET_PING_ANSWER_MS) this.dropUnansweredSocket(ws, "No answer from the stream");
|
|
1002
|
-
return;
|
|
1003
|
-
}
|
|
1004
|
-
if (now - this.lastFrameAt >= SOCKET_QUIET_PING_MS) {
|
|
1005
|
-
this.pingedAt = now;
|
|
1006
|
-
this.sendFrame({ type: "ping" });
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
/**
|
|
1011
|
-
* Gives up on a connection that never opened or went silent: what it was
|
|
1012
|
-
* carrying is reported as interrupted (the stream's health turns to error,
|
|
1013
|
-
* which marks its prices stale), and a new one is opened with the backoff.
|
|
1014
|
-
* Its close, if it ever comes, is for a socket no longer in use.
|
|
1015
|
-
*/
|
|
1016
|
-
private dropUnansweredSocket(ws: WebSocket, reason: string): void {
|
|
1017
|
-
if (this.ws !== ws) return;
|
|
1018
|
-
this.ws = null;
|
|
1019
|
-
this.stopWatching();
|
|
1020
|
-
cloudApiLog.warn("websocket unanswered; reconnecting", { reason, quoteTargets: this.quoteTargets.size });
|
|
1021
|
-
try {
|
|
1022
|
-
ws.close();
|
|
1023
|
-
} catch {
|
|
1024
|
-
// Intentional ignore: a socket that cannot close is dropped all the same.
|
|
1025
|
-
}
|
|
1026
|
-
this.emitTapeStatus({ type: "disconnected", reason: "Stream disconnected; observed window may contain gaps" });
|
|
1027
|
-
this.emitConnection("closed");
|
|
1028
|
-
this.health.reportSocketState(GLOOM_CLOUD_SOCKET_CONNECTION_ID, "error", reason);
|
|
1029
|
-
this.scheduleReconnect();
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
/**
|
|
1033
|
-
* A socket that could not be constructed is an error to show, not to throw:
|
|
1034
|
-
* ensureSocket runs from effects and timers nobody awaits. The reconnect
|
|
1035
|
-
* backoff retries it, so a URL that never works settles at the slowest delay.
|
|
1036
|
-
*/
|
|
1037
|
-
private failSocketOpen(reason: string): void {
|
|
1038
|
-
// The reason can carry the socket URL with its token, so only the health detail keeps it.
|
|
1039
|
-
cloudApiLog.warn("websocket could not be opened");
|
|
1040
|
-
this.health.reportSocketState(GLOOM_CLOUD_SOCKET_CONNECTION_ID, "error", reason);
|
|
1041
|
-
this.scheduleReconnect();
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
private scheduleReconnect(): void {
|
|
1045
|
-
if (this.reconnectTimer || !this.shouldKeepSocketOpen()) return;
|
|
1046
|
-
// Jittered so clients dropped together by a server restart do not all
|
|
1047
|
-
// come back in the same instant.
|
|
1048
|
-
const delay = Math.round(this.reconnectDelayMs * (0.5 + Math.random()));
|
|
1049
|
-
this.reconnectTimer = setTimeout(() => {
|
|
1050
|
-
this.reconnectTimer = null;
|
|
1051
|
-
this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, 10_000);
|
|
1052
|
-
this.ensureSocket();
|
|
1053
|
-
}, delay);
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
private sendSocketMessage(payload: unknown): void {
|
|
1057
|
-
if (this.ws?.readyState !== WebSocket.OPEN) return;
|
|
1058
|
-
if (
|
|
1059
|
-
payload &&
|
|
1060
|
-
typeof payload === "object" &&
|
|
1061
|
-
"type" in (payload as Record<string, unknown>)
|
|
1062
|
-
) {
|
|
1063
|
-
const type = (payload as Record<string, unknown>).type;
|
|
1064
|
-
if (
|
|
1065
|
-
type === "market.subscribe" ||
|
|
1066
|
-
type === "market.unsubscribe" ||
|
|
1067
|
-
type === "chat.subscribe" ||
|
|
1068
|
-
type === "chat.unsubscribe" ||
|
|
1069
|
-
type === "scanner.subscribe" ||
|
|
1070
|
-
type === "scanner.unsubscribe"
|
|
1071
|
-
) {
|
|
1072
|
-
cloudApiLog.info("send websocket message", previewLongLists(payload as Record<string, unknown>));
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
this.ws.send(JSON.stringify(payload));
|
|
1076
|
-
}
|
|
1077
|
-
|
|
1078
|
-
private flushSubscriptions(): void {
|
|
1079
|
-
if (this.ws?.readyState !== WebSocket.OPEN) return;
|
|
1080
|
-
|
|
1081
|
-
for (const channelId of this.channelListeners.keys()) {
|
|
1082
|
-
this.sendSocketMessage({ type: "chat.subscribe", channelId });
|
|
1083
|
-
}
|
|
1084
|
-
|
|
1085
|
-
for (const entry of this.tapeListeners.values()) {
|
|
1086
|
-
this.sendSocketMessage({ type: "tape.subscribe", symbol: entry.symbol, exchange: entry.exchange });
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
for (const scanner of this.scannerListeners.keys()) {
|
|
1090
|
-
this.sendSocketMessage({ type: "scanner.subscribe", scanner });
|
|
1091
|
-
}
|
|
1092
|
-
|
|
1093
|
-
const targets = [...this.quoteTargets.values()].filter((target) => !isPerpTarget(target));
|
|
1094
|
-
if (targets.length > 0) {
|
|
1095
|
-
this.sendSocketMessage({
|
|
1096
|
-
type: "market.subscribe",
|
|
1097
|
-
symbols: targets.map((target) =>
|
|
1098
|
-
this.serializeQuoteStreamTarget(target),
|
|
1099
|
-
),
|
|
1100
|
-
});
|
|
1101
|
-
}
|
|
1102
|
-
this.streamedPerps.clear();
|
|
1103
|
-
this.syncPerpSubscriptions();
|
|
1104
|
-
}
|
|
1105
|
-
|
|
1106
|
-
/**
|
|
1107
|
-
* Streams the perpetual listings within the budget, once this connection's server offers them: the best ranked
|
|
1108
|
-
* across every pane. One that falls out is unsubscribed; one whose target changed (`changed`) is sent again.
|
|
1109
|
-
*/
|
|
1110
|
-
private syncPerpSubscriptions(changed: ReadonlySet<string> = new Set()): void {
|
|
1111
|
-
const ws = this.ws;
|
|
1112
|
-
if (!ws || ws.readyState !== WebSocket.OPEN || this.perpsOfferedOn !== ws) return;
|
|
1113
|
-
const wanted = new Map(
|
|
1114
|
-
[...this.quoteTargets]
|
|
1115
|
-
.filter(([, target]) => isPerpTarget(target))
|
|
1116
|
-
.sort(([, left], [, right]) => perpStreamRank(right) - perpStreamRank(left) || (right.weight ?? 0) - (left.weight ?? 0))
|
|
1117
|
-
.slice(0, PERP_STREAM_BUDGET),
|
|
1118
|
-
);
|
|
1119
|
-
const unsubscribes = [...this.streamedPerps].filter(([key]) => !wanted.has(key)).map(([, target]) => target);
|
|
1120
|
-
const subscribes = [...wanted].filter(([key]) => !this.streamedPerps.has(key) || changed.has(key)).map(([, target]) => target);
|
|
1121
|
-
this.streamedPerps = wanted;
|
|
1122
|
-
if (unsubscribes.length > 0) {
|
|
1123
|
-
this.sendSocketMessage({ type: "market.unsubscribe", symbols: unsubscribes.map((target) => this.serializeQuoteStreamTarget(target)) });
|
|
1124
|
-
}
|
|
1125
|
-
if (subscribes.length > 0) {
|
|
1126
|
-
this.sendSocketMessage({ type: "market.subscribe", symbols: subscribes.map((target) => this.serializeQuoteStreamTarget(target)) });
|
|
351
|
+
/** A listener left: the connection closes once nothing needs it. */
|
|
352
|
+
private releaseSocket(): void {
|
|
353
|
+
if (!this.shouldKeepSocketOpen()) {
|
|
354
|
+
this.teardown();
|
|
1127
355
|
}
|
|
1128
356
|
}
|
|
1129
357
|
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
}, QUOTE_SUBSCRIPTION_FLUSH_MS);
|
|
1136
|
-
}
|
|
358
|
+
/** A connection opened: every subscription goes out on it, chat, tapes and scanners first, then quotes. */
|
|
359
|
+
private replaySubscriptions(): void {
|
|
360
|
+
// The full set goes out now; queued diffs from before the open are part of it.
|
|
361
|
+
this.quotes.dropPending();
|
|
362
|
+
if (!this.connection.openSocket()) return;
|
|
1137
363
|
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
const key = marketKey(target.symbol, target.exchange);
|
|
1141
|
-
this.pendingQuoteUnsubscribes.delete(key);
|
|
1142
|
-
this.pendingQuoteSubscribes.set(key, target);
|
|
364
|
+
for (const channelId of this.listeners.chatChannels.keys()) {
|
|
365
|
+
this.connection.send({ type: "chat.subscribe", channelId });
|
|
1143
366
|
}
|
|
1144
|
-
this.scheduleQuoteSubscriptionFlush();
|
|
1145
|
-
}
|
|
1146
367
|
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
const key = marketKey(target.symbol, target.exchange);
|
|
1150
|
-
this.pendingQuoteSubscribes.delete(key);
|
|
1151
|
-
this.pendingQuoteUnsubscribes.set(key, target);
|
|
368
|
+
for (const market of this.listeners.tape.markets()) {
|
|
369
|
+
this.connection.send({ type: "tape.subscribe", symbol: market.symbol, exchange: market.exchange });
|
|
1152
370
|
}
|
|
1153
|
-
this.scheduleQuoteSubscriptionFlush();
|
|
1154
|
-
}
|
|
1155
371
|
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
this.pendingQuoteSubscribes.clear();
|
|
1159
|
-
this.pendingQuoteUnsubscribes.clear();
|
|
1160
|
-
return;
|
|
1161
|
-
}
|
|
1162
|
-
const subscribes = [...this.pendingQuoteSubscribes.values()].filter((target) => !isPerpTarget(target));
|
|
1163
|
-
const unsubscribes = [...this.pendingQuoteUnsubscribes.values()].filter((target) => !isPerpTarget(target));
|
|
1164
|
-
const perpsChanged = [...this.pendingQuoteSubscribes]
|
|
1165
|
-
.filter(([, target]) => isPerpTarget(target))
|
|
1166
|
-
.map(([key]) => key);
|
|
1167
|
-
const perpsMoved = perpsChanged.length > 0 || [...this.pendingQuoteUnsubscribes.values()].some(isPerpTarget);
|
|
1168
|
-
this.pendingQuoteSubscribes.clear();
|
|
1169
|
-
this.pendingQuoteUnsubscribes.clear();
|
|
1170
|
-
if (perpsMoved) this.syncPerpSubscriptions(new Set(perpsChanged));
|
|
1171
|
-
if (unsubscribes.length > 0) {
|
|
1172
|
-
this.sendSocketMessage({
|
|
1173
|
-
type: "market.unsubscribe",
|
|
1174
|
-
symbols: unsubscribes.map((target) =>
|
|
1175
|
-
this.serializeQuoteStreamTarget(target),
|
|
1176
|
-
),
|
|
1177
|
-
});
|
|
1178
|
-
}
|
|
1179
|
-
if (subscribes.length > 0) {
|
|
1180
|
-
this.sendSocketMessage({
|
|
1181
|
-
type: "market.subscribe",
|
|
1182
|
-
symbols: subscribes.map((target) =>
|
|
1183
|
-
this.serializeQuoteStreamTarget(target),
|
|
1184
|
-
),
|
|
1185
|
-
});
|
|
372
|
+
for (const scanner of this.listeners.scanners.keys()) {
|
|
373
|
+
this.connection.send({ type: "scanner.subscribe", scanner });
|
|
1186
374
|
}
|
|
1187
|
-
}
|
|
1188
375
|
|
|
1189
|
-
|
|
1190
|
-
target: QuoteStreamTarget,
|
|
1191
|
-
): QuoteStreamTarget {
|
|
1192
|
-
return {
|
|
1193
|
-
symbol: target.symbol,
|
|
1194
|
-
exchange: target.exchange ?? "",
|
|
1195
|
-
...(target.surface ? { surface: target.surface } : {}),
|
|
1196
|
-
...(target.visible ? { visible: true } : {}),
|
|
1197
|
-
...(target.selected ? { selected: true } : {}),
|
|
1198
|
-
...(Number.isFinite(target.weight) ? { weight: target.weight } : {}),
|
|
1199
|
-
};
|
|
1200
|
-
}
|
|
1201
|
-
|
|
1202
|
-
private areQuoteStreamTargetsEquivalent(
|
|
1203
|
-
left: QuoteStreamTarget,
|
|
1204
|
-
right: QuoteStreamTarget,
|
|
1205
|
-
): boolean {
|
|
1206
|
-
return (
|
|
1207
|
-
JSON.stringify(this.serializeQuoteStreamTarget(left)) ===
|
|
1208
|
-
JSON.stringify(this.serializeQuoteStreamTarget(right))
|
|
1209
|
-
);
|
|
376
|
+
this.quotes.replay();
|
|
1210
377
|
}
|
|
1211
378
|
}
|