@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.
Files changed (324) hide show
  1. package/package.json +2 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
  3. package/src/api-client/awards.ts +16 -0
  4. package/src/api-client/central-bank-rates.ts +5 -0
  5. package/src/api-client/data.ts +55 -2
  6. package/src/api-client/index.ts +18 -1
  7. package/src/api-client/request.ts +86 -3
  8. package/src/api-client/socket-connection.ts +366 -0
  9. package/src/api-client/socket-features.ts +75 -0
  10. package/src/api-client/socket-frames.ts +161 -0
  11. package/src/api-client/socket-listeners.ts +207 -0
  12. package/src/api-client/socket-quotes.ts +332 -0
  13. package/src/api-client/socket.ts +168 -983
  14. package/src/api-client/supply-chain-graph.ts +4 -2
  15. package/src/api-client/supply-chain.ts +8 -0
  16. package/src/api-client/types/econ.ts +10 -7
  17. package/src/api-client/types/filings-and-calls.ts +8 -0
  18. package/src/app/global-shortcuts.ts +2 -1
  19. package/src/app/keybindings/actions.ts +19 -0
  20. package/src/app/pane-runtime/index.tsx +18 -3
  21. package/src/app/pane-runtime/layout-placement.ts +63 -0
  22. package/src/app/pane-runtime/ticker-open-runtime.ts +10 -2
  23. package/src/brokers/signed-in/adapter.ts +19 -5
  24. package/src/brokers/signed-in/client.ts +13 -1
  25. package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
  26. package/src/capabilities/chart-series.ts +4 -1
  27. package/src/cli/board-coins.ts +10 -1
  28. package/src/cli/commands/crypto-hints.ts +3 -2
  29. package/src/cli/commands/fred-series.ts +0 -54
  30. package/src/cli/commands/market.ts +209 -31
  31. package/src/cli/commands/overview.ts +47 -14
  32. package/src/cli/commands/search.ts +37 -8
  33. package/src/cli/commands/ticker.ts +15 -4
  34. package/src/cli/desktop-pane-shot.ts +27 -2
  35. package/src/cli/fx-quote-rate.ts +1 -1
  36. package/src/cli/glossary.ts +14 -5
  37. package/src/cli/history-catalog-series.ts +85 -0
  38. package/src/cli/index.ts +1 -1
  39. package/src/cli/list-progress.ts +45 -0
  40. package/src/cli/listing-arg.ts +71 -7
  41. package/src/cli/name-entries.ts +8 -4
  42. package/src/cli/not-a-ticker.ts +2 -2
  43. package/src/cli/pane-functions/freshness.ts +50 -3
  44. package/src/cli/pane-functions/index.ts +7 -4
  45. package/src/cli/pane-functions/market-session.ts +66 -14
  46. package/src/cli/pane-functions/options.ts +5 -0
  47. package/src/cli/pane-functions/resolver.ts +9 -2
  48. package/src/cli/pane-functions/screenshot-assessment.ts +28 -3
  49. package/src/cli/pane-functions/screenshot-types.ts +6 -0
  50. package/src/cli/quote-answer.ts +49 -10
  51. package/src/cli/quote-list-reads.ts +87 -0
  52. package/src/cli/report-tables.ts +70 -13
  53. package/src/cli/result.ts +24 -2
  54. package/src/cli/symbol-list.ts +31 -4
  55. package/src/cli/terminal-code-hints.ts +83 -0
  56. package/src/cli/ticker-resolution.ts +2 -1
  57. package/src/cli/treasury-yields.ts +5 -0
  58. package/src/components/chart/native/kitty/manager.ts +2 -0
  59. package/src/components/chart/native/surface/manager.ts +211 -11
  60. package/src/components/command-bar/action-runtime.ts +2 -0
  61. package/src/components/command-bar/panel/index.tsx +2 -13
  62. package/src/components/command-bar/panel/layout.ts +1 -7
  63. package/src/components/command-bar/panel/runtime.ts +0 -1
  64. package/src/components/command-bar/panel/types.ts +0 -2
  65. package/src/components/command-bar/routing/launch-request.ts +2 -1
  66. package/src/components/command-bar/routing/navigation-state.ts +4 -2
  67. package/src/components/command-bar/workflow/types.ts +6 -0
  68. package/src/components/data-table/column-menu.tsx +89 -0
  69. package/src/components/data-table/sort-menu.tsx +9 -2
  70. package/src/components/data-table/view.tsx +33 -6
  71. package/src/components/form-modal/content.tsx +10 -0
  72. package/src/components/index.ts +1 -1
  73. package/src/components/layout/detached-pane-shell.tsx +3 -0
  74. package/src/components/layout/double-escape-close.ts +34 -3
  75. package/src/components/layout/floating-pane.tsx +10 -4
  76. package/src/components/layout/pane/cycle-order.ts +66 -2
  77. package/src/components/layout/pane/footer/index.tsx +25 -11
  78. package/src/components/layout/pane/footer/model.ts +62 -20
  79. package/src/components/layout/pane/header.tsx +140 -31
  80. package/src/components/layout/pane/sidebar.tsx +138 -20
  81. package/src/components/layout/pane/status-footer.ts +3 -1
  82. package/src/components/layout/shell/active-drag.ts +18 -13
  83. package/src/components/layout/shell/drag/magnets.ts +34 -18
  84. package/src/components/layout/shell/drag/runtime.ts +5 -0
  85. package/src/components/layout/shell/index.tsx +25 -0
  86. package/src/components/layout/shell/menu.ts +9 -0
  87. package/src/components/layout/shell/pane/actions.ts +36 -0
  88. package/src/components/layout/shell/pane/management-shortcuts.ts +27 -3
  89. package/src/components/layout/shell/pane-occlusion.ts +40 -0
  90. package/src/components/layout/shell/shortcuts.ts +17 -1
  91. package/src/components/layout/shell/terminal-pointer-runtime.ts +39 -6
  92. package/src/components/layout/shell/window-mode/index.ts +5 -16
  93. package/src/components/layout/shell/window-mode/overlays.tsx +3 -1
  94. package/src/components/market-board/index.tsx +14 -5
  95. package/src/components/metric-treemap/index.tsx +3 -1
  96. package/src/components/ticker/list-table-view.tsx +5 -0
  97. package/src/components/ui/button.tsx +48 -4
  98. package/src/components/ui/data-table/column-order.ts +180 -0
  99. package/src/components/ui/data-table/index.tsx +12 -1
  100. package/src/components/ui/data-table/opentui/index.tsx +291 -32
  101. package/src/components/ui/data-table/opentui/model.ts +43 -4
  102. package/src/components/ui/data-table/types.ts +56 -0
  103. package/src/components/ui/data-table/use-column-order.ts +135 -0
  104. package/src/components/ui/index.ts +1 -1
  105. package/src/components/ui/inline-quick-add.tsx +19 -3
  106. package/src/components/ui/list-view.tsx +11 -5
  107. package/src/components/ui/query-bar.tsx +16 -1
  108. package/src/components/ui/selection-fill.ts +39 -0
  109. package/src/components/ui/table-layout.ts +120 -0
  110. package/src/core/state/app/layout-reducer.ts +2 -1
  111. package/src/core/state/app/pane-choices.ts +68 -0
  112. package/src/core/state/app/state.ts +14 -6
  113. package/src/core/state/app/types.ts +8 -0
  114. package/src/docs/snapshot.json +3 -2
  115. package/src/i18n/es.ts +2 -0
  116. package/src/i18n/ja.ts +2 -0
  117. package/src/i18n/ko.ts +2 -0
  118. package/src/i18n/zh-cn.ts +2 -0
  119. package/src/i18n/zh-tw.ts +2 -0
  120. package/src/layout/pane-manager/dock-tree.ts +19 -0
  121. package/src/layout/pane-manager/index.ts +3 -0
  122. package/src/market-data/coordinator/index.ts +4 -3
  123. package/src/market-data/coordinator/quotes.ts +12 -4
  124. package/src/market-data/market/freshness.ts +33 -0
  125. package/src/market-data/market/status.ts +5 -1
  126. package/src/market-data/quotes/contributions.ts +10 -0
  127. package/src/market-data/quotes/freshness.ts +31 -0
  128. package/src/market-data/quotes/live-valuation.ts +32 -5
  129. package/src/market-data/quotes/regular-session-valuation.ts +1 -1
  130. package/src/market-data/quotes/resolution.ts +4 -0
  131. package/src/market-data/quotes/time.ts +0 -14
  132. package/src/plugins/builtin/account-management/index.tsx +1 -0
  133. package/src/plugins/builtin/awards/detail.tsx +12 -4
  134. package/src/plugins/builtin/awards/headless.ts +29 -8
  135. package/src/plugins/builtin/awards/model.ts +36 -2
  136. package/src/plugins/builtin/awards/pane.tsx +7 -4
  137. package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
  138. package/src/plugins/builtin/broker-manager/index.tsx +7 -6
  139. package/src/plugins/builtin/broker-manager/model.ts +15 -6
  140. package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
  141. package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
  142. package/src/plugins/builtin/broker-manager/table.ts +10 -4
  143. package/src/plugins/builtin/broker-trading/index.tsx +1 -1
  144. package/src/plugins/builtin/central-bank-rates/headless.ts +6 -6
  145. package/src/plugins/builtin/central-bank-rates/index.tsx +1 -1
  146. package/src/plugins/builtin/central-bank-rates/model.ts +21 -3
  147. package/src/plugins/builtin/central-bank-rates/pane.tsx +15 -5
  148. package/src/plugins/builtin/chart-composer/headless.ts +5 -1
  149. package/src/plugins/builtin/chart-composer/pane.tsx +1 -0
  150. package/src/plugins/builtin/chat/content/handle-prompt.tsx +4 -0
  151. package/src/plugins/builtin/chat/controller/realtime.ts +17 -1
  152. package/src/plugins/builtin/chat/message/terminal.tsx +4 -1
  153. package/src/plugins/builtin/chat/sidebar.tsx +35 -19
  154. package/src/plugins/builtin/cloud/askg/pane.tsx +4 -0
  155. package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
  156. package/src/plugins/builtin/cloud/plugin.tsx +1 -0
  157. package/src/plugins/builtin/cloud/team/module.tsx +1 -0
  158. package/src/plugins/builtin/cloud/thesis/detail.tsx +9 -4
  159. package/src/plugins/builtin/commodity-balances/pane.tsx +13 -5
  160. package/src/plugins/builtin/company-kpis/model.ts +3 -3
  161. package/src/plugins/builtin/connections/index.ts +1 -0
  162. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +9 -5
  163. package/src/plugins/builtin/credit-boards/client.ts +5 -0
  164. package/src/plugins/builtin/credit-boards/headless.ts +1 -6
  165. package/src/plugins/builtin/credit-boards/model.ts +0 -6
  166. package/src/plugins/builtin/credit-boards/series.ts +19 -8
  167. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +9 -5
  168. package/src/plugins/builtin/crypto-etf-flows/headless.ts +23 -13
  169. package/src/plugins/builtin/crypto-etf-flows/pane.tsx +8 -3
  170. package/src/plugins/builtin/debt-maturities/headless.ts +16 -7
  171. package/src/plugins/builtin/debt-maturities/model.ts +9 -15
  172. package/src/plugins/builtin/debt-maturities/pane.tsx +9 -10
  173. package/src/plugins/builtin/earnings/board-model.ts +33 -4
  174. package/src/plugins/builtin/earnings/board.tsx +15 -3
  175. package/src/plugins/builtin/earnings/calendar.tsx +10 -6
  176. package/src/plugins/builtin/earnings/client.ts +0 -9
  177. package/src/plugins/builtin/earnings/headless.ts +10 -7
  178. package/src/plugins/builtin/earnings/history.tsx +21 -14
  179. package/src/plugins/builtin/earnings-calls/data.ts +24 -4
  180. package/src/plugins/builtin/earnings-calls/format.ts +23 -5
  181. package/src/plugins/builtin/earnings-calls/headless.ts +23 -3
  182. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  183. package/src/plugins/builtin/earnings-calls/model.ts +11 -1
  184. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -5
  185. package/src/plugins/builtin/econ/calendar-model.ts +27 -0
  186. package/src/plugins/builtin/econ/fred-catalog.ts +3 -0
  187. package/src/plugins/builtin/econ/index.tsx +9 -2
  188. package/src/plugins/builtin/econ-statistics/headless.ts +3 -1
  189. package/src/plugins/builtin/econ-statistics/index.tsx +1 -1
  190. package/src/plugins/builtin/equity-screener/live.ts +74 -18
  191. package/src/plugins/builtin/equity-screener/model.ts +19 -4
  192. package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
  193. package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
  194. package/src/plugins/builtin/equity-screener/results.ts +22 -2
  195. package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
  196. package/src/plugins/builtin/fear-greed/headless.ts +16 -13
  197. package/src/plugins/builtin/fear-greed/pane.tsx +12 -4
  198. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  199. package/src/plugins/builtin/futures/index.tsx +15 -1
  200. package/src/plugins/builtin/futures/table.tsx +1 -1
  201. package/src/plugins/builtin/fx-matrix/index.tsx +32 -19
  202. package/src/plugins/builtin/holders/pane.tsx +30 -20
  203. package/src/plugins/builtin/insider/table.tsx +10 -7
  204. package/src/plugins/builtin/insider/tickers.tsx +1 -1
  205. package/src/plugins/builtin/iv-history/events.ts +5 -0
  206. package/src/plugins/builtin/iv-history/headless.ts +15 -9
  207. package/src/plugins/builtin/jobs/index.tsx +1 -0
  208. package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
  209. package/src/plugins/builtin/macro-day/headless.ts +15 -6
  210. package/src/plugins/builtin/macro-day/model.ts +1 -1
  211. package/src/plugins/builtin/macro-day/releases.ts +25 -16
  212. package/src/plugins/builtin/market-movers/index.tsx +20 -8
  213. package/src/plugins/builtin/market-movers/model.ts +5 -0
  214. package/src/plugins/builtin/market-movers/session-body.tsx +2 -1
  215. package/src/plugins/builtin/money-markets/headless.ts +12 -2
  216. package/src/plugins/builtin/money-markets/pane.tsx +10 -1
  217. package/src/plugins/builtin/options/view.tsx +3 -0
  218. package/src/plugins/builtin/options-positioning/pane.tsx +1 -1
  219. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  220. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
  221. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -31
  222. package/src/plugins/builtin/portfolio-list/pane/index.tsx +19 -1
  223. package/src/plugins/builtin/portfolio-list/quick-add/index.tsx +22 -8
  224. package/src/plugins/builtin/portfolio-list/summary/index.tsx +6 -8
  225. package/src/plugins/builtin/portfolio-list/table.tsx +15 -1
  226. package/src/plugins/builtin/rate-path/pane.tsx +2 -0
  227. package/src/plugins/builtin/realized-vol/headless.ts +28 -2
  228. package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
  229. package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
  230. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  231. package/src/plugins/builtin/seasonality/pane.tsx +2 -1
  232. package/src/plugins/builtin/shared/source-footer.ts +70 -0
  233. package/src/plugins/builtin/short-interest/publications-pane.tsx +5 -1
  234. package/src/plugins/builtin/short-volume/pane.tsx +5 -1
  235. package/src/plugins/builtin/social-mentions/outliers.tsx +10 -1
  236. package/src/plugins/builtin/social-mentions/pane.tsx +7 -0
  237. package/src/plugins/builtin/supply-chain/client.ts +3 -1
  238. package/src/plugins/builtin/supply-chain/flow.tsx +25 -8
  239. package/src/plugins/builtin/supply-chain/graph-client.ts +1 -1
  240. package/src/plugins/builtin/supply-chain/graph-evidence.ts +1 -1
  241. package/src/plugins/builtin/supply-chain/graph-model.ts +12 -1
  242. package/src/plugins/builtin/supply-chain/graph-pane.tsx +9 -8
  243. package/src/plugins/builtin/supply-chain/graph.tsx +12 -6
  244. package/src/plugins/builtin/supply-chain/headless.ts +13 -7
  245. package/src/plugins/builtin/supply-chain/model.ts +68 -11
  246. package/src/plugins/builtin/supply-chain/pane.tsx +9 -6
  247. package/src/plugins/builtin/supply-chain/row-evidence.tsx +5 -5
  248. package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
  249. package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
  250. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
  251. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
  252. package/src/plugins/builtin/ticker-detail/overview/components.tsx +14 -1
  253. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +2 -0
  254. package/src/plugins/builtin/ticker-detail/pane.tsx +48 -24
  255. package/src/plugins/builtin/ticker-detail/quote-footer.ts +5 -0
  256. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +6 -3
  257. package/src/plugins/builtin/treasury-auctions/after.ts +50 -23
  258. package/src/plugins/builtin/treasury-auctions/cache.ts +23 -5
  259. package/src/plugins/builtin/treasury-auctions/headless.ts +226 -37
  260. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +11 -5
  261. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +27 -25
  262. package/src/plugins/builtin/treasury-auctions/hk.ts +60 -8
  263. package/src/plugins/builtin/treasury-auctions/index.tsx +3 -0
  264. package/src/plugins/builtin/treasury-auctions/keys.ts +27 -0
  265. package/src/plugins/builtin/treasury-auctions/like.ts +137 -0
  266. package/src/plugins/builtin/treasury-auctions/model.ts +100 -22
  267. package/src/plugins/builtin/treasury-auctions/pane.tsx +39 -11
  268. package/src/plugins/builtin/vol-surface/heat-grid.tsx +6 -3
  269. package/src/plugins/builtin/vol-surface/pane.tsx +7 -3
  270. package/src/plugins/builtin/world-indices/index.tsx +5 -1
  271. package/src/plugins/builtin/yield-curve/index.tsx +2 -1
  272. package/src/plugins/runtime/index.tsx +1 -0
  273. package/src/plugins/runtime/state.ts +20 -0
  274. package/src/portfolio/column-values.ts +8 -2
  275. package/src/public/__snapshots__/public-api.test.ts.snap +5 -0
  276. package/src/public/react.ts +7 -0
  277. package/src/react/auto-refresh.ts +29 -0
  278. package/src/renderers/browser/deeplink-bridge.ts +24 -3
  279. package/src/renderers/dom/data-table/column-drag.ts +147 -0
  280. package/src/renderers/dom/data-table/index.tsx +22 -0
  281. package/src/renderers/dom/data-table/row.tsx +27 -5
  282. package/src/renderers/dom/desktop/query-bar.tsx +229 -60
  283. package/src/renderers/dom/host/overflow-fade-px.ts +2 -0
  284. package/src/renderers/dom/host/overflow-fade.ts +1 -2
  285. package/src/renderers/dom/styles.css +47 -5
  286. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +2 -1
  287. package/src/renderers/opentui/chart-surface.tsx +1 -0
  288. package/src/renderers/opentui/frame-hits.ts +33 -0
  289. package/src/renderers/opentui/host.tsx +2 -0
  290. package/src/renderers/opentui/native-surface.ts +14 -21
  291. package/src/renderers/opentui/test-utils.tsx +3 -0
  292. package/src/series/types.ts +2 -0
  293. package/src/sources/gloomberb-cloud/fred-attribution.ts +86 -0
  294. package/src/sources/gloomberb-cloud/index.ts +25 -1
  295. package/src/sources/gloomberb-cloud/normalizers.ts +22 -3
  296. package/src/sources/provider-errors.ts +64 -1
  297. package/src/sources/provider-router/batches.ts +19 -0
  298. package/src/sources/provider-router/index.ts +7 -1
  299. package/src/state/app/context/index.tsx +46 -1
  300. package/src/state/pane-unsent-work.ts +47 -0
  301. package/src/test-support/app-store.ts +24 -1
  302. package/src/test-support/shell-pane-keys.tsx +5 -0
  303. package/src/test-support/telemetry-guard.ts +83 -0
  304. package/src/test-support/test-env.ts +12 -0
  305. package/src/theme/colors.ts +17 -1
  306. package/src/theme/ui-tokens.ts +50 -1
  307. package/src/tickers/listing-venues.ts +11 -1
  308. package/src/tickers/search/japanese-names.json +1 -0
  309. package/src/tickers/search/japanese-names.ts +152 -0
  310. package/src/tickers/terminal-codes.ts +55 -6
  311. package/src/time-series/base-series.ts +3 -0
  312. package/src/time-series/live-quotes.ts +3 -9
  313. package/src/types/data-provider.ts +6 -0
  314. package/src/types/financials.ts +11 -0
  315. package/src/types/plugin-contributions.ts +7 -0
  316. package/src/types/plugin-panes.ts +7 -0
  317. package/src/ui/host.tsx +24 -0
  318. package/src/ui/pointer-drag.ts +11 -2
  319. package/src/utils/double-escape-close.ts +42 -0
  320. package/src/utils/fundamentals.ts +14 -3
  321. package/src/utils/fx-status.ts +30 -7
  322. package/src/utils/network-failure.ts +23 -0
  323. package/src/utils/share-multiples.cases.json +780 -2
  324. package/src/utils/share-multiples.ts +154 -24
