@gloom-sh/terminal 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.
- package/package.json +4 -2
- package/src/api-client/errors.ts +8 -0
- package/src/api-client/index.ts +18 -0
- package/src/api-client/request.ts +295 -42
- package/src/api-client/socket.ts +95 -0
- package/src/app/keybindings/actions.ts +1 -1
- package/src/app/pane-runtime/index.tsx +1 -1
- package/src/app/pane-runtime/ticker-inspector-runtime.ts +1 -1
- package/src/app/pane-runtime/ticker-open-runtime.ts +1 -1
- package/src/app/pane-runtime/ticker-open-target.ts +12 -2
- package/src/cli/commands/command-utils.ts +4 -0
- package/src/cli/commands/market.ts +119 -27
- package/src/cli/commands/search.ts +1 -1
- package/src/cli/commands/ticker.ts +10 -6
- package/src/cli/currency-name-hint.ts +60 -0
- package/src/cli/desktop-pane-shot-api-policy.ts +10 -2
- package/src/cli/desktop-pane-shot.ts +2 -1
- package/src/cli/history-rows.ts +18 -1
- package/src/cli/known-gaps.ts +17 -2
- package/src/cli/not-a-ticker.ts +5 -3
- package/src/cli/pane-functions/catalog.ts +9 -1
- package/src/cli/pane-functions/headless.ts +7 -3
- package/src/cli/pane-functions/market-session.ts +6 -7
- package/src/cli/series-search.ts +4 -5
- package/src/components/chart/composite/panel-bitmap.ts +28 -2
- package/src/components/chart/composite/time-axis.ts +17 -2
- package/src/components/command-bar/action-runtime.ts +2 -0
- package/src/components/command-bar/commands/direct/runtime.ts +3 -3
- package/src/components/command-bar/helpers.ts +2 -0
- package/src/components/command-bar/list/model.ts +9 -0
- package/src/components/command-bar/pane-actions.ts +46 -35
- package/src/components/command-bar/pane-templates/workflow.ts +6 -0
- package/src/components/command-bar/panel/index.tsx +30 -3
- package/src/components/command-bar/panel/types.ts +7 -0
- package/src/components/command-bar/routes/root/results.ts +4 -4
- package/src/components/command-bar/routes/root/selection.ts +3 -2
- package/src/components/command-bar/routes/ticker-search/actions.ts +21 -16
- package/src/components/command-bar/routing/launch-request.ts +3 -2
- package/src/components/command-bar/routing/list-state.ts +4 -1
- package/src/components/command-bar/surface/index.tsx +15 -1
- package/src/components/layout/floating-pane.tsx +10 -0
- package/src/components/layout/pane/frame.tsx +6 -0
- package/src/components/layout/pane/header.tsx +244 -42
- package/src/components/layout/pane/index.tsx +20 -2
- package/src/components/layout/shell/active-drag.ts +160 -28
- package/src/components/layout/shell/drag/index.ts +99 -96
- package/src/components/layout/shell/drag/live.ts +3 -17
- package/src/components/layout/shell/drag/magnets.ts +304 -0
- package/src/components/layout/shell/drag/overlays.tsx +77 -75
- package/src/components/layout/shell/drag/runtime.ts +12 -7
- package/src/components/layout/shell/index.tsx +66 -32
- package/src/components/layout/shell/native/pointer-runtime.ts +7 -2
- package/src/components/layout/shell/native/surfaces.ts +1 -9
- package/src/components/layout/shell/native/window-state.ts +21 -25
- package/src/components/layout/shell/pane/layers.tsx +153 -24
- package/src/components/layout/shell/shortcuts.ts +4 -1
- package/src/components/layout/shell/terminal-pointer-runtime.ts +24 -1
- package/src/components/layout/shell/window-mode/overlays.tsx +14 -6
- package/src/components/layout/status-bar.tsx +75 -6
- package/src/components/layout/window-controls.tsx +96 -35
- package/src/components/layout/window-fullscreen.ts +20 -0
- package/src/components/quote-flash.ts +36 -32
- package/src/core/app-runtime.ts +4 -1
- package/src/core/connection-health.ts +76 -1
- package/src/core/state/app/command-bar-launch.ts +12 -0
- package/src/core/state/app/layout.ts +4 -3
- package/src/core/state/app/types.ts +4 -1
- package/src/data/config/layout.ts +2 -2
- package/src/data/config/store/fold-panes.ts +6 -1
- package/src/i18n/es.ts +8 -1
- package/src/i18n/ja.ts +8 -1
- package/src/i18n/ko.ts +8 -1
- package/src/i18n/zh-cn.ts +8 -1
- package/src/i18n/zh-tw.ts +8 -1
- package/src/layout/pane-follow.ts +3 -2
- package/src/layout/pane-layout-move.ts +2 -1
- package/src/layout/pane-manager/dock-stack.ts +38 -0
- package/src/layout/pane-manager/dock-tree.ts +76 -15
- package/src/layout/pane-manager/docking.ts +48 -6
- package/src/layout/pane-manager/floating-actions.ts +12 -3
- package/src/layout/pane-manager/floating-placement.ts +189 -0
- package/src/layout/pane-manager/floating.ts +23 -4
- package/src/layout/pane-manager/gridlock.ts +16 -4
- package/src/layout/pane-manager/hidden-panes.ts +30 -1
- package/src/layout/pane-manager/index.ts +2 -0
- package/src/layout/pane-manager/layout-state.ts +17 -0
- package/src/layout/pane-manager/types.ts +4 -1
- package/src/layout/ticker-retarget.ts +88 -0
- package/src/layout-marketplace/cloud.ts +9 -1
- package/src/market-data/connection-follow.ts +68 -0
- package/src/market-data/coordinator/entries.ts +15 -3
- package/src/market-data/coordinator/events.ts +17 -1
- package/src/market-data/coordinator/financials.ts +20 -7
- package/src/market-data/coordinator/index.ts +217 -4
- package/src/market-data/coordinator/quotes.ts +10 -0
- package/src/market-data/frame-scheduler.ts +47 -10
- package/src/market-data/frame-wake.ts +74 -0
- package/src/market-data/futures-board.ts +7 -6
- package/src/market-data/hooks.tsx +43 -3
- package/src/market-data/performance.ts +78 -9
- package/src/market-data/request-types.ts +6 -3
- package/src/news/aggregator.ts +12 -1
- package/src/plugins/builtin/alerts/cli.ts +2 -1
- package/src/plugins/builtin/analytics/risk-evidence.ts +1 -0
- package/src/plugins/builtin/attention/evidence.ts +1 -1
- package/src/plugins/builtin/awards/client.ts +1 -1
- package/src/plugins/builtin/awards/evidence.ts +1 -1
- package/src/plugins/builtin/awards/pane.tsx +2 -1
- package/src/plugins/builtin/bond-calculator/math.ts +1 -1
- package/src/plugins/builtin/broker-manager/footer.ts +3 -2
- package/src/plugins/builtin/broker-manager/index.tsx +2 -1
- package/src/plugins/builtin/broker-manager/keyboard.ts +2 -1
- package/src/plugins/builtin/buildout/company/pane.tsx +2 -1
- package/src/plugins/builtin/buildout/model/index.ts +6 -0
- package/src/plugins/builtin/buildout/pane/index.tsx +2 -1
- package/src/plugins/builtin/catalysts/evidence.ts +1 -1
- package/src/plugins/builtin/catalysts/pane.tsx +2 -1
- package/src/plugins/builtin/chart-composer/headless.ts +40 -1
- package/src/plugins/builtin/chart-composer/index.tsx +13 -0
- package/src/plugins/builtin/chat/controller/index.ts +10 -3
- package/src/plugins/builtin/chat/controller/session-runtime.ts +9 -2
- package/src/plugins/builtin/chat/status-widget.tsx +3 -1
- package/src/plugins/builtin/cloud-tweets/table.tsx +3 -2
- package/src/plugins/builtin/comment-letters/client.ts +2 -1
- package/src/plugins/builtin/company-kpis/client.ts +1 -1
- package/src/plugins/builtin/company-kpis/pane.tsx +2 -1
- package/src/plugins/builtin/company-kpis/screenshot-evidence.ts +3 -2
- package/src/plugins/builtin/cot/headless.ts +9 -3
- package/src/plugins/builtin/cot/model.ts +44 -3
- package/src/plugins/builtin/credit-documents/client.ts +1 -1
- package/src/plugins/builtin/credit-documents/evidence.ts +1 -1
- package/src/plugins/builtin/credit-documents/pane.tsx +2 -1
- package/src/plugins/builtin/earnings-calls/pane.tsx +1 -1
- package/src/plugins/builtin/earnings-ripple/index.tsx +6 -1
- package/src/plugins/builtin/econ/calendar-model.ts +2 -0
- package/src/plugins/builtin/econ/fred-catalog.ts +5 -5
- package/src/plugins/builtin/econ/print-watch.ts +3 -1
- package/src/plugins/builtin/futures/series.ts +16 -1
- package/src/plugins/builtin/fx-matrix/headless.ts +4 -2
- package/src/plugins/builtin/fx-matrix/index.tsx +37 -3
- package/src/plugins/builtin/fx-matrix/pairs.ts +15 -0
- package/src/plugins/builtin/gpu/headless.ts +2 -1
- package/src/plugins/builtin/help/function-card.tsx +2 -1
- package/src/plugins/builtin/help/index.tsx +3 -2
- package/src/plugins/builtin/insider/display.ts +45 -6
- package/src/plugins/builtin/ipo-calendar/model.ts +2 -0
- package/src/plugins/builtin/iv-history/client.ts +2 -1
- package/src/plugins/builtin/iv-history/headless.ts +2 -1
- package/src/plugins/builtin/jobs/pages.ts +4 -4
- package/src/plugins/builtin/kelly-sizer/headless.ts +2 -1
- package/src/plugins/builtin/market-heatmap/index.tsx +2 -1
- package/src/plugins/builtin/members/client.ts +1 -1
- package/src/plugins/builtin/mna/distress/client.ts +1 -0
- package/src/plugins/builtin/mna/pane.tsx +4 -1
- package/src/plugins/builtin/options/market-reference.ts +1 -1
- package/src/plugins/builtin/options/open-interest-as-of.ts +3 -1
- package/src/plugins/builtin/options/view.tsx +2 -1
- package/src/plugins/builtin/options-calculator/evidence.ts +1 -1
- package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +1 -1
- package/src/plugins/builtin/options-scenario/csp-screen.ts +8 -4
- package/src/plugins/builtin/options-scenario/csp.ts +28 -9
- package/src/plugins/builtin/options-scenario/evidence.ts +5 -4
- package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
- package/src/plugins/builtin/perps/client.ts +1 -1
- package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
- package/src/plugins/builtin/portfolio-list/pane/index.tsx +7 -3
- package/src/plugins/builtin/portfolio-list/use-throttled-memo.ts +10 -19
- package/src/plugins/builtin/research/analyst-model.ts +1 -0
- package/src/plugins/builtin/research/equity-diagnostic-pane.tsx +2 -1
- package/src/plugins/builtin/research/index.tsx +1 -0
- package/src/plugins/builtin/research/relative-valuation-currency.ts +1 -1
- package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -1
- package/src/plugins/builtin/research-search/command-bar-search.ts +3 -1
- package/src/plugins/builtin/research-search/snippet.ts +1 -0
- package/src/plugins/builtin/revenue-breakdown/client.ts +3 -2
- package/src/plugins/builtin/seasonality/headless.ts +2 -1
- package/src/plugins/builtin/sec/command-bar-search.ts +3 -2
- package/src/plugins/builtin/sec/index.tsx +7 -4
- package/src/plugins/builtin/sec/row-summaries.ts +28 -12
- package/src/plugins/builtin/sectors/client.ts +18 -8
- package/src/plugins/builtin/sectors/index.tsx +19 -5
- package/src/plugins/builtin/short-interest/watch-client.ts +2 -1
- package/src/plugins/builtin/social-mentions/client.ts +2 -1
- package/src/plugins/builtin/supply-chain/client.ts +1 -1
- package/src/plugins/builtin/supply-chain/evidence.ts +1 -1
- package/src/plugins/builtin/supply-chain/graph-pane.tsx +2 -1
- package/src/plugins/builtin/supply-chain/pane.tsx +2 -1
- package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +1 -1
- package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +24 -4
- package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +1 -1
- package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -1
- package/src/plugins/builtin/ticker-detail/overview-tab.tsx +25 -2
- package/src/plugins/builtin/time-sales/client.ts +1 -0
- package/src/plugins/builtin/vol-surface/client.ts +2 -1
- package/src/plugins/builtin/yield-curve/headless.ts +3 -1
- package/src/portfolio/column-values.ts +76 -10
- package/src/react/async-resource.ts +12 -0
- package/src/remote/controller.ts +3 -1
- package/src/renderers/browser/app-services.ts +8 -1
- package/src/renderers/browser/cloud-transport.ts +6 -1
- package/src/renderers/cloudflare/worker.ts +24 -2
- package/src/renderers/dom/host/box.tsx +204 -176
- package/src/renderers/dom/host/style.ts +49 -20
- package/src/renderers/dom/host/text.tsx +3 -2
- package/src/renderers/dom/styles.css +32 -0
- package/src/renderers/electrobun/bun/desktop/backend.ts +2 -0
- package/src/renderers/electrobun/bun/desktop/host-requests.ts +25 -1
- package/src/renderers/electrobun/bun/desktop/relaunch.ts +9 -1
- package/src/renderers/electrobun/bun/desktop/windows-script.ts +9 -6
- package/src/renderers/electrobun/bun/window/windows-native.ts +26 -1
- package/src/renderers/electrobun/shared/protocol.ts +6 -0
- package/src/renderers/electrobun/view/ui-host.tsx +7 -0
- package/src/renderers/electrobun/view/window-fullscreen.ts +10 -3
- package/src/shares/portable-layout.ts +99 -2
- package/src/sources/provider-router/index.ts +9 -3
- package/src/sources/provider-router/sources.ts +26 -1
- package/src/sync/core-contributors.ts +18 -4
- package/src/time-series/price-units.ts +11 -0
- package/src/time-series/resolve.ts +12 -0
- package/src/types/config.ts +17 -1
- package/src/types/plugin.ts +6 -0
- package/src/ui/host.tsx +2 -0
- package/src/utils/currency-names.ts +20 -0
- package/src/utils/currency-pair.ts +6 -0
- package/src/utils/exchange-rate-snapshot.ts +20 -2
- package/src/utils/fx-market-hours.ts +43 -0
|
@@ -120,9 +120,14 @@ function repeatsHeldSavedCopy(current: QueryEntry<Quote>, incoming: Quote): bool
|
|
|
120
120
|
return !!held && savedCopyAt(held) != null && savedCopyAt(incoming) == null && !(incoming.lastUpdated > held.lastUpdated);
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
/**
|
|
124
|
-
|
|
125
|
-
|
|
123
|
+
/**
|
|
124
|
+
* Fresh data, or a failure too recent to ask about again unless forced. A
|
|
125
|
+
* failure from before `failuresBefore` (the moment the data service answered
|
|
126
|
+
* again after an outage) does not count: the outage, not the symbol, failed it.
|
|
127
|
+
*/
|
|
128
|
+
function canReuseSnapshotEntry(entry: QueryEntry<TickerFinancials>, failuresBefore = 0): boolean {
|
|
129
|
+
return hasFreshEntryData(entry, SNAPSHOT_CACHE_TTL_MS)
|
|
130
|
+
|| hasRecentFailedAttempt(entry, SNAPSHOT_FAILURE_RETRY_MS, Date.now(), failuresBefore);
|
|
126
131
|
}
|
|
127
132
|
|
|
128
133
|
function storeFinancialsFailure(
|
|
@@ -141,7 +146,12 @@ function storeFinancialsFailure(
|
|
|
141
146
|
type CoordinatorSingleFlight = <T>(key: string, task: () => Promise<T>) => Promise<T>;
|
|
142
147
|
type CoordinatorLoadOptions = { forceRefresh?: boolean };
|
|
143
148
|
|
|
144
|
-
interface
|
|
149
|
+
interface SnapshotLoadPolicy {
|
|
150
|
+
/** Failures that finished before this moment no longer hold an unforced load back (`canReuseSnapshotEntry`). */
|
|
151
|
+
failuresBefore?: number;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
interface LoadFinancialsSnapshotEntryOptions extends SnapshotLoadPolicy {
|
|
145
155
|
dataProvider: DataProvider;
|
|
146
156
|
instrument: InstrumentRef;
|
|
147
157
|
options?: CoordinatorLoadOptions;
|
|
@@ -155,10 +165,11 @@ export async function loadFinancialsSnapshotEntry({
|
|
|
155
165
|
options = {},
|
|
156
166
|
runSingleFlight,
|
|
157
167
|
stores,
|
|
168
|
+
failuresBefore,
|
|
158
169
|
}: LoadFinancialsSnapshotEntryOptions): Promise<QueryEntry<TickerFinancials>> {
|
|
159
170
|
const key = buildSnapshotKey(instrument);
|
|
160
171
|
const current = stores.snapshotStore.get(key);
|
|
161
|
-
if (!options.forceRefresh && canReuseSnapshotEntry(current)) {
|
|
172
|
+
if (!options.forceRefresh && canReuseSnapshotEntry(current, failuresBefore)) {
|
|
162
173
|
return current;
|
|
163
174
|
}
|
|
164
175
|
const flightKey = options.forceRefresh ? `${key}|refresh` : key;
|
|
@@ -192,7 +203,7 @@ export async function loadFinancialsSnapshotEntry({
|
|
|
192
203
|
});
|
|
193
204
|
}
|
|
194
205
|
|
|
195
|
-
interface LoadFinancialsSnapshotBatchOptions {
|
|
206
|
+
interface LoadFinancialsSnapshotBatchOptions extends SnapshotLoadPolicy {
|
|
196
207
|
dataProvider: DataProvider;
|
|
197
208
|
instruments: InstrumentRef[];
|
|
198
209
|
options?: CoordinatorLoadOptions;
|
|
@@ -206,6 +217,7 @@ export async function loadFinancialsSnapshotBatch({
|
|
|
206
217
|
options = {},
|
|
207
218
|
runSingleFlight,
|
|
208
219
|
stores,
|
|
220
|
+
failuresBefore,
|
|
209
221
|
}: LoadFinancialsSnapshotBatchOptions): Promise<QueryEntry<TickerFinancials>[]> {
|
|
210
222
|
const uniqueInstruments = [...new Map(instruments.map((instrument) => [buildSnapshotKey(instrument), instrument] as const)).values()];
|
|
211
223
|
const results = new Map<string, QueryEntry<TickerFinancials>>();
|
|
@@ -214,7 +226,7 @@ export async function loadFinancialsSnapshotBatch({
|
|
|
214
226
|
for (const instrument of uniqueInstruments) {
|
|
215
227
|
const key = buildSnapshotKey(instrument);
|
|
216
228
|
const current = stores.snapshotStore.get(key);
|
|
217
|
-
if (!options.forceRefresh && canReuseSnapshotEntry(current)) {
|
|
229
|
+
if (!options.forceRefresh && canReuseSnapshotEntry(current, failuresBefore)) {
|
|
218
230
|
results.set(key, current);
|
|
219
231
|
} else {
|
|
220
232
|
misses.push(instrument);
|
|
@@ -253,6 +265,7 @@ export async function loadFinancialsSnapshotBatch({
|
|
|
253
265
|
options,
|
|
254
266
|
runSingleFlight,
|
|
255
267
|
stores,
|
|
268
|
+
failuresBefore,
|
|
256
269
|
}));
|
|
257
270
|
}));
|
|
258
271
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { logFailure } from "../../utils/log-failure";
|
|
2
|
+
import { createConcurrencyLimiter } from "../../utils/concurrency";
|
|
2
3
|
import type { CachedAssetArgs, CachedAssetMethod, CachedAssetValue, DataProvider, SecFilingDocument, SecFilingItem } from "../../types/data-provider";
|
|
3
4
|
import type { CorporateActionsData, OptionsChain, PricePoint, Quote, TickerFinancials } from "../../types/financials";
|
|
4
5
|
import { fetchHistoryResult, type HistoryResultRequest } from "../../sources/history-result";
|
|
@@ -55,6 +56,7 @@ import {
|
|
|
55
56
|
classifyError,
|
|
56
57
|
createAttempt,
|
|
57
58
|
errorEntry,
|
|
59
|
+
hasFailedLoad,
|
|
58
60
|
hasFreshEntryData,
|
|
59
61
|
hasFreshReadyEntry,
|
|
60
62
|
readyChartEntry,
|
|
@@ -112,6 +114,33 @@ const STREAM_QUOTE_BASELINE_LIMIT = 256;
|
|
|
112
114
|
* cap if this ceiling turns out to be too generous for it.
|
|
113
115
|
*/
|
|
114
116
|
const RETAINED_ENTRIES_PER_STORE = 64;
|
|
117
|
+
/**
|
|
118
|
+
* Past this many remembered reloads, those for keys no pane watches are
|
|
119
|
+
* dropped. A session browses hundreds of symbols; only what is on screen is
|
|
120
|
+
* asked again after an outage.
|
|
121
|
+
*/
|
|
122
|
+
const REMEMBERED_RELOADS_PRUNE_AT = 512;
|
|
123
|
+
const outageReloadFailed = logFailure("market-data.coordinator.index", "Loading again after an outage failed");
|
|
124
|
+
/**
|
|
125
|
+
* The least time between two sweeps of what an outage failed
|
|
126
|
+
* (`reloadAfterOutage`): a link that keeps dropping and coming back is asked
|
|
127
|
+
* again once in this window, at its end, not at every flip.
|
|
128
|
+
*/
|
|
129
|
+
const OUTAGE_RELOAD_MIN_INTERVAL_MS = 10_000;
|
|
130
|
+
/**
|
|
131
|
+
* How many loads a sweep after an outage runs at once, beside the one batch
|
|
132
|
+
* for quotes and the one for snapshots: a layout of charts and tables must
|
|
133
|
+
* not send its whole backlog in the same instant.
|
|
134
|
+
*/
|
|
135
|
+
const OUTAGE_RELOAD_CONCURRENCY = 4;
|
|
136
|
+
|
|
137
|
+
/** How a key a load wrote is asked again after an outage (`reloadAfterOutage`). */
|
|
138
|
+
interface RememberedReload {
|
|
139
|
+
entry: () => QueryEntry<unknown>;
|
|
140
|
+
reload: () => Promise<unknown>;
|
|
141
|
+
/** A quote or snapshot, asked again with the others of its kind in one batch request. */
|
|
142
|
+
batch?: { kind: "quote" | "snapshot"; instrument: InstrumentRef };
|
|
143
|
+
}
|
|
115
144
|
|
|
116
145
|
// A store hands out a fresh idle entry for every key it has never seen, so
|
|
117
146
|
// two idle reads of the same key must count as the same entry.
|
|
@@ -133,6 +162,30 @@ export class MarketDataCoordinator {
|
|
|
133
162
|
private destroyed = false;
|
|
134
163
|
private readonly cachedQueries = new Map<string, { query: CachedQueryHandle<unknown>; dispose: () => void }>();
|
|
135
164
|
private readonly streamQuoteBaselines = new Map<string, { baseline: TickerFinancials | null; readAt: number }>();
|
|
165
|
+
/**
|
|
166
|
+
* How to ask again for each key a load wrote, so what an outage failed is
|
|
167
|
+
* asked again for the panes still showing it once the data service answers
|
|
168
|
+
* (`reloadAfterOutage`).
|
|
169
|
+
*/
|
|
170
|
+
private readonly reloads = new Map<string, RememberedReload>();
|
|
171
|
+
private reloadsPruneAt = REMEMBERED_RELOADS_PRUNE_AT;
|
|
172
|
+
/** When the last sweep after an outage ran, and the one waiting out OUTAGE_RELOAD_MIN_INTERVAL_MS. */
|
|
173
|
+
private lastOutageSweepAt = Number.NEGATIVE_INFINITY;
|
|
174
|
+
private outageSweepTimer: ReturnType<typeof setTimeout> | null = null;
|
|
175
|
+
/** Loads in flight at a sweep that then failed, asked again together. */
|
|
176
|
+
private outageRetries: RememberedReload[] = [];
|
|
177
|
+
private outageRetryTimer: ReturnType<typeof setTimeout> | null = null;
|
|
178
|
+
private readonly outageReloadGate = createConcurrencyLimiter(OUTAGE_RELOAD_CONCURRENCY);
|
|
179
|
+
/** When the data service last answered again after an outage: a failure before it no longer holds a load back. */
|
|
180
|
+
private failuresBefore = 0;
|
|
181
|
+
/**
|
|
182
|
+
* Since when the quote stream has been down, while it is down
|
|
183
|
+
* (`setQuoteStreamDown`): a streamed quote nothing refreshed since reads as
|
|
184
|
+
* stale. Null while the stream runs.
|
|
185
|
+
*/
|
|
186
|
+
private quoteStreamDownSince: number | null = null;
|
|
187
|
+
/** Quote entries as read while the stream is down, so each keeps one identity for its readers. */
|
|
188
|
+
private interruptedQuoteEntries = new WeakMap<QueryEntry<Quote>, QueryEntry<Quote>>();
|
|
136
189
|
|
|
137
190
|
private readonly retained: QueryStoreRetention = {
|
|
138
191
|
maxRetainedEntries: RETAINED_ENTRIES_PER_STORE,
|
|
@@ -232,7 +285,39 @@ export class MarketDataCoordinator {
|
|
|
232
285
|
}
|
|
233
286
|
|
|
234
287
|
getQuoteEntry(instrument: InstrumentRef): QueryEntry<Quote> {
|
|
235
|
-
|
|
288
|
+
const key = buildQuoteKey(instrument);
|
|
289
|
+
const entry = this.quoteStore.get(key);
|
|
290
|
+
if (!this.isInterruptedQuote(key, entry, [entry])) return entry;
|
|
291
|
+
let interrupted = this.interruptedQuoteEntries.get(entry);
|
|
292
|
+
if (!interrupted) {
|
|
293
|
+
const quote = resolveEntryData(entry)!;
|
|
294
|
+
const stale = { ...quote, stale: true as const };
|
|
295
|
+
interrupted = { ...entry, data: stale, lastGoodData: entry.lastGoodData === quote ? stale : entry.lastGoodData };
|
|
296
|
+
this.interruptedQuoteEntries.set(entry, interrupted);
|
|
297
|
+
}
|
|
298
|
+
return interrupted;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* The quote stream went down at `since`, or runs again (null). While it is
|
|
303
|
+
* down, a quote a pane streams that nothing refreshed since reads as stale,
|
|
304
|
+
* so a price that stopped moving says so instead of passing for live. The
|
|
305
|
+
* held quote itself is kept: the next tick, or a refresh, replaces it.
|
|
306
|
+
*/
|
|
307
|
+
setQuoteStreamDown(since: number | null): void {
|
|
308
|
+
if (this.destroyed || this.quoteStreamDownSince === since) return;
|
|
309
|
+
this.quoteStreamDownSince = since;
|
|
310
|
+
this.interruptedQuoteEntries = new WeakMap();
|
|
311
|
+
for (const key of this.quoteSubscriptionManager.streamingKeys()) this.events.bump(key);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** A streamed quote shown from entries none of which was written since the stream went down. */
|
|
315
|
+
private isInterruptedQuote(key: string, quoteEntry: QueryEntry<Quote>, entries: ReadonlyArray<QueryEntry<unknown>>): boolean {
|
|
316
|
+
const since = this.quoteStreamDownSince;
|
|
317
|
+
if (since == null) return false;
|
|
318
|
+
const quote = resolveEntryData(quoteEntry);
|
|
319
|
+
return !!quote && quote.stale !== true && this.quoteSubscriptionManager.isStreaming(key)
|
|
320
|
+
&& entries.every((entry) => (entry.fetchedAt ?? 0) <= since);
|
|
236
321
|
}
|
|
237
322
|
|
|
238
323
|
getSnapshotEntry(instrument: InstrumentRef): QueryEntry<TickerFinancials> {
|
|
@@ -277,25 +362,34 @@ export class MarketDataCoordinator {
|
|
|
277
362
|
snapshotEntry: QueryEntry<TickerFinancials>;
|
|
278
363
|
quoteEntry: QueryEntry<Quote>;
|
|
279
364
|
chartEntry: QueryEntry<PricePoint[]>;
|
|
365
|
+
streamDownSince: number | null;
|
|
280
366
|
financials: TickerFinancials | null;
|
|
281
367
|
}>();
|
|
282
368
|
|
|
283
369
|
getTickerFinancialsSync(instrument: InstrumentRef): TickerFinancials | null {
|
|
284
370
|
const key = buildSnapshotKey(instrument);
|
|
371
|
+
const quoteKey = buildQuoteKey(instrument);
|
|
285
372
|
const snapshotEntry = this.getSnapshotEntry(instrument);
|
|
286
|
-
|
|
373
|
+
// The quote as stored: it is resolved against the snapshot's first, and marked stale after.
|
|
374
|
+
const quoteEntry = this.quoteStore.get(quoteKey);
|
|
287
375
|
const chartEntry = this.getChartEntry(createBaselineChartRequest(instrument));
|
|
376
|
+
const streamDownSince = this.quoteStreamDownSince;
|
|
288
377
|
const cached = this.financialsSnapshotCache.get(key);
|
|
289
378
|
if (
|
|
290
379
|
cached
|
|
291
380
|
&& sameQueryEntry(cached.snapshotEntry, snapshotEntry)
|
|
292
381
|
&& sameQueryEntry(cached.quoteEntry, quoteEntry)
|
|
293
382
|
&& sameQueryEntry(cached.chartEntry, chartEntry)
|
|
383
|
+
&& cached.streamDownSince === streamDownSince
|
|
294
384
|
) {
|
|
295
385
|
return cached.financials;
|
|
296
386
|
}
|
|
297
|
-
|
|
298
|
-
|
|
387
|
+
let financials = buildTickerFinancialsSnapshot(snapshotEntry, quoteEntry, chartEntry);
|
|
388
|
+
// Marked after the quote is resolved: a stale streamed quote must not hand the price back to an older snapshot's.
|
|
389
|
+
if (financials?.quote && financials.quote.stale !== true && this.isInterruptedQuote(quoteKey, quoteEntry, [quoteEntry, snapshotEntry])) {
|
|
390
|
+
financials = { ...financials, quote: { ...financials.quote, stale: true } };
|
|
391
|
+
}
|
|
392
|
+
this.financialsSnapshotCache.set(key, { snapshotEntry, quoteEntry, chartEntry, streamDownSince, financials });
|
|
299
393
|
return financials;
|
|
300
394
|
}
|
|
301
395
|
|
|
@@ -359,6 +453,102 @@ export class MarketDataCoordinator {
|
|
|
359
453
|
}
|
|
360
454
|
}
|
|
361
455
|
|
|
456
|
+
/** Remembers how to ask again for `key` (`reloadAfterOutage`). */
|
|
457
|
+
private rememberReload<T>(key: string, store: QueryStore<T>, reload: () => Promise<unknown>, batch?: RememberedReload["batch"]): void {
|
|
458
|
+
this.reloads.set(key, { entry: () => store.get(key), reload, batch });
|
|
459
|
+
if (this.reloads.size <= this.reloadsPruneAt) return;
|
|
460
|
+
for (const remembered of this.reloads.keys()) {
|
|
461
|
+
if (!this.events.hasKeyListeners(remembered)) this.reloads.delete(remembered);
|
|
462
|
+
}
|
|
463
|
+
this.reloadsPruneAt = Math.max(REMEMBERED_RELOADS_PRUNE_AT, this.reloads.size * 2);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* The data service answers again after an outage. A failure from before now
|
|
468
|
+
* no longer holds a load back, and what a pane still shows that failed is
|
|
469
|
+
* asked again (`sweepAfterOutage`), at most once per
|
|
470
|
+
* OUTAGE_RELOAD_MIN_INTERVAL_MS: a recovery inside that window is swept at
|
|
471
|
+
* its end.
|
|
472
|
+
*/
|
|
473
|
+
reloadAfterOutage(): void {
|
|
474
|
+
if (this.destroyed) return;
|
|
475
|
+
this.failuresBefore = Date.now();
|
|
476
|
+
if (this.outageSweepTimer) return;
|
|
477
|
+
const waitMs = this.lastOutageSweepAt + OUTAGE_RELOAD_MIN_INTERVAL_MS - Date.now();
|
|
478
|
+
if (waitMs <= 0) {
|
|
479
|
+
this.sweepAfterOutage();
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
const timer = setTimeout(() => {
|
|
483
|
+
this.outageSweepTimer = null;
|
|
484
|
+
this.sweepAfterOutage();
|
|
485
|
+
}, waitMs);
|
|
486
|
+
(timer as { unref?: () => void }).unref?.();
|
|
487
|
+
this.outageSweepTimer = timer;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Asks again for what a pane still shows that failed, and for what waits on
|
|
492
|
+
* a request sent into the outage, should that request fail. Keys no pane
|
|
493
|
+
* watches are left until something asks.
|
|
494
|
+
*/
|
|
495
|
+
private sweepAfterOutage(): void {
|
|
496
|
+
if (this.destroyed) return;
|
|
497
|
+
this.lastOutageSweepAt = Date.now();
|
|
498
|
+
const failed: RememberedReload[] = [];
|
|
499
|
+
for (const [key, remembered] of [...this.reloads]) {
|
|
500
|
+
if (!this.events.hasKeyListeners(key)) {
|
|
501
|
+
this.reloads.delete(key);
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const current = remembered.entry();
|
|
505
|
+
if (current.phase === "loading" || current.phase === "refreshing") {
|
|
506
|
+
// Joins the request in flight; a failure it ends in was the outage's.
|
|
507
|
+
void remembered.reload().then(() => {
|
|
508
|
+
if (hasFailedLoad(remembered.entry())) this.retryAfterOutage(remembered);
|
|
509
|
+
}).catch(outageReloadFailed);
|
|
510
|
+
} else if (hasFailedLoad(current)) {
|
|
511
|
+
failed.push(remembered);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
void this.reloadTogether(failed);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** A load in flight at a sweep failed: asked again with the others that fail with it (one deadline, one dropped connection). */
|
|
518
|
+
private retryAfterOutage(remembered: RememberedReload): void {
|
|
519
|
+
if (this.destroyed) return;
|
|
520
|
+
this.outageRetries.push(remembered);
|
|
521
|
+
if (this.outageRetryTimer) return;
|
|
522
|
+
this.outageRetryTimer = setTimeout(() => {
|
|
523
|
+
this.outageRetryTimer = null;
|
|
524
|
+
const retries = this.outageRetries;
|
|
525
|
+
this.outageRetries = [];
|
|
526
|
+
void this.reloadTogether(retries);
|
|
527
|
+
}, 0);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Asks again for keys an outage failed: the quotes in one batch request,
|
|
532
|
+
* the snapshots in another, and the rest OUTAGE_RELOAD_CONCURRENCY at a
|
|
533
|
+
* time, rather than one request per symbol all at once.
|
|
534
|
+
*/
|
|
535
|
+
private async reloadTogether(remembered: readonly RememberedReload[]): Promise<void> {
|
|
536
|
+
const quotes: InstrumentRef[] = [];
|
|
537
|
+
const snapshots: InstrumentRef[] = [];
|
|
538
|
+
const rest: Array<() => Promise<unknown>> = [];
|
|
539
|
+
for (const { batch, reload } of remembered) {
|
|
540
|
+
if (batch?.kind === "quote") quotes.push(batch.instrument);
|
|
541
|
+
else if (batch?.kind === "snapshot") snapshots.push(batch.instrument);
|
|
542
|
+
else rest.push(reload);
|
|
543
|
+
}
|
|
544
|
+
const runs: Array<() => Promise<unknown>> = [...rest];
|
|
545
|
+
if (quotes.length > 0) runs.unshift(() => this.loadQuotesBatch(quotes));
|
|
546
|
+
if (snapshots.length > 0) runs.unshift(() => this.loadSnapshotsBatch(snapshots));
|
|
547
|
+
await Promise.all(runs.map((run) => this.outageReloadGate(async () => {
|
|
548
|
+
if (!this.destroyed) await run();
|
|
549
|
+
}).catch(outageReloadFailed)));
|
|
550
|
+
}
|
|
551
|
+
|
|
362
552
|
private runSingleFlight<T>(key: string, task: () => Promise<T>): Promise<T> {
|
|
363
553
|
const existing = this.inFlight.get(key);
|
|
364
554
|
if (existing) {
|
|
@@ -375,12 +565,14 @@ export class MarketDataCoordinator {
|
|
|
375
565
|
instrument: InstrumentRef,
|
|
376
566
|
options: { forceRefresh?: boolean } = {},
|
|
377
567
|
): Promise<QueryEntry<TickerFinancials>> {
|
|
568
|
+
this.rememberReload(buildSnapshotKey(instrument), this.snapshotStore, () => this.loadSnapshot(instrument), { kind: "snapshot", instrument });
|
|
378
569
|
return loadFinancialsSnapshotEntry({
|
|
379
570
|
dataProvider: this.dataProvider,
|
|
380
571
|
instrument,
|
|
381
572
|
options,
|
|
382
573
|
runSingleFlight: (key, task) => this.runSingleFlight(key, task),
|
|
383
574
|
stores: this.financialCacheStores,
|
|
575
|
+
failuresBefore: this.failuresBefore,
|
|
384
576
|
});
|
|
385
577
|
}
|
|
386
578
|
|
|
@@ -388,12 +580,16 @@ export class MarketDataCoordinator {
|
|
|
388
580
|
instruments: InstrumentRef[],
|
|
389
581
|
options: { forceRefresh?: boolean } = {},
|
|
390
582
|
): Promise<QueryEntry<TickerFinancials>[]> {
|
|
583
|
+
for (const instrument of instruments) {
|
|
584
|
+
this.rememberReload(buildSnapshotKey(instrument), this.snapshotStore, () => this.loadSnapshot(instrument), { kind: "snapshot", instrument });
|
|
585
|
+
}
|
|
391
586
|
return loadFinancialsSnapshotBatch({
|
|
392
587
|
dataProvider: this.dataProvider,
|
|
393
588
|
instruments,
|
|
394
589
|
options,
|
|
395
590
|
runSingleFlight: (key, task) => this.runSingleFlight(key, task),
|
|
396
591
|
stores: this.financialCacheStores,
|
|
592
|
+
failuresBefore: this.failuresBefore,
|
|
397
593
|
});
|
|
398
594
|
}
|
|
399
595
|
|
|
@@ -401,6 +597,7 @@ export class MarketDataCoordinator {
|
|
|
401
597
|
instrument: InstrumentRef,
|
|
402
598
|
options: { forceRefresh?: boolean } = {},
|
|
403
599
|
): Promise<QueryEntry<Quote>> {
|
|
600
|
+
this.rememberReload(buildQuoteKey(instrument), this.quoteStore, () => this.loadQuote(instrument), { kind: "quote", instrument });
|
|
404
601
|
return loadQuoteEntry({
|
|
405
602
|
dataProvider: this.dataProvider,
|
|
406
603
|
instrument,
|
|
@@ -415,6 +612,9 @@ export class MarketDataCoordinator {
|
|
|
415
612
|
instruments: InstrumentRef[],
|
|
416
613
|
options: { forceRefresh?: boolean } = {},
|
|
417
614
|
): Promise<QueryEntry<Quote>[]> {
|
|
615
|
+
for (const instrument of instruments) {
|
|
616
|
+
this.rememberReload(buildQuoteKey(instrument), this.quoteStore, () => this.loadQuote(instrument), { kind: "quote", instrument });
|
|
617
|
+
}
|
|
418
618
|
return loadQuoteBatchEntries({
|
|
419
619
|
dataProvider: this.dataProvider,
|
|
420
620
|
instruments,
|
|
@@ -431,6 +631,7 @@ export class MarketDataCoordinator {
|
|
|
431
631
|
): Promise<QueryEntry<PricePoint[]>> {
|
|
432
632
|
const key = buildChartKey(request);
|
|
433
633
|
this.chartRequests.set(key, request);
|
|
634
|
+
this.rememberReload(key, this.chartStore, () => this.loadChart(request));
|
|
434
635
|
const current = this.chartStore.get(key);
|
|
435
636
|
const currentData = normalizeFreshChartData(resolveEntryData(current), request, current.history, current.fetchedAt);
|
|
436
637
|
if (!options.forceRefresh && currentData.length > 0 && hasFreshEntryData(current, CHART_CACHE_TTL_MS)) {
|
|
@@ -491,6 +692,7 @@ export class MarketDataCoordinator {
|
|
|
491
692
|
options: { forceRefresh?: boolean; batch?: boolean } = {},
|
|
492
693
|
): Promise<QueryEntry<OptionsChain>> {
|
|
493
694
|
const key = buildOptionsKey(request);
|
|
695
|
+
this.rememberReload(key, this.optionsStore, () => this.loadOptions(request, { batch: options.batch }));
|
|
494
696
|
const loadingKey = options.forceRefresh ? `${key}|refresh` : key;
|
|
495
697
|
const existing = this.optionsLoads.get(loadingKey);
|
|
496
698
|
if (existing) return existing;
|
|
@@ -535,6 +737,7 @@ export class MarketDataCoordinator {
|
|
|
535
737
|
}
|
|
536
738
|
|
|
537
739
|
async loadSecFilings(request: SecFilingsRequest, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<SecFilingItem[]>> {
|
|
740
|
+
this.rememberReload(buildSecFilingsKey(request), this.secFilingsStore, () => this.loadSecFilings(request));
|
|
538
741
|
return this.loadCachedQuery("getSecFilings", [request.instrument.symbol, request.count ?? 50, request.instrument.exchange, toMarketDataContext(request.instrument)], buildSecFilingsKey(request), this.secFilingsStore, options.forceRefresh, (value) => value.length === 0) ?? loadSecFilingsEntry({
|
|
539
742
|
forceRefresh: options.forceRefresh,
|
|
540
743
|
dataProvider: this.dataProvider,
|
|
@@ -545,6 +748,7 @@ export class MarketDataCoordinator {
|
|
|
545
748
|
}
|
|
546
749
|
|
|
547
750
|
async loadSecFilingContent(filing: SecFilingItem, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<string | null>> {
|
|
751
|
+
this.rememberReload(buildSecContentKey(filing.accessionNumber), this.secContentStore, () => this.loadSecFilingContent(filing));
|
|
548
752
|
return this.loadCachedQuery("getSecFilingContent", [filing], buildSecContentKey(filing.accessionNumber), this.secContentStore, options.forceRefresh) ?? loadSecFilingContentEntry({
|
|
549
753
|
forceRefresh: options.forceRefresh,
|
|
550
754
|
dataProvider: this.dataProvider,
|
|
@@ -555,6 +759,7 @@ export class MarketDataCoordinator {
|
|
|
555
759
|
}
|
|
556
760
|
|
|
557
761
|
async loadSecFilingDocuments(filing: SecFilingItem, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<SecFilingDocument[]>> {
|
|
762
|
+
this.rememberReload(buildSecDocumentsKey(filing.accessionNumber), this.secDocumentsStore, () => this.loadSecFilingDocuments(filing));
|
|
558
763
|
return this.loadCachedQuery("getSecFilingDocuments", [filing], buildSecDocumentsKey(filing.accessionNumber), this.secDocumentsStore, options.forceRefresh, (value) => value.length === 0) ?? loadSecFilingDocumentsEntry({
|
|
559
764
|
forceRefresh: options.forceRefresh,
|
|
560
765
|
dataProvider: this.dataProvider,
|
|
@@ -565,6 +770,7 @@ export class MarketDataCoordinator {
|
|
|
565
770
|
}
|
|
566
771
|
|
|
567
772
|
async loadArticleSummary(url: string): Promise<QueryEntry<string | null>> {
|
|
773
|
+
this.rememberReload(buildArticleSummaryKey(url), this.articleSummaryStore, () => this.loadArticleSummary(url));
|
|
568
774
|
return this.loadCachedQuery("getArticleSummary", [url], buildArticleSummaryKey(url), this.articleSummaryStore) ?? loadArticleSummaryEntry({
|
|
569
775
|
dataProvider: this.dataProvider,
|
|
570
776
|
url,
|
|
@@ -574,6 +780,7 @@ export class MarketDataCoordinator {
|
|
|
574
780
|
}
|
|
575
781
|
|
|
576
782
|
async loadFxRate(currency: string, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<number>> {
|
|
783
|
+
this.rememberReload(buildFxKey(currency), this.fxStore, () => this.loadFxRate(currency));
|
|
577
784
|
return this.loadCachedQuery("getExchangeRate", [currency], buildFxKey(currency), this.fxStore, options.forceRefresh) ?? loadFxRateEntry({
|
|
578
785
|
dataProvider: this.dataProvider,
|
|
579
786
|
currency,
|
|
@@ -647,6 +854,12 @@ export class MarketDataCoordinator {
|
|
|
647
854
|
for (const { dispose } of this.cachedQueries.values()) dispose();
|
|
648
855
|
this.cachedQueries.clear();
|
|
649
856
|
this.streamQuoteBaselines.clear();
|
|
857
|
+
this.reloads.clear();
|
|
858
|
+
if (this.outageSweepTimer) clearTimeout(this.outageSweepTimer);
|
|
859
|
+
if (this.outageRetryTimer) clearTimeout(this.outageRetryTimer);
|
|
860
|
+
this.outageSweepTimer = null;
|
|
861
|
+
this.outageRetryTimer = null;
|
|
862
|
+
this.outageRetries = [];
|
|
650
863
|
for (const timer of this.fxLegTimers.values()) clearTimeout(timer);
|
|
651
864
|
this.fxLegTimers.clear();
|
|
652
865
|
}
|
|
@@ -247,6 +247,16 @@ export class QuoteSubscriptionManager {
|
|
|
247
247
|
return dispose;
|
|
248
248
|
}
|
|
249
249
|
|
|
250
|
+
/** Whether a pane streams this quote key now. */
|
|
251
|
+
isStreaming(key: string): boolean {
|
|
252
|
+
return (this.quoteSubscriptions.get(key)?.targets.size ?? 0) > 0;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** The quote keys panes stream now. */
|
|
256
|
+
streamingKeys(): string[] {
|
|
257
|
+
return [...this.quoteSubscriptions].filter(([, entry]) => entry.targets.size > 0).map(([key]) => key);
|
|
258
|
+
}
|
|
259
|
+
|
|
250
260
|
private createNoopSubscription(): QuoteSubscriptionHandle {
|
|
251
261
|
const dispose = (() => {}) as QuoteSubscriptionHandle;
|
|
252
262
|
dispose.update = () => {};
|
|
@@ -54,6 +54,27 @@ export interface DataFrameRequest {
|
|
|
54
54
|
phase?: DataFramePhase;
|
|
55
55
|
/** Driver time before which the task must not run; background keys use it to wait out their interval. */
|
|
56
56
|
notBefore?: number;
|
|
57
|
+
/**
|
|
58
|
+
* Lets the task wait to share a frame with other work: it runs in the first
|
|
59
|
+
* frame at or after `notBefore`, but only sets a frame off itself at this
|
|
60
|
+
* driver time. A frame that runs nothing else does not hold the next one
|
|
61
|
+
* back or count toward load pacing, so a quote arriving just after it is not
|
|
62
|
+
* kept waiting.
|
|
63
|
+
*/
|
|
64
|
+
rideUntil?: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface QueuedTask {
|
|
68
|
+
notBefore: number;
|
|
69
|
+
/** When the task sets a frame off by itself. */
|
|
70
|
+
wakeAt: number;
|
|
71
|
+
rides: boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** How many riding (rideUntil) and other tasks a frame ran. */
|
|
75
|
+
interface FrameTally {
|
|
76
|
+
riders: number;
|
|
77
|
+
others: number;
|
|
57
78
|
}
|
|
58
79
|
|
|
59
80
|
function monotonicNow(): number {
|
|
@@ -186,7 +207,7 @@ export function createManualFrameDriver(minIntervalMs: number): {
|
|
|
186
207
|
}
|
|
187
208
|
|
|
188
209
|
export class DataFrameScheduler {
|
|
189
|
-
private readonly queues: Record<DataFramePhase, Map<DataFrameTask,
|
|
210
|
+
private readonly queues: Record<DataFramePhase, Map<DataFrameTask, QueuedTask>> = {
|
|
190
211
|
apply: new Map(),
|
|
191
212
|
notify: new Map(),
|
|
192
213
|
};
|
|
@@ -230,10 +251,18 @@ export class DataFrameScheduler {
|
|
|
230
251
|
}
|
|
231
252
|
|
|
232
253
|
/** Queues a task for the next frame. A task queued twice runs once. */
|
|
233
|
-
request(task: DataFrameTask, { phase = "apply", notBefore = Number.NEGATIVE_INFINITY }: DataFrameRequest = {}): void {
|
|
254
|
+
request(task: DataFrameTask, { phase = "apply", notBefore = Number.NEGATIVE_INFINITY, rideUntil }: DataFrameRequest = {}): void {
|
|
234
255
|
const queue = this.queues[phase];
|
|
235
256
|
const existing = queue.get(task);
|
|
236
|
-
|
|
257
|
+
const rides = rideUntil !== undefined;
|
|
258
|
+
const wakeAt = rides ? Math.max(notBefore, rideUntil) : notBefore;
|
|
259
|
+
if (existing === undefined) {
|
|
260
|
+
queue.set(task, { notBefore, wakeAt, rides });
|
|
261
|
+
} else {
|
|
262
|
+
existing.notBefore = Math.min(existing.notBefore, notBefore);
|
|
263
|
+
existing.wakeAt = Math.min(existing.wakeAt, wakeAt);
|
|
264
|
+
existing.rides &&= rides;
|
|
265
|
+
}
|
|
237
266
|
if (!this.running) this.reschedule();
|
|
238
267
|
}
|
|
239
268
|
|
|
@@ -252,7 +281,7 @@ export class DataFrameScheduler {
|
|
|
252
281
|
private reschedule(): void {
|
|
253
282
|
let earliest = Number.POSITIVE_INFINITY;
|
|
254
283
|
for (const queue of Object.values(this.queues)) {
|
|
255
|
-
for (const
|
|
284
|
+
for (const queued of queue.values()) earliest = Math.min(earliest, queued.wakeAt);
|
|
256
285
|
}
|
|
257
286
|
if (earliest === Number.POSITIVE_INFINITY) {
|
|
258
287
|
this.cancel();
|
|
@@ -269,10 +298,14 @@ export class DataFrameScheduler {
|
|
|
269
298
|
}, at - this.driver.now());
|
|
270
299
|
}
|
|
271
300
|
|
|
272
|
-
|
|
301
|
+
/** The tasks due by `now`, counted into `frame` as riding (rideUntil) or not. */
|
|
302
|
+
private takeDue(phase: DataFramePhase, now: number, frame: FrameTally): DataFrameTask[] {
|
|
273
303
|
const due: DataFrameTask[] = [];
|
|
274
|
-
for (const [task,
|
|
275
|
-
if (notBefore
|
|
304
|
+
for (const [task, queued] of this.queues[phase]) {
|
|
305
|
+
if (queued.notBefore > now) continue;
|
|
306
|
+
due.push(task);
|
|
307
|
+
if (queued.rides) frame.riders += 1;
|
|
308
|
+
else frame.others += 1;
|
|
276
309
|
}
|
|
277
310
|
for (const task of due) this.queues[phase].delete(task);
|
|
278
311
|
return due;
|
|
@@ -283,21 +316,25 @@ export class DataFrameScheduler {
|
|
|
283
316
|
this.running = true;
|
|
284
317
|
const driver = this.driver;
|
|
285
318
|
const now = driver.now();
|
|
319
|
+
const previousFrameAt = this.lastFrameAt;
|
|
286
320
|
this.lastFrameAt = now;
|
|
321
|
+
const frame: FrameTally = { riders: 0, others: 0 };
|
|
287
322
|
let notified = false;
|
|
288
323
|
try {
|
|
289
324
|
// Applying a batch may queue another applier (a flush feeding a
|
|
290
325
|
// derived store); those still belong to this frame.
|
|
291
326
|
for (let pass = 0; pass < MAX_APPLY_PASSES; pass += 1) {
|
|
292
|
-
const due = this.takeDue("apply", now);
|
|
327
|
+
const due = this.takeDue("apply", now, frame);
|
|
293
328
|
if (due.length === 0) break;
|
|
294
329
|
runTasks(due);
|
|
295
330
|
}
|
|
296
331
|
// Listeners that write data while being notified are heard next frame.
|
|
297
|
-
const listeners = this.takeDue("notify", now);
|
|
298
|
-
notified = listeners.length > 0;
|
|
332
|
+
const listeners = this.takeDue("notify", now, frame);
|
|
333
|
+
notified = listeners.length > 0 && frame.others > 0;
|
|
299
334
|
runTasks(listeners);
|
|
300
335
|
} finally {
|
|
336
|
+
// Nothing but riders ran: the next frame is spaced from the last one that carried data.
|
|
337
|
+
if (frame.riders > 0 && frame.others === 0) this.lastFrameAt = previousFrameAt;
|
|
301
338
|
this.running = false;
|
|
302
339
|
// Only a frame that told readers something sets off renders worth timing.
|
|
303
340
|
if (notified && driver.afterFrame) {
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { useRef, useSyncExternalStore } from "react";
|
|
2
|
+
import { marketDataFrames, type DataFrameScheduler, type DataFrameTask } from "./frame-scheduler";
|
|
3
|
+
|
|
4
|
+
export interface DataFrameWake {
|
|
5
|
+
/** The market data clock (monotonic, in ms). */
|
|
6
|
+
now(): number;
|
|
7
|
+
/**
|
|
8
|
+
* Renders the component again in the first market data frame at or after
|
|
9
|
+
* `time` on that clock, waiting up to one frame interval longer for a frame
|
|
10
|
+
* that brings quotes. Booked twice, the earlier time wins; a component that
|
|
11
|
+
* still needs one after it renders books again.
|
|
12
|
+
*/
|
|
13
|
+
wakeAt(time: number): void;
|
|
14
|
+
/** Drops a booked render that is no longer needed. */
|
|
15
|
+
cancel(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface WakeStore extends DataFrameWake {
|
|
19
|
+
version: number;
|
|
20
|
+
booked: boolean;
|
|
21
|
+
listener: (() => void) | null;
|
|
22
|
+
task: DataFrameTask;
|
|
23
|
+
subscribe(listener: () => void): () => void;
|
|
24
|
+
getVersion(): number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function createWakeStore(frames: DataFrameScheduler): WakeStore {
|
|
28
|
+
const store: WakeStore = {
|
|
29
|
+
version: 0,
|
|
30
|
+
booked: false,
|
|
31
|
+
listener: null,
|
|
32
|
+
task: () => {
|
|
33
|
+
store.booked = false;
|
|
34
|
+
store.version += 1;
|
|
35
|
+
store.listener?.();
|
|
36
|
+
},
|
|
37
|
+
subscribe(listener) {
|
|
38
|
+
store.listener = listener;
|
|
39
|
+
return () => {
|
|
40
|
+
store.listener = null;
|
|
41
|
+
store.cancel();
|
|
42
|
+
};
|
|
43
|
+
},
|
|
44
|
+
getVersion: () => store.version,
|
|
45
|
+
now: () => frames.now(),
|
|
46
|
+
wakeAt(time) {
|
|
47
|
+
store.booked = true;
|
|
48
|
+
// Due at `time`, it waits up to a frame for one that carries quotes.
|
|
49
|
+
frames.request(store.task, { phase: "notify", notBefore: time, rideUntil: time + frames.frameIntervalMs() });
|
|
50
|
+
},
|
|
51
|
+
cancel() {
|
|
52
|
+
if (!store.booked) return;
|
|
53
|
+
store.booked = false;
|
|
54
|
+
frames.remove(store.task);
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
return store;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A re-render booked on the market data clock, in the same React pass as the
|
|
62
|
+
* store updates that frame delivers. A flash ending or a throttled total
|
|
63
|
+
* catching up then rides along with the next quotes instead of costing a
|
|
64
|
+
* commit, and in the terminal a full redraw, of its own.
|
|
65
|
+
*/
|
|
66
|
+
export function useDataFrameWake(frames: DataFrameScheduler = marketDataFrames): DataFrameWake {
|
|
67
|
+
const storeRef = useRef<{ frames: DataFrameScheduler; store: WakeStore } | null>(null);
|
|
68
|
+
if (storeRef.current?.frames !== frames) storeRef.current = { frames, store: createWakeStore(frames) };
|
|
69
|
+
const { store } = storeRef.current;
|
|
70
|
+
// A store notification is a sync-lane update, as every market data hook's is,
|
|
71
|
+
// so React folds it into the same render as the frame's other updates.
|
|
72
|
+
useSyncExternalStore(store.subscribe, store.getVersion, store.getVersion);
|
|
73
|
+
return store;
|
|
74
|
+
}
|