@gloom-sh/terminal 0.20.10 → 0.20.12
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 +2 -1
- package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
- package/src/api-client/awards.ts +16 -0
- package/src/api-client/central-bank-rates.ts +5 -0
- package/src/api-client/data.ts +55 -2
- package/src/api-client/index.ts +18 -1
- package/src/api-client/request.ts +86 -3
- package/src/api-client/socket-connection.ts +366 -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 +168 -983
- package/src/api-client/supply-chain-graph.ts +4 -2
- package/src/api-client/supply-chain.ts +8 -0
- package/src/api-client/types/econ.ts +10 -7
- package/src/api-client/types/filings-and-calls.ts +8 -0
- package/src/app/global-shortcuts.ts +2 -1
- package/src/app/keybindings/actions.ts +19 -0
- package/src/app/pane-runtime/index.tsx +18 -3
- package/src/app/pane-runtime/layout-placement.ts +63 -0
- package/src/app/pane-runtime/ticker-open-runtime.ts +10 -2
- 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/capabilities/chart-series.ts +4 -1
- package/src/cli/board-coins.ts +10 -1
- package/src/cli/commands/crypto-hints.ts +3 -2
- package/src/cli/commands/fred-series.ts +0 -54
- package/src/cli/commands/market.ts +209 -31
- package/src/cli/commands/overview.ts +47 -14
- package/src/cli/commands/search.ts +37 -8
- package/src/cli/commands/ticker.ts +15 -4
- package/src/cli/desktop-pane-shot.ts +27 -2
- package/src/cli/fx-quote-rate.ts +1 -1
- package/src/cli/glossary.ts +14 -5
- package/src/cli/history-catalog-series.ts +85 -0
- package/src/cli/index.ts +1 -1
- package/src/cli/list-progress.ts +45 -0
- package/src/cli/listing-arg.ts +71 -7
- package/src/cli/name-entries.ts +8 -4
- package/src/cli/not-a-ticker.ts +2 -2
- package/src/cli/pane-functions/freshness.ts +50 -3
- package/src/cli/pane-functions/index.ts +7 -4
- package/src/cli/pane-functions/market-session.ts +66 -14
- package/src/cli/pane-functions/options.ts +5 -0
- package/src/cli/pane-functions/resolver.ts +9 -2
- package/src/cli/pane-functions/screenshot-assessment.ts +28 -3
- package/src/cli/pane-functions/screenshot-types.ts +6 -0
- package/src/cli/quote-answer.ts +49 -10
- package/src/cli/quote-list-reads.ts +87 -0
- package/src/cli/report-tables.ts +70 -13
- package/src/cli/result.ts +24 -2
- package/src/cli/symbol-list.ts +31 -4
- package/src/cli/terminal-code-hints.ts +83 -0
- package/src/cli/ticker-resolution.ts +2 -1
- package/src/cli/treasury-yields.ts +5 -0
- 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/action-runtime.ts +2 -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/routing/launch-request.ts +2 -1
- package/src/components/command-bar/routing/navigation-state.ts +4 -2
- package/src/components/command-bar/workflow/types.ts +6 -0
- 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/view.tsx +33 -6
- package/src/components/form-modal/content.tsx +10 -0
- package/src/components/index.ts +1 -1
- package/src/components/layout/detached-pane-shell.tsx +3 -0
- package/src/components/layout/double-escape-close.ts +34 -3
- package/src/components/layout/floating-pane.tsx +10 -4
- package/src/components/layout/pane/cycle-order.ts +66 -2
- package/src/components/layout/pane/footer/index.tsx +25 -11
- package/src/components/layout/pane/footer/model.ts +62 -20
- package/src/components/layout/pane/header.tsx +140 -31
- package/src/components/layout/pane/sidebar.tsx +138 -20
- package/src/components/layout/pane/status-footer.ts +3 -1
- package/src/components/layout/shell/active-drag.ts +18 -13
- package/src/components/layout/shell/drag/magnets.ts +34 -18
- package/src/components/layout/shell/drag/runtime.ts +5 -0
- package/src/components/layout/shell/index.tsx +25 -0
- package/src/components/layout/shell/menu.ts +9 -0
- package/src/components/layout/shell/pane/actions.ts +36 -0
- package/src/components/layout/shell/pane/management-shortcuts.ts +27 -3
- package/src/components/layout/shell/pane-occlusion.ts +40 -0
- package/src/components/layout/shell/shortcuts.ts +17 -1
- package/src/components/layout/shell/terminal-pointer-runtime.ts +39 -6
- package/src/components/layout/shell/window-mode/index.ts +5 -16
- package/src/components/layout/shell/window-mode/overlays.tsx +3 -1
- package/src/components/market-board/index.tsx +14 -5
- package/src/components/metric-treemap/index.tsx +3 -1
- package/src/components/ticker/list-table-view.tsx +5 -0
- package/src/components/ui/button.tsx +48 -4
- package/src/components/ui/data-table/column-order.ts +180 -0
- package/src/components/ui/data-table/index.tsx +12 -1
- package/src/components/ui/data-table/opentui/index.tsx +291 -32
- 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/inline-quick-add.tsx +19 -3
- package/src/components/ui/list-view.tsx +11 -5
- package/src/components/ui/query-bar.tsx +16 -1
- package/src/components/ui/selection-fill.ts +39 -0
- package/src/components/ui/table-layout.ts +120 -0
- package/src/core/state/app/layout-reducer.ts +2 -1
- package/src/core/state/app/pane-choices.ts +68 -0
- package/src/core/state/app/state.ts +14 -6
- package/src/core/state/app/types.ts +8 -0
- package/src/docs/snapshot.json +3 -2
- package/src/i18n/es.ts +2 -0
- package/src/i18n/ja.ts +2 -0
- package/src/i18n/ko.ts +2 -0
- package/src/i18n/zh-cn.ts +2 -0
- package/src/i18n/zh-tw.ts +2 -0
- package/src/layout/pane-manager/dock-tree.ts +19 -0
- package/src/layout/pane-manager/index.ts +3 -0
- package/src/market-data/coordinator/index.ts +4 -3
- package/src/market-data/coordinator/quotes.ts +12 -4
- package/src/market-data/market/freshness.ts +33 -0
- package/src/market-data/market/status.ts +5 -1
- package/src/market-data/quotes/contributions.ts +10 -0
- package/src/market-data/quotes/freshness.ts +31 -0
- package/src/market-data/quotes/live-valuation.ts +32 -5
- package/src/market-data/quotes/regular-session-valuation.ts +1 -1
- package/src/market-data/quotes/resolution.ts +4 -0
- package/src/market-data/quotes/time.ts +0 -14
- package/src/plugins/builtin/account-management/index.tsx +1 -0
- package/src/plugins/builtin/awards/detail.tsx +12 -4
- package/src/plugins/builtin/awards/headless.ts +29 -8
- package/src/plugins/builtin/awards/model.ts +36 -2
- package/src/plugins/builtin/awards/pane.tsx +7 -4
- package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
- package/src/plugins/builtin/broker-manager/index.tsx +7 -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/broker-trading/index.tsx +1 -1
- package/src/plugins/builtin/central-bank-rates/headless.ts +6 -6
- package/src/plugins/builtin/central-bank-rates/index.tsx +1 -1
- package/src/plugins/builtin/central-bank-rates/model.ts +21 -3
- package/src/plugins/builtin/central-bank-rates/pane.tsx +15 -5
- package/src/plugins/builtin/chart-composer/headless.ts +5 -1
- package/src/plugins/builtin/chart-composer/pane.tsx +1 -0
- package/src/plugins/builtin/chat/content/handle-prompt.tsx +4 -0
- package/src/plugins/builtin/chat/controller/realtime.ts +17 -1
- package/src/plugins/builtin/chat/message/terminal.tsx +4 -1
- package/src/plugins/builtin/chat/sidebar.tsx +35 -19
- package/src/plugins/builtin/cloud/askg/pane.tsx +4 -0
- package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
- package/src/plugins/builtin/cloud/plugin.tsx +1 -0
- package/src/plugins/builtin/cloud/team/module.tsx +1 -0
- package/src/plugins/builtin/cloud/thesis/detail.tsx +9 -4
- package/src/plugins/builtin/commodity-balances/pane.tsx +13 -5
- package/src/plugins/builtin/company-kpis/model.ts +3 -3
- package/src/plugins/builtin/connections/index.ts +1 -0
- package/src/plugins/builtin/credit-boards/cdx-pane.tsx +9 -5
- package/src/plugins/builtin/credit-boards/client.ts +5 -0
- package/src/plugins/builtin/credit-boards/headless.ts +1 -6
- package/src/plugins/builtin/credit-boards/model.ts +0 -6
- package/src/plugins/builtin/credit-boards/series.ts +19 -8
- package/src/plugins/builtin/credit-boards/sovr-pane.tsx +9 -5
- package/src/plugins/builtin/crypto-etf-flows/headless.ts +23 -13
- package/src/plugins/builtin/crypto-etf-flows/pane.tsx +8 -3
- package/src/plugins/builtin/debt-maturities/headless.ts +16 -7
- package/src/plugins/builtin/debt-maturities/model.ts +9 -15
- package/src/plugins/builtin/debt-maturities/pane.tsx +9 -10
- package/src/plugins/builtin/earnings/board-model.ts +33 -4
- package/src/plugins/builtin/earnings/board.tsx +15 -3
- package/src/plugins/builtin/earnings/calendar.tsx +10 -6
- package/src/plugins/builtin/earnings/client.ts +0 -9
- package/src/plugins/builtin/earnings/headless.ts +10 -7
- package/src/plugins/builtin/earnings/history.tsx +21 -14
- package/src/plugins/builtin/earnings-calls/data.ts +24 -4
- package/src/plugins/builtin/earnings-calls/format.ts +23 -5
- package/src/plugins/builtin/earnings-calls/headless.ts +23 -3
- package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
- package/src/plugins/builtin/earnings-calls/model.ts +11 -1
- package/src/plugins/builtin/earnings-calls/pane.tsx +2 -5
- package/src/plugins/builtin/econ/calendar-model.ts +27 -0
- package/src/plugins/builtin/econ/fred-catalog.ts +3 -0
- package/src/plugins/builtin/econ/index.tsx +9 -2
- package/src/plugins/builtin/econ-statistics/headless.ts +3 -1
- package/src/plugins/builtin/econ-statistics/index.tsx +1 -1
- 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/fear-greed/headless.ts +16 -13
- package/src/plugins/builtin/fear-greed/pane.tsx +12 -4
- package/src/plugins/builtin/filing-events/index.tsx +1 -0
- 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 +32 -19
- package/src/plugins/builtin/holders/pane.tsx +30 -20
- package/src/plugins/builtin/insider/table.tsx +10 -7
- package/src/plugins/builtin/insider/tickers.tsx +1 -1
- package/src/plugins/builtin/iv-history/events.ts +5 -0
- package/src/plugins/builtin/iv-history/headless.ts +15 -9
- package/src/plugins/builtin/jobs/index.tsx +1 -0
- package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
- package/src/plugins/builtin/macro-day/headless.ts +15 -6
- package/src/plugins/builtin/macro-day/model.ts +1 -1
- package/src/plugins/builtin/macro-day/releases.ts +25 -16
- package/src/plugins/builtin/market-movers/index.tsx +20 -8
- package/src/plugins/builtin/market-movers/model.ts +5 -0
- package/src/plugins/builtin/market-movers/session-body.tsx +2 -1
- package/src/plugins/builtin/money-markets/headless.ts +12 -2
- package/src/plugins/builtin/money-markets/pane.tsx +10 -1
- package/src/plugins/builtin/options/view.tsx +3 -0
- package/src/plugins/builtin/options-positioning/pane.tsx +1 -1
- package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
- package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
- package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -31
- package/src/plugins/builtin/portfolio-list/pane/index.tsx +19 -1
- package/src/plugins/builtin/portfolio-list/quick-add/index.tsx +22 -8
- package/src/plugins/builtin/portfolio-list/summary/index.tsx +6 -8
- package/src/plugins/builtin/portfolio-list/table.tsx +15 -1
- package/src/plugins/builtin/rate-path/pane.tsx +2 -0
- package/src/plugins/builtin/realized-vol/headless.ts +28 -2
- package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
- package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
- package/src/plugins/builtin/risk-factors/index.tsx +1 -0
- package/src/plugins/builtin/seasonality/pane.tsx +2 -1
- package/src/plugins/builtin/shared/source-footer.ts +70 -0
- package/src/plugins/builtin/short-interest/publications-pane.tsx +5 -1
- package/src/plugins/builtin/short-volume/pane.tsx +5 -1
- package/src/plugins/builtin/social-mentions/outliers.tsx +10 -1
- package/src/plugins/builtin/social-mentions/pane.tsx +7 -0
- package/src/plugins/builtin/supply-chain/client.ts +3 -1
- package/src/plugins/builtin/supply-chain/flow.tsx +25 -8
- package/src/plugins/builtin/supply-chain/graph-client.ts +1 -1
- package/src/plugins/builtin/supply-chain/graph-evidence.ts +1 -1
- package/src/plugins/builtin/supply-chain/graph-model.ts +12 -1
- package/src/plugins/builtin/supply-chain/graph-pane.tsx +9 -8
- package/src/plugins/builtin/supply-chain/graph.tsx +12 -6
- package/src/plugins/builtin/supply-chain/headless.ts +13 -7
- package/src/plugins/builtin/supply-chain/model.ts +68 -11
- package/src/plugins/builtin/supply-chain/pane.tsx +9 -6
- package/src/plugins/builtin/supply-chain/row-evidence.tsx +5 -5
- 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/ticker-detail/overview/components.tsx +14 -1
- package/src/plugins/builtin/ticker-detail/overview-tab.tsx +2 -0
- package/src/plugins/builtin/ticker-detail/pane.tsx +48 -24
- package/src/plugins/builtin/ticker-detail/quote-footer.ts +5 -0
- package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +6 -3
- package/src/plugins/builtin/treasury-auctions/after.ts +50 -23
- package/src/plugins/builtin/treasury-auctions/cache.ts +23 -5
- package/src/plugins/builtin/treasury-auctions/headless.ts +226 -37
- package/src/plugins/builtin/treasury-auctions/hk-headless.ts +11 -5
- package/src/plugins/builtin/treasury-auctions/hk-view.tsx +27 -25
- package/src/plugins/builtin/treasury-auctions/hk.ts +60 -8
- package/src/plugins/builtin/treasury-auctions/index.tsx +3 -0
- package/src/plugins/builtin/treasury-auctions/keys.ts +27 -0
- package/src/plugins/builtin/treasury-auctions/like.ts +137 -0
- package/src/plugins/builtin/treasury-auctions/model.ts +100 -22
- package/src/plugins/builtin/treasury-auctions/pane.tsx +39 -11
- package/src/plugins/builtin/vol-surface/heat-grid.tsx +6 -3
- package/src/plugins/builtin/vol-surface/pane.tsx +7 -3
- package/src/plugins/builtin/world-indices/index.tsx +5 -1
- package/src/plugins/builtin/yield-curve/index.tsx +2 -1
- package/src/plugins/runtime/index.tsx +1 -0
- package/src/plugins/runtime/state.ts +20 -0
- package/src/portfolio/column-values.ts +8 -2
- package/src/public/__snapshots__/public-api.test.ts.snap +5 -0
- package/src/public/react.ts +7 -0
- package/src/react/auto-refresh.ts +29 -0
- package/src/renderers/browser/deeplink-bridge.ts +24 -3
- 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/desktop/query-bar.tsx +229 -60
- package/src/renderers/dom/host/overflow-fade-px.ts +2 -0
- package/src/renderers/dom/host/overflow-fade.ts +1 -2
- package/src/renderers/dom/styles.css +47 -5
- package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +2 -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/series/types.ts +2 -0
- package/src/sources/gloomberb-cloud/fred-attribution.ts +86 -0
- package/src/sources/gloomberb-cloud/index.ts +25 -1
- package/src/sources/gloomberb-cloud/normalizers.ts +22 -3
- package/src/sources/provider-errors.ts +64 -1
- package/src/sources/provider-router/batches.ts +19 -0
- package/src/sources/provider-router/index.ts +7 -1
- package/src/state/app/context/index.tsx +46 -1
- package/src/state/pane-unsent-work.ts +47 -0
- package/src/test-support/app-store.ts +24 -1
- package/src/test-support/shell-pane-keys.tsx +5 -0
- package/src/test-support/telemetry-guard.ts +83 -0
- package/src/test-support/test-env.ts +12 -0
- package/src/theme/colors.ts +17 -1
- package/src/theme/ui-tokens.ts +50 -1
- package/src/tickers/listing-venues.ts +11 -1
- package/src/tickers/search/japanese-names.json +1 -0
- package/src/tickers/search/japanese-names.ts +152 -0
- package/src/tickers/terminal-codes.ts +55 -6
- package/src/time-series/base-series.ts +3 -0
- package/src/time-series/live-quotes.ts +3 -9
- package/src/types/data-provider.ts +6 -0
- package/src/types/financials.ts +11 -0
- package/src/types/plugin-contributions.ts +7 -0
- package/src/types/plugin-panes.ts +7 -0
- package/src/ui/host.tsx +24 -0
- package/src/ui/pointer-drag.ts +11 -2
- package/src/utils/double-escape-close.ts +42 -0
- package/src/utils/fundamentals.ts +14 -3
- package/src/utils/fx-status.ts +30 -7
- package/src/utils/network-failure.ts +23 -0
- package/src/utils/share-multiples.cases.json +780 -2
- package/src/utils/share-multiples.ts +154 -24
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,36 @@ 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_FIRST_RECONNECT_MAX_MS, SOCKET_PING_ANSWER_MS, SOCKET_QUIET_PING_MS } from "./socket-connection";
|
|
25
|
+
|
|
26
|
+
const cloudApiLog = debugLog.createLogger("cloud-api");
|
|
32
27
|
|
|
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
28
|
/**
|
|
69
|
-
*
|
|
70
|
-
*
|
|
29
|
+
* A hello after this long without any frame (a laptop asleep, an outage)
|
|
30
|
+
* says what changed meanwhile was missed, and the account's listeners load
|
|
31
|
+
* their data again. A deploy's reconnect, a few seconds without frames, does
|
|
32
|
+
* not: every client reconnects then, and each reloading would come at once.
|
|
71
33
|
*/
|
|
72
|
-
const
|
|
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
|
-
const cloudApiLog = debugLog.createLogger("cloud-api");
|
|
34
|
+
export const SOCKET_RESYNC_AFTER_SILENCE_MS = 60_000;
|
|
77
35
|
|
|
78
|
-
type ChannelListener = (message: ChatMessage) => void;
|
|
79
36
|
type ChatNotificationListener = (notification: ChatNotification) => void;
|
|
80
37
|
type ChatChannelStateListener = (state: ChatChannelState) => void;
|
|
81
38
|
type ChatPresenceListener = (onlineCount: number) => void;
|
|
82
39
|
type ChatReactionsListener = (update: ChatReactionsUpdate) => void;
|
|
83
40
|
type TeamNotificationListener = (notification: TeamNotification) => void;
|
|
84
41
|
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
42
|
type ScannerListener = (event: ScannerFeedEvent) => void;
|
|
94
43
|
|
|
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
44
|
type CloudApiSocketDelegate = {
|
|
109
45
|
getBaseUrl: () => string;
|
|
110
46
|
getSocketAuthToken: () => string | null;
|
|
@@ -113,7 +49,8 @@ type CloudApiSocketDelegate = {
|
|
|
113
49
|
isUsingWebSocketToken: () => boolean;
|
|
114
50
|
clearWebSocketTokenForFallback: () => boolean;
|
|
115
51
|
markCurrentUserUnverified: () => void;
|
|
116
|
-
|
|
52
|
+
/** `resync`: the socket was silent long enough that changes were missed (`SOCKET_RESYNC_AFTER_SILENCE_MS`). */
|
|
53
|
+
updateCurrentUserFromSocket: (user: Partial<AuthUser>, options: { resync: boolean }) => void;
|
|
117
54
|
/** The service answered on this connection (it opened, or sent a frame); see `CloudApiRequestTransport.noteServiceAnswered`. */
|
|
118
55
|
onServiceAnswered?: () => void;
|
|
119
56
|
};
|
|
@@ -130,81 +67,55 @@ type ChatChannelConnection = {
|
|
|
130
67
|
close: () => void;
|
|
131
68
|
};
|
|
132
69
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
70
|
+
/**
|
|
71
|
+
* The app's realtime link to Gloom Cloud: quotes, chat, team and scanner
|
|
72
|
+
* feeds over one WebSocket. It keeps the connection open while anything
|
|
73
|
+
* listens and decides what each subscription needs from it; the connection
|
|
74
|
+
* itself, inbound frames, quote batching, feature negotiation and the listener
|
|
75
|
+
* registries live in the `socket-*` modules beside it.
|
|
76
|
+
*/
|
|
141
77
|
export class CloudApiSocket {
|
|
142
|
-
private
|
|
143
|
-
private
|
|
144
|
-
private
|
|
145
|
-
|
|
146
|
-
private
|
|
147
|
-
/**
|
|
148
|
-
private
|
|
149
|
-
/**
|
|
150
|
-
private
|
|
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>();
|
|
78
|
+
private readonly listeners = new SocketListeners();
|
|
79
|
+
private readonly connection: SocketConnection;
|
|
80
|
+
private readonly quotes: QuoteStreamSubscriptions;
|
|
81
|
+
private readonly features: SocketFeatures;
|
|
82
|
+
private readonly frameRoutes: SocketFrameRoutes;
|
|
83
|
+
/** When the last frame arrived, on this connection or the one before. */
|
|
84
|
+
private lastFrameAt: number | null = null;
|
|
85
|
+
/** How long nothing arrived before the frame being handled. */
|
|
86
|
+
private silenceBeforeFrameMs = 0;
|
|
203
87
|
|
|
204
88
|
constructor(
|
|
205
89
|
private readonly delegate: CloudApiSocketDelegate,
|
|
206
|
-
|
|
207
|
-
) {
|
|
90
|
+
health: ConnectionHealthRegistry = connectionHealth,
|
|
91
|
+
) {
|
|
92
|
+
this.connection = new SocketConnection(delegate, health, {
|
|
93
|
+
wanted: () => this.shouldKeepSocketOpen(),
|
|
94
|
+
logCounts: () => ({
|
|
95
|
+
quoteTargets: this.quotes.size,
|
|
96
|
+
channelTargets: this.listeners.chatChannels.size,
|
|
97
|
+
}),
|
|
98
|
+
opened: () => this.replaySubscriptions(),
|
|
99
|
+
received: (raw) => void this.handleSocketMessage(raw),
|
|
100
|
+
interrupted: () => this.listeners.tape.emitAll({ type: "disconnected", reason: "Stream disconnected; observed window may contain gaps" }),
|
|
101
|
+
closed: () => this.listeners.connection.emit("closed"),
|
|
102
|
+
});
|
|
103
|
+
const send = (payload: Record<string, unknown>) => this.connection.send(payload);
|
|
104
|
+
this.quotes = new QuoteStreamSubscriptions({
|
|
105
|
+
openSocket: () => this.connection.openSocket(),
|
|
106
|
+
send,
|
|
107
|
+
});
|
|
108
|
+
this.features = new SocketFeatures({
|
|
109
|
+
send,
|
|
110
|
+
perpsOffered: (socket) => this.quotes.setPerpsConnection(socket),
|
|
111
|
+
});
|
|
112
|
+
this.frameRoutes = {
|
|
113
|
+
listeners: this.listeners,
|
|
114
|
+
ready: (frame) => this.handleReady(frame),
|
|
115
|
+
unverified: () => this.handleUnverified(),
|
|
116
|
+
quote: (frame) => this.quotes.deliver(frame),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
208
119
|
|
|
209
120
|
syncAuthState(options: { reconnect?: boolean } = {}): void {
|
|
210
121
|
if (!this.shouldKeepSocketOpen()) {
|
|
@@ -214,32 +125,12 @@ export class CloudApiSocket {
|
|
|
214
125
|
if (options.reconnect) {
|
|
215
126
|
this.teardown();
|
|
216
127
|
}
|
|
217
|
-
this.
|
|
128
|
+
this.connection.ensureOpen();
|
|
218
129
|
}
|
|
219
130
|
|
|
220
131
|
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
|
-
}
|
|
132
|
+
this.listeners.tape.emitAll({ type: "reset", reason: "Stream session changed" });
|
|
133
|
+
this.connection.close();
|
|
243
134
|
}
|
|
244
135
|
|
|
245
136
|
connectChannel(
|
|
@@ -257,14 +148,10 @@ export class CloudApiSocket {
|
|
|
257
148
|
};
|
|
258
149
|
}
|
|
259
150
|
|
|
260
|
-
const listeners
|
|
261
|
-
|
|
262
|
-
const firstListener = listeners.size === 0;
|
|
263
|
-
listeners.add(onMessage);
|
|
264
|
-
this.channelListeners.set(channelId, listeners);
|
|
265
|
-
this.ensureSocket();
|
|
151
|
+
const firstListener = this.listeners.chatChannels.add(channelId, onMessage);
|
|
152
|
+
this.connection.ensureOpen();
|
|
266
153
|
if (firstListener) {
|
|
267
|
-
this.
|
|
154
|
+
this.connection.send({ type: "chat.subscribe", channelId });
|
|
268
155
|
}
|
|
269
156
|
|
|
270
157
|
return {
|
|
@@ -284,30 +171,22 @@ export class CloudApiSocket {
|
|
|
284
171
|
}
|
|
285
172
|
},
|
|
286
173
|
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();
|
|
174
|
+
const removal = this.listeners.chatChannels.remove(channelId, onMessage);
|
|
175
|
+
if (removal === "unknown-key") return;
|
|
176
|
+
if (removal === "last") {
|
|
177
|
+
this.connection.send({ type: "chat.unsubscribe", channelId });
|
|
296
178
|
}
|
|
179
|
+
this.releaseSocket();
|
|
297
180
|
},
|
|
298
181
|
};
|
|
299
182
|
}
|
|
300
183
|
|
|
301
184
|
subscribeChatNotifications(listener: ChatNotificationListener): () => void {
|
|
302
|
-
this.
|
|
303
|
-
return () => {
|
|
304
|
-
this.chatNotificationListeners.delete(listener);
|
|
305
|
-
};
|
|
185
|
+
return this.listeners.chatNotifications.add(listener);
|
|
306
186
|
}
|
|
307
187
|
|
|
308
188
|
subscribeChatMentionCandidatesChanged(listener: () => void): () => void {
|
|
309
|
-
this.
|
|
310
|
-
return () => { this.chatMentionCandidatesListeners.delete(listener); };
|
|
189
|
+
return this.listeners.chatMentionCandidates.add(listener);
|
|
311
190
|
}
|
|
312
191
|
|
|
313
192
|
/**
|
|
@@ -315,92 +194,53 @@ export class CloudApiSocket {
|
|
|
315
194
|
* notifications, it never opens the socket by itself.
|
|
316
195
|
*/
|
|
317
196
|
subscribeChatChannelState(listener: ChatChannelStateListener): () => void {
|
|
318
|
-
this.
|
|
319
|
-
return () => {
|
|
320
|
-
this.chatChannelStateListeners.delete(listener);
|
|
321
|
-
};
|
|
197
|
+
return this.listeners.chatChannelState.add(listener);
|
|
322
198
|
}
|
|
323
199
|
|
|
324
200
|
/** A message's reactions changed in a channel this socket reads. */
|
|
325
201
|
subscribeChatReactions(listener: ChatReactionsListener): () => void {
|
|
326
|
-
this.
|
|
327
|
-
return () => {
|
|
328
|
-
this.chatReactionsListeners.delete(listener);
|
|
329
|
-
};
|
|
202
|
+
return this.listeners.chatReactions.add(listener);
|
|
330
203
|
}
|
|
331
204
|
|
|
332
205
|
subscribeChatPresence(listener: ChatPresenceListener): () => void {
|
|
333
|
-
this.
|
|
334
|
-
return () => {
|
|
335
|
-
this.chatPresenceListeners.delete(listener);
|
|
336
|
-
};
|
|
206
|
+
return this.listeners.chatPresence.add(listener);
|
|
337
207
|
}
|
|
338
208
|
|
|
339
209
|
/** Whether the server's last "ready" frame offered this protocol feature. */
|
|
340
210
|
serverOffers(feature: string): boolean {
|
|
341
|
-
return this.
|
|
211
|
+
return this.features.offers(feature);
|
|
342
212
|
}
|
|
343
213
|
|
|
344
214
|
subscribeServerFeatures(listener: () => void): () => void {
|
|
345
|
-
this.
|
|
346
|
-
return () => {
|
|
347
|
-
this.offeredFeatureListeners.delete(listener);
|
|
348
|
-
};
|
|
215
|
+
return this.features.subscribe(listener);
|
|
349
216
|
}
|
|
350
217
|
|
|
351
218
|
/** "ready" after each server hello (features negotiated), "closed" when that connection ends. */
|
|
352
219
|
subscribeConnection(listener: (event: "ready" | "closed") => void): () => void {
|
|
353
|
-
this.
|
|
354
|
-
return () => {
|
|
355
|
-
this.connectionListeners.delete(listener);
|
|
356
|
-
};
|
|
220
|
+
return this.listeners.connection.add(listener);
|
|
357
221
|
}
|
|
358
222
|
|
|
359
223
|
/** Sends one frame on the open connection; false when there is none. */
|
|
360
224
|
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);
|
|
225
|
+
return this.connection.sendFrame(payload);
|
|
373
226
|
}
|
|
374
227
|
|
|
375
228
|
subscribeTeamNotifications(listener: TeamNotificationListener): () => void {
|
|
376
|
-
this.
|
|
229
|
+
const remove = this.listeners.teamNotifications.add(listener);
|
|
377
230
|
this.syncAuthState();
|
|
378
231
|
return () => {
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
this.teardown();
|
|
382
|
-
}
|
|
232
|
+
remove();
|
|
233
|
+
this.releaseSocket();
|
|
383
234
|
};
|
|
384
235
|
}
|
|
385
236
|
|
|
386
237
|
/** Subscribes to a server push frame by type, e.g. a team layout update. */
|
|
387
238
|
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);
|
|
239
|
+
this.listeners.cloudEvents.add(type, listener);
|
|
392
240
|
this.syncAuthState();
|
|
393
241
|
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
|
-
}
|
|
242
|
+
this.listeners.cloudEvents.remove(type, listener);
|
|
243
|
+
this.releaseSocket();
|
|
404
244
|
};
|
|
405
245
|
}
|
|
406
246
|
|
|
@@ -412,800 +252,145 @@ export class CloudApiSocket {
|
|
|
412
252
|
scanner: ScannerKind,
|
|
413
253
|
listener: ScannerListener,
|
|
414
254
|
): () => void {
|
|
415
|
-
const listeners
|
|
416
|
-
|
|
417
|
-
const firstListener = listeners.size === 0;
|
|
418
|
-
listeners.add(listener);
|
|
419
|
-
this.scannerListeners.set(scanner, listeners);
|
|
420
|
-
this.ensureSocket();
|
|
255
|
+
const firstListener = this.listeners.scanners.add(scanner, listener);
|
|
256
|
+
this.connection.ensureOpen();
|
|
421
257
|
if (firstListener) {
|
|
422
|
-
this.
|
|
258
|
+
this.connection.send({ type: "scanner.subscribe", scanner });
|
|
423
259
|
} else {
|
|
424
|
-
const snapshot = this.
|
|
260
|
+
const snapshot = this.listeners.scanners.snapshot(scanner);
|
|
425
261
|
if (snapshot) listener(snapshot);
|
|
426
262
|
}
|
|
427
263
|
|
|
428
264
|
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();
|
|
265
|
+
const removal = this.listeners.scanners.remove(scanner, listener);
|
|
266
|
+
if (removal !== "removed" && removal !== "last") return;
|
|
267
|
+
if (removal === "last") {
|
|
268
|
+
this.connection.send({ type: "scanner.unsubscribe", scanner });
|
|
438
269
|
}
|
|
270
|
+
this.releaseSocket();
|
|
439
271
|
};
|
|
440
272
|
}
|
|
441
273
|
|
|
442
274
|
subscribeTape(symbol: string, exchange: string, listener: (event: TapeFeedEvent) => void): () => void {
|
|
443
275
|
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 });
|
|
276
|
+
const firstListener = this.listeners.tape.add(target, listener);
|
|
277
|
+
this.connection.ensureOpen();
|
|
278
|
+
if (firstListener) this.connection.send({ type: "tape.subscribe", ...target });
|
|
451
279
|
return () => {
|
|
452
|
-
const
|
|
453
|
-
if (
|
|
454
|
-
if (
|
|
455
|
-
|
|
456
|
-
this.sendSocketMessage({ type: "tape.unsubscribe", ...target });
|
|
457
|
-
}
|
|
458
|
-
if (!this.shouldKeepSocketOpen()) this.teardown();
|
|
280
|
+
const removal = this.listeners.tape.remove(target, listener);
|
|
281
|
+
if (removal !== "removed" && removal !== "last") return;
|
|
282
|
+
if (removal === "last") this.connection.send({ type: "tape.unsubscribe", ...target });
|
|
283
|
+
this.releaseSocket();
|
|
459
284
|
};
|
|
460
285
|
}
|
|
461
286
|
|
|
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
287
|
subscribeQuotes(
|
|
467
288
|
targets: QuoteStreamTarget[],
|
|
468
289
|
onQuote: (target: QuoteStreamTarget, quote: CloudQuotePayload) => void,
|
|
469
290
|
): () => 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
|
-
|
|
291
|
+
const subscription = this.quotes.subscribe(targets, onQuote);
|
|
292
|
+
this.connection.ensureOpen();
|
|
293
|
+
subscription.announce();
|
|
530
294
|
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
|
-
}
|
|
295
|
+
subscription.release();
|
|
296
|
+
this.releaseSocket();
|
|
575
297
|
};
|
|
576
298
|
}
|
|
577
299
|
|
|
578
300
|
dispose(): void {
|
|
579
301
|
cloudApiLog.info("dispose api client", {
|
|
580
|
-
quoteTargets: this.
|
|
581
|
-
channelTargets: this.
|
|
302
|
+
quoteTargets: this.quotes.size,
|
|
303
|
+
channelTargets: this.listeners.chatChannels.size,
|
|
582
304
|
});
|
|
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;
|
|
305
|
+
this.listeners.clear();
|
|
306
|
+
this.features.clearListeners();
|
|
307
|
+
this.quotes.clear();
|
|
308
|
+
this.connection.resetBackoff();
|
|
604
309
|
this.teardown();
|
|
605
310
|
}
|
|
606
311
|
|
|
607
312
|
async handleSocketMessage(raw: string): Promise<void> {
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
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
|
-
}
|
|
313
|
+
const now = Date.now();
|
|
314
|
+
this.silenceBeforeFrameMs = this.lastFrameAt == null ? 0 : now - this.lastFrameAt;
|
|
315
|
+
this.lastFrameAt = now;
|
|
316
|
+
dispatchSocketFrame(raw, this.frameRoutes);
|
|
317
|
+
}
|
|
652
318
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
}
|
|
663
|
-
return;
|
|
319
|
+
private handleReady(frame: SocketReadyFrame): void {
|
|
320
|
+
this.features.negotiate(this.connection.socket, frame.features);
|
|
321
|
+
if (frame.user) {
|
|
322
|
+
cloudApiLog.info("websocket ready", {
|
|
323
|
+
emailVerified: frame.user.emailVerified === true,
|
|
324
|
+
});
|
|
325
|
+
this.delegate.updateCurrentUserFromSocket(frame.user, {
|
|
326
|
+
resync: this.silenceBeforeFrameMs >= SOCKET_RESYNC_AFTER_SILENCE_MS,
|
|
327
|
+
});
|
|
664
328
|
}
|
|
329
|
+
this.listeners.connection.emit("ready");
|
|
330
|
+
}
|
|
665
331
|
|
|
332
|
+
private handleUnverified(): void {
|
|
333
|
+
cloudApiLog.warn("websocket marked unverified");
|
|
666
334
|
if (
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
typeof parsed.data?.messageId === "string"
|
|
335
|
+
this.delegate.isUsingWebSocketToken() &&
|
|
336
|
+
this.delegate.clearWebSocketTokenForFallback()
|
|
670
337
|
) {
|
|
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,
|
|
685
|
-
);
|
|
686
|
-
for (const listener of this.chatNotificationListeners) {
|
|
687
|
-
listener(notification);
|
|
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,
|
|
338
|
+
this.connection.resetBackoff();
|
|
339
|
+
cloudApiLog.warn(
|
|
340
|
+
"cleared websocket token after auth rejection; falling back to session token",
|
|
709
341
|
);
|
|
710
|
-
|
|
711
|
-
|
|
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
|
-
}
|
|
751
|
-
return;
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
if (parsed?.type === "market.quote") {
|
|
755
|
-
this.dispatchMarketQuote(parsed);
|
|
342
|
+
this.teardown();
|
|
343
|
+
this.connection.scheduleReconnect();
|
|
756
344
|
return;
|
|
757
345
|
}
|
|
758
|
-
|
|
759
|
-
if (
|
|
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);
|
|
346
|
+
this.delegate.markCurrentUserUnverified();
|
|
347
|
+
if (this.hasMarketStreams()) {
|
|
764
348
|
return;
|
|
765
349
|
}
|
|
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);
|
|
350
|
+
this.teardown();
|
|
834
351
|
}
|
|
835
352
|
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
): void {
|
|
840
|
-
this.scannerSnapshots.set(scanner, event);
|
|
841
|
-
for (const listener of this.scannerListeners.get(scanner) ?? []) {
|
|
842
|
-
listener(event);
|
|
843
|
-
}
|
|
353
|
+
/** Quotes, scanners and tapes stream signed out too, so they keep the connection without a verified account. */
|
|
354
|
+
private hasMarketStreams(): boolean {
|
|
355
|
+
return this.quotes.size > 0 || this.listeners.scanners.size > 0 || this.listeners.tape.size > 0;
|
|
844
356
|
}
|
|
845
357
|
|
|
846
358
|
private shouldKeepSocketOpen(): boolean {
|
|
847
|
-
if (this.
|
|
848
|
-
return true;
|
|
359
|
+
if (this.hasMarketStreams()) return true;
|
|
849
360
|
return (
|
|
850
361
|
this.delegate.hasSessionCredential() &&
|
|
851
362
|
this.delegate.hasVerifiedUser() &&
|
|
852
|
-
(this.
|
|
853
|
-
this.
|
|
854
|
-
this.
|
|
363
|
+
(this.listeners.chatChannels.size > 0 ||
|
|
364
|
+
this.listeners.teamNotifications.size > 0 ||
|
|
365
|
+
this.listeners.cloudEvents.size > 0)
|
|
855
366
|
);
|
|
856
367
|
}
|
|
857
368
|
|
|
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)) });
|
|
369
|
+
/** A listener left: the connection closes once nothing needs it. */
|
|
370
|
+
private releaseSocket(): void {
|
|
371
|
+
if (!this.shouldKeepSocketOpen()) {
|
|
372
|
+
this.teardown();
|
|
1127
373
|
}
|
|
1128
374
|
}
|
|
1129
375
|
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
}, QUOTE_SUBSCRIPTION_FLUSH_MS);
|
|
1136
|
-
}
|
|
376
|
+
/** A connection opened: every subscription goes out on it, chat, tapes and scanners first, then quotes. */
|
|
377
|
+
private replaySubscriptions(): void {
|
|
378
|
+
// The full set goes out now; queued diffs from before the open are part of it.
|
|
379
|
+
this.quotes.dropPending();
|
|
380
|
+
if (!this.connection.openSocket()) return;
|
|
1137
381
|
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
const key = marketKey(target.symbol, target.exchange);
|
|
1141
|
-
this.pendingQuoteUnsubscribes.delete(key);
|
|
1142
|
-
this.pendingQuoteSubscribes.set(key, target);
|
|
382
|
+
for (const channelId of this.listeners.chatChannels.keys()) {
|
|
383
|
+
this.connection.send({ type: "chat.subscribe", channelId });
|
|
1143
384
|
}
|
|
1144
|
-
this.scheduleQuoteSubscriptionFlush();
|
|
1145
|
-
}
|
|
1146
385
|
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
const key = marketKey(target.symbol, target.exchange);
|
|
1150
|
-
this.pendingQuoteSubscribes.delete(key);
|
|
1151
|
-
this.pendingQuoteUnsubscribes.set(key, target);
|
|
386
|
+
for (const market of this.listeners.tape.markets()) {
|
|
387
|
+
this.connection.send({ type: "tape.subscribe", symbol: market.symbol, exchange: market.exchange });
|
|
1152
388
|
}
|
|
1153
|
-
this.scheduleQuoteSubscriptionFlush();
|
|
1154
|
-
}
|
|
1155
389
|
|
|
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
|
-
});
|
|
390
|
+
for (const scanner of this.listeners.scanners.keys()) {
|
|
391
|
+
this.connection.send({ type: "scanner.subscribe", scanner });
|
|
1186
392
|
}
|
|
1187
|
-
}
|
|
1188
393
|
|
|
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
|
-
);
|
|
394
|
+
this.quotes.replay();
|
|
1210
395
|
}
|
|
1211
396
|
}
|