gloomberb 0.19.3 → 0.19.5

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 (226) hide show
  1. package/package.json +4 -2
  2. package/src/api-client/errors.ts +8 -0
  3. package/src/api-client/index.ts +18 -0
  4. package/src/api-client/request.ts +295 -42
  5. package/src/api-client/socket.ts +95 -0
  6. package/src/app/keybindings/actions.ts +1 -1
  7. package/src/app/pane-runtime/index.tsx +1 -1
  8. package/src/app/pane-runtime/ticker-inspector-runtime.ts +1 -1
  9. package/src/app/pane-runtime/ticker-open-runtime.ts +1 -1
  10. package/src/app/pane-runtime/ticker-open-target.ts +12 -2
  11. package/src/cli/commands/command-utils.ts +4 -0
  12. package/src/cli/commands/market.ts +119 -27
  13. package/src/cli/commands/search.ts +1 -1
  14. package/src/cli/commands/ticker.ts +10 -6
  15. package/src/cli/currency-name-hint.ts +60 -0
  16. package/src/cli/desktop-pane-shot-api-policy.ts +10 -2
  17. package/src/cli/desktop-pane-shot.ts +2 -1
  18. package/src/cli/history-rows.ts +18 -1
  19. package/src/cli/known-gaps.ts +17 -2
  20. package/src/cli/not-a-ticker.ts +5 -3
  21. package/src/cli/pane-functions/catalog.ts +9 -1
  22. package/src/cli/pane-functions/headless.ts +7 -3
  23. package/src/cli/pane-functions/market-session.ts +6 -7
  24. package/src/cli/series-search.ts +4 -5
  25. package/src/components/chart/composite/panel-bitmap.ts +28 -2
  26. package/src/components/chart/composite/time-axis.ts +17 -2
  27. package/src/components/command-bar/action-runtime.ts +2 -0
  28. package/src/components/command-bar/commands/direct/runtime.ts +3 -3
  29. package/src/components/command-bar/helpers.ts +2 -0
  30. package/src/components/command-bar/list/model.ts +9 -0
  31. package/src/components/command-bar/pane-actions.ts +46 -35
  32. package/src/components/command-bar/pane-templates/workflow.ts +6 -0
  33. package/src/components/command-bar/panel/index.tsx +30 -3
  34. package/src/components/command-bar/panel/types.ts +7 -0
  35. package/src/components/command-bar/routes/root/results.ts +4 -4
  36. package/src/components/command-bar/routes/root/selection.ts +3 -2
  37. package/src/components/command-bar/routes/ticker-search/actions.ts +21 -16
  38. package/src/components/command-bar/routing/launch-request.ts +3 -2
  39. package/src/components/command-bar/routing/list-state.ts +4 -1
  40. package/src/components/command-bar/surface/index.tsx +15 -1
  41. package/src/components/layout/floating-pane.tsx +10 -0
  42. package/src/components/layout/pane/frame.tsx +6 -0
  43. package/src/components/layout/pane/header.tsx +244 -42
  44. package/src/components/layout/pane/index.tsx +20 -2
  45. package/src/components/layout/shell/active-drag.ts +160 -28
  46. package/src/components/layout/shell/drag/index.ts +99 -96
  47. package/src/components/layout/shell/drag/live.ts +3 -17
  48. package/src/components/layout/shell/drag/magnets.ts +304 -0
  49. package/src/components/layout/shell/drag/overlays.tsx +77 -75
  50. package/src/components/layout/shell/drag/runtime.ts +12 -7
  51. package/src/components/layout/shell/index.tsx +66 -32
  52. package/src/components/layout/shell/native/pointer-runtime.ts +7 -2
  53. package/src/components/layout/shell/native/surfaces.ts +1 -9
  54. package/src/components/layout/shell/native/window-state.ts +21 -25
  55. package/src/components/layout/shell/pane/layers.tsx +153 -24
  56. package/src/components/layout/shell/shortcuts.ts +4 -1
  57. package/src/components/layout/shell/terminal-pointer-runtime.ts +24 -1
  58. package/src/components/layout/shell/window-mode/overlays.tsx +14 -6
  59. package/src/components/layout/status-bar.tsx +75 -6
  60. package/src/components/layout/window-controls.tsx +96 -35
  61. package/src/components/layout/window-fullscreen.ts +20 -0
  62. package/src/components/quote-flash.ts +36 -32
  63. package/src/core/app-runtime.ts +4 -1
  64. package/src/core/connection-health.ts +76 -1
  65. package/src/core/state/app/command-bar-launch.ts +12 -0
  66. package/src/core/state/app/layout.ts +4 -3
  67. package/src/core/state/app/types.ts +4 -1
  68. package/src/data/config/layout.ts +2 -2
  69. package/src/data/config/store/fold-panes.ts +6 -1
  70. package/src/i18n/es.ts +8 -1
  71. package/src/i18n/ja.ts +8 -1
  72. package/src/i18n/ko.ts +8 -1
  73. package/src/i18n/zh-cn.ts +8 -1
  74. package/src/i18n/zh-tw.ts +8 -1
  75. package/src/layout/pane-follow.ts +3 -2
  76. package/src/layout/pane-layout-move.ts +2 -1
  77. package/src/layout/pane-manager/dock-stack.ts +38 -0
  78. package/src/layout/pane-manager/dock-tree.ts +76 -15
  79. package/src/layout/pane-manager/docking.ts +48 -6
  80. package/src/layout/pane-manager/floating-actions.ts +12 -3
  81. package/src/layout/pane-manager/floating-placement.ts +189 -0
  82. package/src/layout/pane-manager/floating.ts +23 -4
  83. package/src/layout/pane-manager/gridlock.ts +16 -4
  84. package/src/layout/pane-manager/hidden-panes.ts +30 -1
  85. package/src/layout/pane-manager/index.ts +2 -0
  86. package/src/layout/pane-manager/layout-state.ts +17 -0
  87. package/src/layout/pane-manager/types.ts +4 -1
  88. package/src/layout/ticker-retarget.ts +88 -0
  89. package/src/layout-marketplace/cloud.ts +9 -1
  90. package/src/market-data/connection-follow.ts +68 -0
  91. package/src/market-data/coordinator/entries.ts +15 -3
  92. package/src/market-data/coordinator/events.ts +17 -1
  93. package/src/market-data/coordinator/financials.ts +20 -7
  94. package/src/market-data/coordinator/index.ts +217 -4
  95. package/src/market-data/coordinator/quotes.ts +10 -0
  96. package/src/market-data/frame-scheduler.ts +47 -10
  97. package/src/market-data/frame-wake.ts +74 -0
  98. package/src/market-data/futures-board.ts +7 -6
  99. package/src/market-data/hooks.tsx +43 -3
  100. package/src/market-data/performance.ts +78 -9
  101. package/src/market-data/request-types.ts +6 -3
  102. package/src/news/aggregator.ts +12 -1
  103. package/src/plugins/builtin/alerts/cli.ts +2 -1
  104. package/src/plugins/builtin/analytics/risk-evidence.ts +1 -0
  105. package/src/plugins/builtin/attention/evidence.ts +1 -1
  106. package/src/plugins/builtin/awards/client.ts +1 -1
  107. package/src/plugins/builtin/awards/evidence.ts +1 -1
  108. package/src/plugins/builtin/awards/pane.tsx +2 -1
  109. package/src/plugins/builtin/bond-calculator/math.ts +1 -1
  110. package/src/plugins/builtin/broker-manager/footer.ts +3 -2
  111. package/src/plugins/builtin/broker-manager/index.tsx +2 -1
  112. package/src/plugins/builtin/broker-manager/keyboard.ts +2 -1
  113. package/src/plugins/builtin/buildout/company/pane.tsx +2 -1
  114. package/src/plugins/builtin/buildout/model/index.ts +6 -0
  115. package/src/plugins/builtin/buildout/pane/index.tsx +2 -1
  116. package/src/plugins/builtin/catalysts/evidence.ts +1 -1
  117. package/src/plugins/builtin/catalysts/pane.tsx +2 -1
  118. package/src/plugins/builtin/chart-composer/headless.ts +40 -1
  119. package/src/plugins/builtin/chart-composer/index.tsx +13 -0
  120. package/src/plugins/builtin/chat/controller/index.ts +10 -3
  121. package/src/plugins/builtin/chat/controller/session-runtime.ts +9 -2
  122. package/src/plugins/builtin/chat/status-widget.tsx +3 -1
  123. package/src/plugins/builtin/cloud-tweets/table.tsx +3 -2
  124. package/src/plugins/builtin/comment-letters/client.ts +2 -1
  125. package/src/plugins/builtin/company-kpis/client.ts +1 -1
  126. package/src/plugins/builtin/company-kpis/pane.tsx +2 -1
  127. package/src/plugins/builtin/company-kpis/screenshot-evidence.ts +3 -2
  128. package/src/plugins/builtin/cot/headless.ts +9 -3
  129. package/src/plugins/builtin/cot/model.ts +44 -3
  130. package/src/plugins/builtin/credit-documents/client.ts +1 -1
  131. package/src/plugins/builtin/credit-documents/evidence.ts +1 -1
  132. package/src/plugins/builtin/credit-documents/pane.tsx +2 -1
  133. package/src/plugins/builtin/earnings-calls/pane.tsx +1 -1
  134. package/src/plugins/builtin/earnings-ripple/index.tsx +6 -1
  135. package/src/plugins/builtin/econ/calendar-model.ts +2 -0
  136. package/src/plugins/builtin/econ/fred-catalog.ts +5 -5
  137. package/src/plugins/builtin/econ/print-watch.ts +3 -1
  138. package/src/plugins/builtin/futures/series.ts +16 -1
  139. package/src/plugins/builtin/fx-matrix/headless.ts +4 -2
  140. package/src/plugins/builtin/fx-matrix/index.tsx +37 -3
  141. package/src/plugins/builtin/fx-matrix/pairs.ts +15 -0
  142. package/src/plugins/builtin/gpu/headless.ts +2 -1
  143. package/src/plugins/builtin/help/function-card.tsx +2 -1
  144. package/src/plugins/builtin/help/index.tsx +3 -2
  145. package/src/plugins/builtin/insider/display.ts +45 -6
  146. package/src/plugins/builtin/ipo-calendar/model.ts +2 -0
  147. package/src/plugins/builtin/iv-history/client.ts +2 -1
  148. package/src/plugins/builtin/iv-history/headless.ts +2 -1
  149. package/src/plugins/builtin/jobs/pages.ts +4 -4
  150. package/src/plugins/builtin/kelly-sizer/headless.ts +2 -1
  151. package/src/plugins/builtin/market-heatmap/index.tsx +2 -1
  152. package/src/plugins/builtin/members/client.ts +1 -1
  153. package/src/plugins/builtin/mna/distress/client.ts +1 -0
  154. package/src/plugins/builtin/mna/pane.tsx +4 -1
  155. package/src/plugins/builtin/options/market-reference.ts +1 -1
  156. package/src/plugins/builtin/options/open-interest-as-of.ts +3 -1
  157. package/src/plugins/builtin/options/view.tsx +2 -1
  158. package/src/plugins/builtin/options-calculator/evidence.ts +1 -1
  159. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +1 -1
  160. package/src/plugins/builtin/options-scenario/csp-screen.ts +8 -4
  161. package/src/plugins/builtin/options-scenario/csp.ts +28 -9
  162. package/src/plugins/builtin/options-scenario/evidence.ts +5 -4
  163. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  164. package/src/plugins/builtin/perps/client.ts +1 -1
  165. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
  166. package/src/plugins/builtin/portfolio-list/pane/index.tsx +7 -3
  167. package/src/plugins/builtin/portfolio-list/use-throttled-memo.ts +10 -19
  168. package/src/plugins/builtin/research/analyst-model.ts +1 -0
  169. package/src/plugins/builtin/research/equity-diagnostic-pane.tsx +2 -1
  170. package/src/plugins/builtin/research/index.tsx +1 -0
  171. package/src/plugins/builtin/research/relative-valuation-currency.ts +1 -1
  172. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -1
  173. package/src/plugins/builtin/research-search/command-bar-search.ts +3 -1
  174. package/src/plugins/builtin/research-search/snippet.ts +1 -0
  175. package/src/plugins/builtin/revenue-breakdown/client.ts +3 -2
  176. package/src/plugins/builtin/seasonality/headless.ts +2 -1
  177. package/src/plugins/builtin/sec/command-bar-search.ts +3 -2
  178. package/src/plugins/builtin/sec/index.tsx +7 -4
  179. package/src/plugins/builtin/sec/row-summaries.ts +28 -12
  180. package/src/plugins/builtin/sectors/client.ts +18 -8
  181. package/src/plugins/builtin/sectors/index.tsx +19 -5
  182. package/src/plugins/builtin/short-interest/watch-client.ts +2 -1
  183. package/src/plugins/builtin/social-mentions/client.ts +2 -1
  184. package/src/plugins/builtin/supply-chain/client.ts +1 -1
  185. package/src/plugins/builtin/supply-chain/evidence.ts +1 -1
  186. package/src/plugins/builtin/supply-chain/graph-pane.tsx +2 -1
  187. package/src/plugins/builtin/supply-chain/pane.tsx +2 -1
  188. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +1 -1
  189. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +24 -4
  190. package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +1 -1
  191. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -1
  192. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +25 -2
  193. package/src/plugins/builtin/time-sales/client.ts +1 -0
  194. package/src/plugins/builtin/vol-surface/client.ts +2 -1
  195. package/src/plugins/builtin/yield-curve/headless.ts +3 -1
  196. package/src/portfolio/column-values.ts +76 -10
  197. package/src/react/async-resource.ts +12 -0
  198. package/src/remote/controller.ts +3 -1
  199. package/src/renderers/browser/app-services.ts +8 -1
  200. package/src/renderers/browser/cloud-transport.ts +6 -1
  201. package/src/renderers/cloudflare/worker.ts +24 -2
  202. package/src/renderers/dom/host/box.tsx +204 -176
  203. package/src/renderers/dom/host/style.ts +49 -20
  204. package/src/renderers/dom/host/text.tsx +3 -2
  205. package/src/renderers/dom/styles.css +32 -0
  206. package/src/renderers/electrobun/bun/desktop/backend.ts +2 -0
  207. package/src/renderers/electrobun/bun/desktop/host-requests.ts +25 -1
  208. package/src/renderers/electrobun/bun/desktop/relaunch.ts +9 -1
  209. package/src/renderers/electrobun/bun/desktop/windows-script.ts +9 -6
  210. package/src/renderers/electrobun/bun/window/windows-native.ts +26 -1
  211. package/src/renderers/electrobun/shared/protocol.ts +6 -0
  212. package/src/renderers/electrobun/view/ui-host.tsx +7 -0
  213. package/src/renderers/electrobun/view/window-fullscreen.ts +10 -3
  214. package/src/shares/portable-layout.ts +99 -2
  215. package/src/sources/provider-router/index.ts +9 -3
  216. package/src/sources/provider-router/sources.ts +26 -1
  217. package/src/sync/core-contributors.ts +18 -4
  218. package/src/time-series/price-units.ts +11 -0
  219. package/src/time-series/resolve.ts +12 -0
  220. package/src/types/config.ts +17 -1
  221. package/src/types/plugin.ts +6 -0
  222. package/src/ui/host.tsx +2 -0
  223. package/src/utils/currency-names.ts +20 -0
  224. package/src/utils/currency-pair.ts +6 -0
  225. package/src/utils/exchange-rate-snapshot.ts +20 -2
  226. package/src/utils/fx-market-hours.ts +43 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gloomberb",