@@ -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 { mergeQuoteSubscriptionTargets } from "../market-data/quote-subscription-target";
25
- import { recordServerClockSample } from "../market-data/quotes/clock";
26
- import { perpetualListing } from "../tickers/perpetual-listing";
27
- import {
28
- connectionHealth,
29
- GLOOM_CLOUD_SOCKET_CONNECTION_ID,
30
- type ConnectionHealthRegistry,
31
- } from "../core/connection-health";
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
- * 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.
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 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
- 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
- updateCurrentUserFromSocket: (user: Partial<AuthUser>) => void;
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
- function marketKey(symbol: string, exchange?: string): string {
134
- const normalizedSymbolValue = normalizeSymbol(symbol);
135
- const normalizedExchangeValue = canonicalExchange(exchange);
136
- return normalizedExchangeValue
137
- ? `${normalizedSymbolValue}:${normalizedExchangeValue}`
138
- : normalizedSymbolValue;
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 ws: WebSocket | null = null;
143
- private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
144
- private reconnectDelayMs = 1000;
145
- /** Gives up on a connection that has not opened in SOCKET_CONNECT_TIMEOUT_MS. */
146
- private connectTimer: ReturnType<typeof setTimeout> | null = null;
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>();
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
- private readonly health: ConnectionHealthRegistry = connectionHealth,
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.ensureSocket();
128
+ this.connection.ensureOpen();
218
129
  }