3
- "version": "0.19.3",
4
- "packageManager": "bun@1.3.11",
3
+ "version": "0.19.5",
4
+ "packageManager": "bun@1.3.14",
5
5
  "description": "Market research and portfolio tracker for the terminal",
6
6
  "module": "src/public/index.ts",
7
7
  "type": "module",
@@ -99,6 +99,7 @@
99
99
  "kit:page": "bun run scripts/pane-chrome/kit-page.ts",
100
100
  "audit:ui:compare": "bun run scripts/pane-chrome/ui-audit-compare.ts",
101
101
  "benchmark:pane-drag:compare": "bun run scripts/pane-chrome/frame-budget.ts",
102
+ "benchmark:pane-drag:smoothness": "bun run scripts/pane-chrome/drag-smoothness.ts",
102
103
  "test:global-upgrade": "bun run scripts/smoke-global-upgrade.ts",
103
104
  "release": "./scripts/release.sh"
104
105
  },
@@ -125,6 +126,7 @@
125
126
  "playwright-core": "1.60.0",
126
127
  "png-to-ico": "^2.1.8",
127
128
  "rcedit": "^4.0.1",
129
+ "resedit": "^3.1.0",
128
130
  "typescript": "^5.9.2",
129
131
  "wrangler": "^4.0.0"
130
132
  },
@@ -22,6 +22,14 @@ export class ApiRequestError extends Error {
22
22
  }
23
23
  }
24
24
 
25
+ /** What a pane screenshot's local proxy answers (403) to a request the capture does not send. */
26
+ export const SHOT_REQUEST_REFUSED = "The pane screenshot does not send this request.";
27
+
28
+ /** Whether `error` is the capture's own refusal of a request, not an answer of the service. */
29
+ export function isShotRequestRefused(error: unknown): boolean {
30
+ return error instanceof ApiRequestError && error.status === 403 && error.code === SHOT_REQUEST_REFUSED;
31
+ }
32
+
25
33
  /**
26
34
  * A write refused with 412 because the server holds a newer revision than the
27
35
  * one the write was based on. `current` is what the server holds now, or null
@@ -107,6 +107,8 @@ class GloomApiClient {
107
107
  private sessionRevalidationGeneration = 0;
108
108
  private sessionRevalidationTimer: ReturnType<typeof setTimeout> | null = null;
109
109
  private sessionChecked = false;
110
+ /** When a session check last answered for the credential in place (`recentSession`). */
111
+ private sessionCheckedAt: number | null = null;
110
112
  /** Last few session transitions, content-free, for app://auth. */
111
113
  private authTrace: Array<{ at: number; event: string; token: boolean; user: string }> = [];