219
130
 
220
131
  teardown(): void {
221
- this.emitTapeStatus({ type: "reset", reason: "Stream session changed" });
222
- if (this.reconnectTimer) {
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
- this.channelListeners.get(channelId) ?? new Set<ChannelListener>();
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.sendSocketMessage({ type: "chat.subscribe", channelId });
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 current = this.channelListeners.get(channelId);
288
- if (!current) return;
289
- current.delete(onMessage);
290
- if (current.size === 0) {
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.chatNotificationListeners.add(listener);
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.chatMentionCandidatesListeners.add(listener);
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.chatChannelStateListeners.add(listener);
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.chatReactionsListeners.add(listener);
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.chatPresenceListeners.add(listener);
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.offeredFeatures.has(feature);
211
+ return this.features.offers(feature);
342
212
  }
343
213
 
344
214
  subscribeServerFeatures(listener: () => void): () => void {
345
- this.offeredFeatureListeners.add(listener);
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.connectionListeners.add(listener);
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
- if (this.ws?.readyState !== WebSocket.OPEN) return false;
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.teamNotificationListeners.add(listener);
229
+ const remove = this.listeners.teamNotifications.add(listener);
377
230
  this.syncAuthState();
378
231
  return () => {
379
- this.teamNotificationListeners.delete(listener);
380
- if (!this.shouldKeepSocketOpen()) {
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
- const listeners =
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
- const current = this.cloudEventListeners.get(type);
395
- if (current) {
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
- this.scannerListeners.get(scanner) ?? new Set<ScannerListener>();
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.sendSocketMessage({ type: "scanner.subscribe", scanner });
258
+ this.connection.send({ type: "scanner.subscribe", scanner });
423
259
  } else {
424
- const snapshot = this.scannerSnapshots.get(scanner);
260
+ const snapshot = this.listeners.scanners.snapshot(scanner);
425
261
  if (snapshot) listener(snapshot);
426
262
  }
427
263
 
428
264
  return () => {
429
- const current = this.scannerListeners.get(scanner);
430
- if (!current || !current.delete(listener)) return;
431
- if (current.size === 0) {
432
- this.scannerListeners.delete(scanner);
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 key = marketKey(target.symbol, target.exchange);
445
- const existing = this.tapeListeners.get(key);
446
- const entry = existing ?? { ...target, listeners: new Set<(event: TapeFeedEvent) => void>() };
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 current = this.tapeListeners.get(key);
453
- if (!current?.listeners.delete(listener)) return;
454
- if (!current.listeners.size) {
455
- this.tapeListeners.delete(key);
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 subscriptionId = this.nextQuoteSubscriptionId++;
471
- const uniqueTargets = [
472
- ...new Map(
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
- const removedTargets: QuoteStreamTarget[] = [];
532
- const updatedTargets: QuoteStreamTarget[] = [];
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.quoteTargets.size,
581
- channelTargets: this.channelListeners.size,
302
+ quoteTargets: this.quotes.size,
303
+ channelTargets: this.listeners.chatChannels.size,
582
304
  });
583
- this.channelListeners.clear();
584
- this.offeredFeatureListeners.clear();
585
- this.connectionListeners.clear();
586
- this.chatNotificationListeners.clear();
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
- let parsed: any;
609
- try {
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
- }
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
- if (
654
- parsed?.type === "chat.message" &&
655
- typeof parsed.channelId === "string" &&
656
- parsed.data
657
- ) {
658
- const message = normalizeChatMessage(parsed.data as ChatMessage);
659
- for (const listener of this.channelListeners.get(parsed.channelId) ??
660
- []) {
661
- listener(message);
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
- parsed?.type === "chat.reactions" &&
668
- typeof parsed.channelId === "string" &&
669
- typeof parsed.data?.messageId === "string"
335
+ this.delegate.isUsingWebSocketToken() &&
336
+ this.delegate.clearWebSocketTokenForFallback()
670
337
  ) {
671
- const update: ChatReactionsUpdate = {
672
- channelId: parsed.channelId,
673
- messageId: parsed.data.messageId,
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
- 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
- }
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 (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);
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
- private emitScannerEvent(
837
- scanner: ScannerKind,
838
- event: ScannerFeedEvent,
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.quoteTargets.size > 0 || this.scannerListeners.size > 0 || this.tapeListeners.size > 0)
848
- return true;
359
+ if (this.hasMarketStreams()) return true;
849
360
  return (
850
361
  this.delegate.hasSessionCredential() &&
851
362
  this.delegate.hasVerifiedUser() &&
852
- (this.channelListeners.size > 0 ||
853
- this.teamNotificationListeners.size > 0 ||
854
- this.cloudEventListeners.size > 0)
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
- private ensureSocket(): void {
859
- if (!this.shouldKeepSocketOpen() || this.ws || this.reconnectTimer) return;
860
-
861
- const socketBaseUrl = this.getWebSocketBaseUrl();
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
- private scheduleQuoteSubscriptionFlush(): void {
1131
- if (this.quoteSubscriptionFlushTimer) return;
1132
- this.quoteSubscriptionFlushTimer = setTimeout(() => {
1133
- this.quoteSubscriptionFlushTimer = null;
1134
- this.flushQueuedQuoteSubscriptions();
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
- private queueQuoteSubscribes(targets: QuoteStreamTarget[]): void {
1139
- for (const target of targets) {
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
- private queueQuoteUnsubscribes(targets: QuoteStreamTarget[]): void {
1148
- for (const target of targets) {
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
- private flushQueuedQuoteSubscriptions(): void {
1157
- if (this.ws?.readyState !== WebSocket.OPEN) {
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
- private serializeQuoteStreamTarget(
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
  }