112
114
  private sessionRequest: PendingSessionRequest | null = null;
@@ -142,6 +144,7 @@ class GloomApiClient {
142
144
  ...user,
143
145
  }));
144
146
  },
147
+ onServiceAnswered: () => this.transport.noteServiceAnswered(),
145
148
  });
146
149
  private readonly chat: CloudChatApi = new CloudChatApi({
147
150
  request: (path, options) => this.request(path, options),
@@ -312,6 +315,8 @@ class GloomApiClient {
312
315
  const changed = this.socketEntitlementKey(this.currentUser) !== this.socketEntitlementKey(user);
313
316
  this.traceAuth("setCurrentUser", user);
314
317
  this.currentUser = user;
318
+ // Another account, or a plan that changed, reads other answers: no later read joins one sent before.
319
+ if (changed) this.transport.forgetSharedReads();
315
320
  if (confirmSession) {
316
321
  this.clearSessionRevalidationTimer();
317
322
  this.verifiedSessionIdentity = user ? {} : null;
@@ -484,6 +489,17 @@ class GloomApiClient {
484
489
  }
485
490
  }
486
491
 
492
+ /**
493
+ * What a session check made within `maxAgeMs` found for the credential in
494
+ * place, or undefined when none did and the server has to be asked. Lets a
495
+ * view that opens right after the app checked its session use that answer.
496
+ */
497
+ recentSession(maxAgeMs: number): { user: AuthUser | null } | undefined {
498
+ if (!this.sessionChecked || this.sessionCheckedAt === null || this.sessionTransitions > 0 || this.sessionRequest) return undefined;
499
+ if (Date.now() - this.sessionCheckedAt > maxAgeMs) return undefined;
500
+ return { user: this.currentUser };
501
+ }
502
+
487
503
  async getSession(isCurrent: () => boolean = () => true): Promise<AuthUser | null> {
488
504
  if (!isCurrent()) return this.currentUser;
489
505
  const existing = this.sessionRequest;
@@ -507,6 +523,7 @@ class GloomApiClient {
507
523
  .then(({ user, validated }) => {
508
524
  if (validated && canApply()) {
509
525
  this.sessionChecked = true;
526
+ this.sessionCheckedAt = Date.now();
510
527
  this.clearSessionRevalidationTimer();
511
528
  }
512
529
  this.traceAuth(validated ? "getSession:done" : "getSession:retained", user);
@@ -913,6 +930,7 @@ class GloomApiClient {
913
930
  this.sessionRequestGeneration += 1;
914
931
  this.sessionRequest = null;
915
932
  this.socket.dispose();
933
+ this.transport.dispose();
916
934
  }
917
935
 
918
936
  searchInstruments = this.data.searchInstruments.bind(this.data);
@@ -56,6 +56,13 @@ const UPLOAD_REQUEST_LIMIT_MS = 300_000;
56
56
  */
57
57
  const SERVICE_PROBE_TIMEOUT_MS = 3_000;
58
58
  const SERVICE_PROBE_PATH = "/health";
59
+ /**
60
+ * While the service is unreachable it is asked whether it answers again, this
61
+ * soon after the outage began and then twice as long after each check up to
62
+ * the cap, so the app hears it is back without waiting for a pane to ask.
63
+ */
64
+ const RECOVERY_PROBE_FIRST_MS = 2_000;
65
+ const RECOVERY_PROBE_MAX_MS = 15_000;
59
66
  // Research may fill missing sections after a primary read; quote/history reads remain latency bounded.
60
67
  const RESEARCH_MARKET_PATHS = new Set([
61
68
  "/market/dividends", "/market/short-interest", "/market/movers", "/market/trending",
@@ -82,6 +89,49 @@ type CloudApiStreamFetch = (
82
89
  init?: RequestInit,
83
90
  ) => Promise<Response>;
84
91
  type SessionCookieName = (typeof SESSION_COOKIE_NAMES)[number];
92
+ /**
93
+ * Whether a GET may join an identical one still out (`readShared`): market
94
+ * data reads, which panes opening together ask for at once, and only when the
95
+ * caller did not ask the HTTP cache for a fresh copy. Elsewhere a read asked
96
+ * after another is often asked because the first may be stale (a forced
97
+ * refresh), and joining it would hand back the older answer.
98
+ */
99
+ function isSharedRead(path: string, options: RequestInit | undefined): boolean {
100
+ return path.startsWith("/market/") && options?.cache === undefined;
101
+ }
102
+
103
+ /**
104
+ * Whether a request can change what a later read answers. POSTs under the
105
+ * market and cloud data paths are batch reads (quotes, histories, perps,
106
+ * exposure), and telemetry and research activity reports change nothing a
107
+ * read returns; everything else that is not a GET is taken as a write.
108
+ */
109
+ function changesReads(method: string, path: string): boolean {
110
+ if (method === "GET" || method === "HEAD") return false;
111
+ if (path.startsWith("/cloud/auth/")) return true;
112
+ return !/^\/(?:market|cloud|telemetry|activity)\//.test(path);
113
+ }
114
+
115
+ /** A request's headers in a fixed order, so two identical requests compare equal. */
116
+ function headerLines(headers: Headers): string {
117
+ const lines: string[] = [];
118
+ headers.forEach((value, name) => { lines.push(`${name}:${value}`); });
119
+ return lines.sort().join("\n");
120
+ }
121
+ /**
122
+ * A response and the read of its body, which several callers can each parse.
123
+ * The body is read apart from the headers: a caller takes the session cookie
124
+ * from the headers even when the body never arrives.
125
+ */
126
+ interface CloudApiAnswer {
127
+ response: CloudApiResponse;
128
+ text: Promise<string>;
129
+ }
130
+ interface SharedRead {
131
+ answer: Promise<CloudApiAnswer>;
132
+ controller: AbortController;
133
+ waiters: number;
134
+ }
85
135
 
86
136
  export interface CloudApiFetchTransportOptions {
87
137
  /**
@@ -200,6 +250,34 @@ export async function putWithRevision<T, Current extends { revision: number }>(
200
250
  }
201
251
  }
202
252
 
253
+ /**
254
+ * Background traffic. Crash reports, usage counts and command-search reports:
255
+ * a rate-limited, timed-out or missing one must not show up as a Cloud outage
256
+ * in the connections pane, and one that never got out (an ad blocker refuses
257
+ * `/telemetry/` in a browser that reaches everything else) says nothing of
258
+ * whether the data service answers. Nor must the map's probe for geo layers,
259
+ * which a server without them answers with 404, or a ticker change lookup: a
260
+ * note beside a quote, never one of the refused market requests a lookup of
261
+ * many symbols waits out and retries. Nor the tickers beside a list of
262
+ * organization names, which say so in place, or a 13F filer's EDGAR filing
263
+ * list, whose report says it went unchecked, or a company's other listings,
264
+ * beside a list check that still answers for the listing itself. Nor the
265
+ * batched searches and ticker changes a list of symbols starts with: a service
266
+ * without them answers 404, and whatever they leave unanswered is looked up
267
+ * one symbol at a time, which is tracked.
268
+ */
269
+ function isBackgroundRequest(path: string): boolean {
270
+ return path.startsWith("/telemetry/")
271
+ || path === "/assist/searches"
272
+ || path === "/cloud/geo/layers"
273
+ || path.startsWith("/cloud/sec/13f/filer?")
274
+ || path.startsWith("/market/ticker-changes?")
275
+ || path.startsWith("/market/issuer-listings?")
276
+ || path === "/market/ticker-changes/batch"
277
+ || path === "/market/search/batch"
278
+ || path === "/market/organization-tickers";
279
+ }
280
+
203
281
  function throwIfRequestAborted(signal: AbortSignal | null | undefined): void {
204
282
  if (!signal?.aborted) return;
205
283
  throw (
@@ -228,6 +306,16 @@ export class CloudApiRequestTransport {
228
306
  /** Requests waiting under a deadline: the check that the service answers runs only while one is. */
229
307
  private pending = 0;
230
308
  private probe: AbortController | null = null;
309
+ /** The next check whether an unreachable service answers again, and how long after it the one after waits. */
310
+ private recoveryTimer: ReturnType<typeof setTimeout> | null = null;
311
+ private recoveryDelayMs = RECOVERY_PROBE_FIRST_MS;
312
+ /** Bumped by `dispose`, so a check still out does not schedule the next one. */
313
+ private recoveryGeneration = 0;
314
+ /** The check whether an unreachable service answers again, while it is out, and when the last one went out. */
315
+ private recoveryProbe: AbortController | null = null;
316
+ private lastRecoveryProbeAt = Number.NEGATIVE_INFINITY;
317
+ /** GETs still out, by URL and headers, that an identical GET joins instead of sending its own (`readShared`). */
318
+ private readonly sharedReads = new Map<string, SharedRead>();
231
319
 
232
320
  readonly baseUrl = getCloudApiBaseUrl();
233
321
 
@@ -258,12 +346,14 @@ export class CloudApiRequestTransport {
258
346
  }
259
347
 
260
348
  setCookieSessionMode(enabled: boolean): void {
349
+ if (this.cookieSessionMode !== enabled) this.forgetSharedReads();
261
350
  this.cookieSessionMode = enabled;
262
351
  }
263
352
 
264
353
  setSessionToken(token: string | null): void {
265
354
  if (this.sessionToken !== token) {
266
355
  this.sessionCookieName = null;
356
+ this.forgetSharedReads();
267
357
  }
268
358
  this.sessionToken = token;
269
359
  if (!token) {
@@ -275,6 +365,16 @@ export class CloudApiRequestTransport {
275
365
  this.websocketToken = token;
276
366
  }
277
367
 
368
+ /**
369
+ * Stops later GETs from joining the ones still out (`readShared`); callers
370
+ * already waiting keep their answer. A write, or another account signing
371
+ * in, can change what a read answers, and in cookie mode a request's
372
+ * headers do not say whose session it carries.
373
+ */
374
+ forgetSharedReads(): void {
375
+ this.sharedReads.clear();
376
+ }
377
+
278
378
  getSocketAuthToken(): string | null {
279
379
  return this.websocketToken || this.sessionToken;
280
380
  }
@@ -340,11 +440,11 @@ export class CloudApiRequestTransport {
340
440
  );
341
441
  }
342
442
 
343
- async request<T>(path: string, options?: RequestInit, canApplySession: () => boolean = () => true): Promise<T> {
443
+ async request<T>(path: string, options?: RequestInit, canApplySession?: () => boolean): Promise<T> {
344
444
  return this.withDeadline(path, this.deadlineFor(path), options?.signal, (signal) => this.performRequest<T>(path, {
345
445
  ...options,
346
446
  signal,
347
- }, canApplySession));
447
+ }, canApplySession ?? (() => true), undefined, !canApplySession && isSharedRead(path, options)));
348
448
  }
349
449
 
350
450
  /**
@@ -422,7 +522,7 @@ export class CloudApiRequestTransport {
422
522
  // The caller gave up first: its abort settles the request, and says nothing of the connection.
423
523
  if (callerSignal?.aborted) return;
424
524
  if (!answered()) {
425
- this.recordNoAnswer(generation, true);
525
+ if (!isBackgroundRequest(path)) this.recordNoAnswer(generation, true);
426
526
  fail(new DataServiceUnreachableError(timedOut(deadline.answerMs)));
427
527
  } else if (deadline.limitMs > deadline.answerMs) {
428
528
  timers.push(setTimeout(() => fail(timedOut(deadline.limitMs)), deadline.limitMs - deadline.answerMs));
@@ -448,7 +548,11 @@ export class CloudApiRequestTransport {
448
548
  * A caller's abort stays an abort. An answer of any status says the
449
549
  * connection works, for the deadlines of the requests beside it.
450
550
  */
451
- private async reachService<R>(fetch: () => Promise<R>, signal: AbortSignal | null | undefined): Promise<R> {
551
+ private async reachService<R>(
552
+ fetch: () => Promise<R>,
553
+ signal: AbortSignal | null | undefined,
554
+ background = false,
555
+ ): Promise<R> {
452
556
  const generation = cloudApiTransportGeneration;
453
557
  let response: R;
454
558
  try {
@@ -456,7 +560,8 @@ export class CloudApiRequestTransport {
456
560
  } catch (error) {
457
561
  if (signal?.aborted) throw error;
458
562
  const failure = asDataServiceFailure(error);
459
- if (failure instanceof DataServiceUnreachableError) this.recordNoAnswer(generation, false);
563
+ // Background traffic that never got out says nothing of the service (`isBackgroundRequest`).
564
+ if (failure instanceof DataServiceUnreachableError && !background) this.recordNoAnswer(generation, false);
460
565
  throw failure;
461
566
  }
462
567
  this.recordAnswer();
@@ -467,15 +572,42 @@ export class CloudApiRequestTransport {
467
572
  private forgetOtherTransport(): void {
468
573
  if (this.fetchTransport || this.connectionGeneration === cloudApiTransportGeneration) return;
469
574
  this.connectionGeneration = cloudApiTransportGeneration;
470
- this.unreachable = false;
471
- this.hungAt = null;
575
+ this.markReachable();
472
576
  }
473
577
 
474
578
  /** Something came back from the service: the connection works. */
475
579
  private recordAnswer(): void {
476
580
  this.answers += 1;
477
- this.unreachable = false;
581
+ this.markReachable();
582
+ }
583
+
584
+ /**
585
+ * The service answered on another channel (the quote stream opened, or sent
586
+ * a frame). That alone does not end an outage: a stream can run while
587
+ * requests still fail (a proxy that lets one through and not the other),
588
+ * and ending the outage on each frame would start it again at the stream's
589
+ * tick rate. While the service is unreachable this checks over HTTP at once
590
+ * instead (`runRecoveryCheck`), one check at a time and at most one per
591
+ * RECOVERY_PROBE_FIRST_MS. It does not count toward the deadlines of
592
+ * requests in flight, which wait for an answer over this transport.
593
+ */
594
+ noteServiceAnswered(): void {
595
+ if (!this.unreachable || this.recoveryProbe) return;
596
+ if (Date.now() - this.lastRecoveryProbeAt < RECOVERY_PROBE_FIRST_MS) return;
597
+ this.stopRecoveryChecks();
598
+ this.runRecoveryCheck();
599
+ }
600
+
601
+ /**
602
+ * Ends an outage: requests stop failing fast, and the connections registry
603
+ * hears the service answers again, which asks again for what failed meanwhile.
604
+ */
605
+ private markReachable(): void {
478
606
  this.hungAt = null;
607
+ if (!this.unreachable) return;
608
+ this.unreachable = false;
609
+ this.stopRecoveryChecks();
610
+ this.connectionHealth.reportReachability(GLOOM_CLOUD_HTTP_CONNECTION_ID, true);
479
611
  }
480
612
 
481
613
  /**
@@ -485,8 +617,66 @@ export class CloudApiRequestTransport {
485
617
  */
486
618
  private recordNoAnswer(generation: number, hung: boolean): void {
487
619
  if (!this.fetchTransport && generation !== cloudApiTransportGeneration) return;
488
- this.unreachable = true;
489
620
  if (hung) this.hungAt = Date.now();
621
+ if (this.unreachable) {
622
+ // A chain of checks stopped by `dispose` starts again.
623
+ this.scheduleRecoveryCheck();
624
+ return;
625
+ }
626
+ this.unreachable = true;
627
+ this.connectionHealth.reportReachability(GLOOM_CLOUD_HTTP_CONNECTION_ID, false);
628
+ this.recoveryDelayMs = RECOVERY_PROBE_FIRST_MS;
629
+ this.scheduleRecoveryCheck();
630
+ }
631
+
632
+ /**
633
+ * Checks again later whether the unreachable service answers: nothing else
634
+ * may be asking (no stream, no pane refreshing), and what failed in the
635
+ * outage is asked again only once something answers. The timer never holds
636
+ * a command's process open.
637
+ */
638
+ private scheduleRecoveryCheck(): void {
639
+ if (this.recoveryTimer || this.recoveryProbe || !this.unreachable) return;
640
+ const timer = setTimeout(() => {
641
+ this.recoveryTimer = null;
642
+ this.runRecoveryCheck();
643
+ }, this.recoveryDelayMs);
644
+ (timer as { unref?: () => void }).unref?.();
645
+ this.recoveryTimer = timer;
646
+ }
647
+
648
+ /** Asks `/health` now whether the unreachable service answers; the next check is scheduled once this one is done. */
649
+ private runRecoveryCheck(): void {
650
+ if (!this.unreachable || this.recoveryProbe) return;
651
+ const generation = this.recoveryGeneration;
652
+ this.lastRecoveryProbeAt = Date.now();
653
+ this.recoveryDelayMs = Math.min(this.recoveryDelayMs * 2, RECOVERY_PROBE_MAX_MS);
654
+ const controller = new AbortController();
655
+ this.recoveryProbe = controller;
656
+ const giveUp = setTimeout(() => controller.abort(), SERVICE_PROBE_TIMEOUT_MS);
657
+ (giveUp as { unref?: () => void }).unref?.();
658
+ (this.fetchTransport ?? cloudApiFetchTransport)(`${this.baseUrl}${SERVICE_PROBE_PATH}`, { signal: controller.signal })
659
+ .then(() => this.recordAnswer(), () => {
660
+ // Intentional ignore: still unreachable; the next check is scheduled below.
661
+ })
662
+ .finally(() => {
663
+ clearTimeout(giveUp);
664
+ if (this.recoveryProbe === controller) this.recoveryProbe = null;
665
+ if (generation === this.recoveryGeneration) this.scheduleRecoveryCheck();
666
+ });
667
+ }
668
+
669
+ private stopRecoveryChecks(): void {
670
+ if (this.recoveryTimer) clearTimeout(this.recoveryTimer);
671
+ this.recoveryTimer = null;
672
+ }
673
+
674
+ /** Stops checking whether an unreachable service answers again; a request that goes unanswered after starts the checks again. */
675
+ dispose(): void {
676
+ this.recoveryGeneration += 1;
677
+ this.stopRecoveryChecks();
678
+ this.recoveryProbe?.abort();
679
+ this.recoveryProbe = null;
490
680
  }
491
681
 
492
682
  /**
@@ -554,8 +744,19 @@ export class CloudApiRequestTransport {
554
744
  options: RequestInit | undefined,
555
745
  canApplySession: () => boolean,
556
746
  send?: CloudApiFetchTransport,
747
+ /**
748
+ * Whether an identical GET already out can answer this one (`readShared`,
749
+ * `isSharedRead`). Never for a request tied to a session check: a newer
750
+ * check must reach the server rather than take an answer about an older
751
+ * credential.
752
+ */
753
+ shareable = false,
557
754
  ): Promise<T> {
558
755
  throwIfRequestAborted(options?.signal);
756
+ const method = (options?.method ?? "GET").toUpperCase();
757
+ // A read asked during or after a write must not take an answer sent before it.
758
+ const writes = changesReads(method, path);
759
+ if (writes) this.forgetSharedReads();
559
760
  const headers = new Headers(options?.headers);
560
761
  if (
561
762
  !headers.has("Content-Type") &&
@@ -569,20 +770,29 @@ export class CloudApiRequestTransport {
569
770
  headers.set("Origin", this.baseUrl);
570
771
 
571
772
  const operation = `${options?.method ?? "GET"} ${path.split("?")[0]}`;
572
- const request = async () => {
573
- const res = await this.reachService(() => (send ?? this.fetchTransport ?? cloudApiFetchTransport)(
574
- `${this.baseUrl}${path}`,
575
- {
576
- ...options,
577
- headers,
578
- credentials: "include",
579
- },
580
- ), options?.signal);
773
+ const url = `${this.baseUrl}${path}`;
774
+ const read = async (signal: AbortSignal | null | undefined): Promise<CloudApiAnswer> => {
775
+ const response = await this.reachService(() => (send ?? this.fetchTransport ?? cloudApiFetchTransport)(url, {
776
+ ...options,
777
+ headers,
778
+ credentials: "include",
779
+ signal,
780
+ }), signal, isBackgroundRequest(path));
781
+ throwIfRequestAborted(signal);
782
+ const text = response.text();
783
+ text.catch(() => { /* Intentional ignore: every caller awaits this body after reading the headers. */ });
784
+ return { response, text };
785
+ };
786
+ const answer = async () => {
787
+ const shared = shareable && !send && method === "GET" && options?.body == null;
788
+ const { response: res, text: body } = shared
789
+ ? await this.readShared(`${url}\n${headerLines(headers)}`, options?.signal, read)
790
+ : await read(options?.signal);
581
791
  throwIfRequestAborted(options?.signal);
582
792
  const ownsCredential = canApplySession() && this.sessionToken === sessionTokenAtRequestStart;
583
793
  if (ownsCredential) this.extractSessionCookie(res);
584
794
  const sessionTokenAfterHeaders = this.sessionToken;
585
- const text = await res.text();
795
+ const text = await body;
586
796
  throwIfRequestAborted(options?.signal);
587
797
 
588
798
  if (!res.ok) {
@@ -604,29 +814,14 @@ export class CloudApiRequestTransport {
604
814
  }
605
815
  return parsed as T;
606
816
  };
607
- // Crash reports, usage counts and command-search reports are background
608
- // traffic: a rate-limited, timed-out or missing one must not show up as a
609
- // Cloud outage in the connections pane. Nor must the map's probe for geo
610
- // layers, which a server without them answers with 404, or a ticker
611
- // change lookup: a note beside a quote, never one of the refused market
612
- // requests a lookup of many symbols waits out and retries. Nor the
613
- // tickers beside a list of organization names, which say so in place,
614
- // or a 13F filer's EDGAR filing list, whose report says it went unchecked,
615
- // or a company's other listings, beside a list check that still answers
616
- // for the listing itself. Nor the batched searches and ticker changes a
617
- // list of symbols starts with: a service without them answers 404, and whatever they leave
618
- // unanswered is looked up one symbol at a time, which is tracked.
619
- if (
620
- path.startsWith("/telemetry/")
621
- || path === "/assist/searches"
622
- || path === "/cloud/geo/layers"
623
- || path.startsWith("/cloud/sec/13f/filer?")
624
- || path.startsWith("/market/ticker-changes?")
625
- || path.startsWith("/market/issuer-listings?")
626
- || path === "/market/ticker-changes/batch"
627
- || path === "/market/search/batch"
628
- || path === "/market/organization-tickers"
629
- ) return request();
817
+ const request = async () => {
818
+ try {
819
+ return await answer();
820
+ } finally {
821
+ if (writes) this.forgetSharedReads();
822
+ }
823
+ };
824
+ if (isBackgroundRequest(path)) return request();
630
825
  return this.connectionHealth.track(
631
826
  GLOOM_CLOUD_HTTP_CONNECTION_ID,
632
827
  operation,
@@ -641,6 +836,64 @@ export class CloudApiRequestTransport {
641
836
  );
642
837
  }
643
838
 
839
+ /**
840
+ * Identical GETs (same URL and headers, so the same credential) asked while
841
+ * one is still out share it: each caller gets the same answer and parses its
842
+ * own copy. Panes that open together ask for the same quote or history from
843
+ * several places at once, and the browser would otherwise send each one and
844
+ * queue them behind each other. A caller that gives up leaves the request
845
+ * running for the others; the last one to give up cancels it.
846
+ */
847
+ private readShared(
848
+ key: string,
849
+ signal: AbortSignal | null | undefined,
850
+ read: (signal: AbortSignal) => Promise<CloudApiAnswer>,
851
+ ): Promise<CloudApiAnswer> {
852
+ throwIfRequestAborted(signal);
853
+ let flight = this.sharedReads.get(key);
854
+ if (!flight) {
855
+ const controller = new AbortController();
856
+ // Joinable until its body is in, not only its headers, and not a moment
857
+ // longer: a caller that has the body can ask again and must go out.
858
+ const done = () => { if (this.sharedReads.get(key) === created) this.sharedReads.delete(key); };
859
+ const answer = read(controller.signal).then((first) => {
860
+ const text = first.text.finally(done);
861
+ text.catch(() => { /* Intentional ignore: each waiter awaits this body and sees its failure. */ });
862
+ return { response: first.response, text };
863
+ }, (error: unknown) => {
864
+ done();
865
+ throw error;
866
+ });
867
+ const created: SharedRead = { answer, controller, waiters: 0 };
868
+ this.sharedReads.set(key, created);
869
+ flight = created;
870
+ }
871
+ const current = flight;
872
+ current.waiters += 1;
873
+ if (!signal) return current.answer;
874
+ // A caller stays on the request until its body is in: giving up while the
875
+ // body is still arriving counts as leaving, as it does before the headers.
876
+ let leave = () => {};
877
+ const left = new Promise<never>((_, reject) => {
878
+ leave = () => {
879
+ current.waiters -= 1;
880
+ reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
881
+ if (current.waiters > 0) return;
882
+ if (this.sharedReads.get(key) === current) this.sharedReads.delete(key);
883
+ current.controller.abort(signal.reason);
884
+ };
885
+ });
886
+ left.catch(() => { /* Intentional ignore: the race below hands this abort to the caller. */ });
887
+ signal.addEventListener("abort", leave, { once: true });
888
+ const stop = () => signal.removeEventListener("abort", leave);
889
+ void current.answer.then((answer) => answer.text).then(stop, stop);
890
+ return Promise.race([current.answer, left]).then((answer) => {
891
+ const text = Promise.race([answer.text, left]);
892
+ text.catch(() => { /* Intentional ignore: the caller awaits this body and sees its failure. */ });
893
+ return { response: answer.response, text };
894
+ });
895
+ }
896
+
644
897
  private extractSessionCookie(res: CloudApiResponse): void {
645
898
  const setCookie = res.headers.getSetCookie?.() ?? [];
646
899
  const fallbackHeader = res.headers.get("set-cookie");