Skip to content

Commit de8d549

Browse files
fix(console, app-shell): discovery starts with the session check; Setup's open reads no whole object registry (#35304)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg48yiCyRmnqoUoHcQ9VbBp6)_ Part of #34211 — this lands asks (1) and (2). The card stays open for its two acceptance numbers, which this PR does not reach (see Acceptance notes): the list page is not at 5 serial layers, and Setup still sends two small object reads (both answer empty), not one. Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:控制台冷加载时,`discovery` 请求现在在 HTML 解析阶段就和 `get-session` 一起发出,不再等主包下载完再单独排一层;打开 Setup 不再读取整份对象注册表(showcase 上约 860 KB),改成只读它导航项需要的对象,已在应用包(bundle)里的对象直接从包里回答。 - 为什么改:卡片实测控制台首屏 7 层串行请求,其中 discovery 独占一层;Setup 先读空的包对象列表,再读整份注册表(服务端最重的一次元数据计算)。 - 风险与回滚:只动控制台启动(`index.html`、`main.tsx`、新的 `lib/early-discovery.ts`)和 app-shell 两处(Setup 根路由的对象范围、存在性读取走 bundle);回滚即 revert 本 PR。`index.html` 不在认领列出的路径里,见 Acceptance notes。 - 先看:`ui/packages/app-shell/src/providers/MetadataProvider.tsx`(存在性读取由 bundle 回答的分支)、`ui/packages/app-shell/src/console/appObjectScope.ts`(删掉根路由读整份注册表的例外)、`ui/apps/console/index.html`(`startEarlyDiscovery`)。 - 两分钟验证:`pnpm --dir ui exec vitest run apps/console/src/__tests__/sessionCheckBootDedup.test.tsx packages/app-shell/src/providers/__tests__/MetadataProvider.bundleFirstReads-28645.test.tsx packages/app-shell/src/console/__tests__/AppContent.emptyPackageScope-13046.test.tsx`,预期 3 个文件全绿。 - 需要你做的:决定卡片剩下的两个验收数字(列表页 5 层以内、Setup 恰好一次 `meta/object`)是否另开后续,或按本 PR 的读数调整验收。 ## What changes Measured first (A1) on a production console build (`pnpm console:build`, served by `objectstack dev --ui --seed-admin` from `examples/app-showcase` on a private port), signed in through the login page (so the Bearer token and the early session check are in play), headless Chromium 1440x900, one warm-up load, then a fresh page per load; every `/api/` resource entry from navigation to network idle plus 3 s, start and end times from the Resource Timing API. A request's layer is 1 + the deepest layer of any request that ENDED before it STARTED, so the page's count is the longest chain of strictly sequential requests. On a fast local server this counts the client's own render and chunk gaps as layers too, so it reads higher than the card's grouping; both readings are below. 1. **Discovery starts with get-session (ask 1, reproduced).** On `origin/main` `d6d96450` discovery left at 581–613 ms, after the main bundle evaluated, while `get-session` left at 19–23 ms. `index.html` now sends `GET /api/v1/discovery` during parse in a third inline script, `startEarlyDiscovery`, beside `runtime/config` and `get-session`, and leaves the pending answer under `Symbol.for('objectui.earlyDiscovery')`. The console's discovery reader moves out of `languageSeed.ts` into `src/lib/early-discovery.ts` as `readConsoleDiscovery()`: it takes that request once (same URL) as the request behind `getSharedDiscovery`, and `main.tsx` starts it on every boot. Before, a device with a stored language skipped it, so discovery waited for the data adapter's `connect()`, after the session. The adapter's `connect()` asks the same per-origin cache, so it joins the answer. It is one request either way, and its spelling (`credentials: 'include'`, `Accept: application/json`, no Bearer) is the one `languageSeed` already sent. A failed or non-OK early request is not reused. 2. **Setup's open reads no whole object registry (ask 2, reproduced).** On `origin/main`, Setup sent `meta/object?package=com.objectstack.setup` (49 B, empty) and then `meta/object` (862,486 B, the whole registry). The root of an app whose package holds no objects of its own was the one app route that fell back to the registry. It now reads the way that app's object routes do: the package list, then the objects its entries require (`requiresObject`) in the one presence read. The presence read (the batched names scope, `views: false`) now answers a name the entered app's bundle holds from the bundle, as a by-name read of it is answered, so Setup's 14 required objects cost no request. What remains on Setup is the package list and, after the landing redirects to `dashboard/system_overview`, that dashboard's widget gate asking for `sys_package_installation` (49 B, empty: an object this runtime does not register; the registry used to answer it). 3. **The bundle starts with `meta/app`'s answer already (ask 3, premise does not reproduce).** `meta/app/APP/bundle` leaves 35–50 ms after `meta/app` answers, in the same render as `meta/object?package=` and `me/apps`, and on several loads before `meta/object?package=` has answered (list run 1: package read 731→758, bundle from 741). The console root has entered the bundle as soon as the app list names the app (`useAppObjectScopePrefetch`, since objectstack#28645). It cannot start earlier without the app's name, which only `meta/app` answers: the route segment is the package id. No change here. <details><summary>A1 readings, before (origin/main d6d9645) and after (b48d967, product files byte-identical to head)</summary> Chain-depth layers, each run: | page | before | after | |:--|:--|:--| | list `showcase_task` | 13, 12 | 11, 12, 12 | | Setup open | 13, 12 | 11, 13, 10 | The card's grouping (requests that run together), list page: - before: L1 `runtime/config`, `get-session` · L2 `discovery` · L3 permissions, organization, i18n, `auth/config`, `meta/app`, `sys_user_preference` · L4 `meta/object?package=`, `me/apps`, bundle · L5 `meta/object?names=sys_user`, view, packages, `ai/agents` · L6 data reads · L7 `meta/object/sys_user`, notification receipt (7) - after: L1 `runtime/config`, `get-session`, `discovery` · then the same groups (6) Object list reads on Setup: before `?package=com.objectstack.setup` (49 B) + whole registry (862,486 B); after `?package=com.objectstack.setup` (49 B) + `?names=sys_package_installation` (49 B). An intermediate build without the bundle-answered presence read sent a third, `?names=` with the 14 required objects (111,925 B). After, list run 1 (ms from navigation, start→end): ``` L1: runtime/config (26→80) · auth/get-session (30→105) · discovery (31→107) L2: auth/me/permissions (712→757) · i18n/translations/en (723→760) · organization/get-active-member (724→768) · organization/list (724→773) · auth/config (756→776) L3: meta/app (760→804) · data/sys_user_preference (765→818) L4: meta/object?package=com.example.showcase (847→882) · me/apps (861→1005) · auth/me/localization (864→900) · meta/app/showcase_app/bundle (864→1002) L5: meta/object?names=sys_user (1015→1033) ``` Before, list run 1: ``` L1: runtime/config (22→29) · auth/get-session (23→71) L2: discovery (581→585) L3: auth/me/permissions (622→646) · i18n/translations/en (630→659) · organization/get-active-member (632→665) · organization/list (632→671) L4: auth/config (657→674) · meta/app (662→696) · data/sys_user_preference (664→705) L5: auth/me/localization (716→731) · meta/object?package=com.example.showcase (731→758) L6: me/apps (739→849) · meta/app/showcase_app/bundle (741→847) ``` Setup's sidebar after the change draws the same 46 entries, every `requiresObject` entry among them (Business Units, Sharing Rules, Queues, Webhooks, HTTP Deliveries ...), and the landing dashboard renders. </details> ## Tests - `ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx`, new top-level describe `discovery starts at parse time beside get-session, and the console reads that request (objectstack#34211)`: the shipped `index.html` scripts, run in document order, send `runtime/config`, `get-session` and `discovery` in one parse pass; `main.tsx` starts `readConsoleDiscovery(SERVER_BASE)`; the reader takes the parse-time request and an adapter-style `getSharedDiscovery` caller joins it (one discovery request, its own fetcher never called); a failed early request is asked again. - `ui/packages/app-shell/src/providers/__tests__/MetadataProvider.bundleFirstReads-28645.test.tsx`, new top-level describe `a presence read is answered from the entered app's bundle (objectstack#34211)`: a bundled name asks nothing; only the names the bundle does not hold go in one `?names=` read; CONTROL: with the bundle still on the wire the names are asked as before. The harness double now also answers the `?names=` list door. - `AppContent.emptyPackageScope-13046.test.tsx` and `AppContent.objectScope-12811.test.tsx`: the two CONTROLs that pinned the root's `?package=` then whole-registry read are now pins of the new shape: the package list, then one presence read, and the whole registry at no point. The 13046 one moved into its own top-level describe, since it is no longer a control. - `main.nativeBridgeVersion-29330.test.tsx` mocks the new boot kick beside the other boot modules it already mocks (it imports `main.tsx`). <details><summary>Ablations (scripts/ablation-replace.mjs, each restored: blob == HEAD, git diff HEAD empty)</summary> - `early-discovery.ts`: `const early = await takeEarlyDiscovery(url);` → `const early = null as { body: unknown } | null;` — 1 failed / 21 passed: `the console reader takes the parse-time request …` ("expected [ [ …(2) ], [ …(2) ] ] to have a length of 1 but got 2"). - `appObjectScope.ts`: the removed root exception put back (`if (!route.objectName && !own.served.some(…)) return { candidate, scope: null, … }`) — 2 failed / 13 passed: both root pins ("expected [ …(2) ] to include 'object?names=sys_member'" and "… 'object?names=cloud_only'"). - `MetadataProvider.tsx`: `if (bundled.state === 'hit') {` → `if (bundled.state === 'hit' && false) {` — 2 failed / 18 passed: `answers a bundled name from the bundle, and asks nothing` and `asks, in one ?names= read, only the names the bundle does not hold`. </details> ## Acceptance notes - **The card's two acceptance numbers are not reached.** List page: the card's grouping goes 7 → 6 layers. The chain counted on the built console stays at 11–12 layers, because most of what is left is client render and lazy-chunk gaps between requests, not request-to-request waits. The waits that are left are real dependencies: `meta/app` and the permission reads need the mounted tree, the package list and the bundle need `meta/app`'s answer (the URL holds the package id, the bundle route takes the app name), and the view and data reads need the object. Setup: two object reads remain, both 49 B and empty. The second is `DashboardView`'s widget gate asking for an object this runtime does not register, which only a server answer settles. The registry used to answer it, at 862 KB. Getting to one read would need a server-side signal, such as the app item saying its package holds no objects, or the bundle answering absence. That is out of this PR (claim: no server edit). - `ui/apps/console/index.html` is outside the claim's listed paths (`ui/apps/console/src/**` boot). Ask (1) cannot be met without it, because the session check starts there. The change follows its two sibling parse-time scripts. - The list page still reads `sys_user` twice: `meta/object?names=sys_user` (presence) at ~1015 ms and `meta/object/sys_user` (by name) at ~1571 ms. Noted, not traced here. - Ask (3) is unchanged: see What changes, item 3. ## Verification On head `93c21bff` (`origin/main` merged; the incoming commits touch no file of this diff): - Scoped re-check after the merge: `cd ui && pnpm exec vitest run` over the five test files named under Tests plus `App.listPageBootReadsOnce-28085` and `languageSeed.test.ts`: 7 files, 82 tests passed; `pnpm --filter @object-ui/app-shell run type-check` exit 0. - On `998d59a3` (the last product commit): `cd ui && pnpm exec vitest run packages/app-shell/src/console/ packages/app-shell/src/providers/ packages/app-shell/src/hooks/ packages/app-shell/src/views/__tests__/ apps/console/src/` under the verify lock: Test Files 847 passed, Tests 7836 passed. `pnpm --filter @object-ui/app-shell --filter @object-ui/console run type-check`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands` on `998d59a3`: 39 derived families, 39 run, each exit 0 (`pnpm --dir ui exec vitest run scripts/`: 171 files passed, 2 skipped). `pnpm check:new-line-citations` (ui): 0 new citations. - Dogfood battery: not run (no `!` in the title, no `(narrowing)` arm). - The CI families (Lint & Repo Gates, Type Check UI, Test UI, Build & E2E UI and the rest of the required set) are this PR's check-runs. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 17ceb2d commit de8d549

12 files changed

Lines changed: 444 additions & 57 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/console': patch
4+
---
5+
6+
fix(console, app-shell): discovery starts with the session check, and Setup's open no longer reads the whole object registry
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
The console asked for `GET /api/v1/discovery` from its main bundle, after the session check had answered and the bundle had downloaded, and the data layer waited for it before the first permission and app reads. `index.html` now sends it during parse, beside `get-session`, and the console's one shared discovery read takes that request, so it is no longer a round trip of its own in the boot.
12+
13+
Opening Setup (the root of an app whose package holds no objects of its own) read the package's empty object list and then the whole object registry. The root now reads as that app's object routes do: the package list, then the objects its entries require (`requiresObject`), and an object the entered app's bundle holds is answered from the bundle without a request. On the showcase app the registry is about 860 KB; Setup's open there now reads two object lists that answer empty instead.
14+
15+
What does not change: the routes that read the whole registry before (a record overlay, a record route with no declared record page) still do; which entries the sidebar shows is unchanged. No metadata key, value or default changes.

‎ui/apps/console/index.html‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,68 @@
183183
globalThis[Symbol.for('objectui.earlySessionCheck')] = { authUrl: authUrl, token: token, body: body };
184184
})();
185185
</script>
186+
<!--
187+
The page's ONE `GET /api/v1/discovery`, started during parse beside
188+
`get-session` above (objectstack#34211).
189+
190+
The data adapter's `connect()` waits for discovery before the metadata
191+
tree mounts, and the console asked for it from the bundle
192+
(`src/lib/early-discovery.ts`), after the main chunk had downloaded and
193+
evaluated: a round trip of its own between the session check and the
194+
boot's permission and app reads, though it needs nothing from the bundle
195+
or from the session's answer. This script asks the same question at parse
196+
time and hands the pending answer to `readConsoleDiscovery()`, which
197+
takes it once, when the URL matches, as the request behind the console's
198+
one shared discovery read.
199+
200+
The request is that reader's byte for byte: the same URL (the server
201+
origin through the same Vite HTML env substitution as the scripts above),
202+
`credentials: 'include'`, the same `Accept`, and the stored Bearer from
203+
the same `localStorage` key when there is one; the slot carries the URL
204+
and the token, and the reader takes it only when both match. It keeps
205+
the reader's 10 s bound: a request still open then is aborted and
206+
rejects as a timeout, which the reader reports. A request that fails
207+
otherwise or answers non-OK hands over a rejection, and the reader asks
208+
the server itself.
209+
210+
`src/__tests__/sessionCheckBootDedup.test.tsx` executes THIS script's
211+
text against the real `readConsoleDiscovery()`, so a drift between the
212+
two spellings of the slot fails a test rather than silently restoring the
213+
second request.
214+
-->
215+
<script>
216+
(function startEarlyDiscovery() {
217+
const injected = '%VITE_SERVER_URL%';
218+
const base = (injected.charAt(0) === '%' ? '' : injected).replace(/\/+$/, '');
219+
const url = base + '/api/v1/discovery';
220+
// The stored Bearer rides along, as on every console request; blocked
221+
// storage sends none, exactly as the reader then does.
222+
let token = '';
223+
try {
224+
token = localStorage.getItem('auth-session-token') || '';
225+
} catch (_) { /* storage blocked */ }
226+
const headers = { Accept: 'application/json' };
227+
if (token) headers.Authorization = 'Bearer ' + token;
228+
// The reader's 10 s bound: a hung request rejects as a timeout, which
229+
// the reader reports instead of asking again.
230+
const ctrl = new AbortController();
231+
const timer = setTimeout(function () { ctrl.abort(); }, 10000);
232+
const body = fetch(url, { credentials: 'include', headers: headers, signal: ctrl.signal })
233+
.then(
234+
function (res) {
235+
if (!res.ok) throw new Error('discovery ' + res.status);
236+
return res.json();
237+
},
238+
function (err) {
239+
throw err && err.name === 'AbortError' ? new Error('discovery timeout') : err;
240+
},
241+
)
242+
.finally(function () { clearTimeout(timer); });
243+
// The reader treats any other failure as "ask again"; it is never unhandled.
244+
body.catch(function () {});
245+
globalThis[Symbol.for('objectui.earlyDiscovery')] = { url: url, token: token, body: body };
246+
})();
247+
</script>
186248
<script>
187249
window.process = window.process || { env: { NODE_ENV: 'development' }, version: '', platform: 'browser' };
188250
</script>

‎ui/apps/console/src/__tests__/main.nativeBridgeVersion-29330.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ vi.mock('../pwaManifestIcons', async (importOriginal) => ({
7575
resolveManifestIcons,
7676
}));
7777
vi.mock('../lib/auth-preflight', () => ({ preflightAuth: async () => undefined }));
78+
vi.mock('../lib/early-discovery', () => ({ readConsoleDiscovery: async () => null }));
7879
vi.mock('../register-plugins', () => ({}));
7980
vi.mock('../registerDeveloperComponents', () => ({}));
8081
vi.mock('../registerStudioComponents', () => ({}));

‎ui/apps/console/src/__tests__/sessionCheckBootDedup.test.tsx‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2323
import { render, screen, act, cleanup } from '@testing-library/react';
2424
import { AuthProvider, useAuth } from '@object-ui/auth';
2525
import { preflightAuth } from '../lib/auth-preflight';
26+
import { readConsoleDiscovery } from '../lib/early-discovery';
27+
import { getSharedDiscovery } from '@object-ui/data-objectstack';
28+
import { clearSharedDiscoveryCache } from '../../../../packages/data-objectstack/src/sharedDiscovery';
2629

2730
const TOKEN = 'tok_valid';
2831
const EARLY_SLOT = Symbol.for('objectui.earlySessionCheck');
@@ -341,3 +344,135 @@ describe('one page, one server origin', () => {
341344
expect(sessionCalls()[0]![0]).toBe('/api/v1/auth/get-session');
342345
});
343346
});
347+
348+
describe('discovery starts at parse time beside get-session, and the console reads that request (objectstack#34211)', () => {
349+
const DISCOVERY_SLOT = Symbol.for('objectui.earlyDiscovery');
350+
const SERVER = 'https://api.example.test';
351+
const discoveryCalls = () => fetchStub.mock.calls.filter(([input]) => urlOf(input).includes('/discovery'));
352+
353+
beforeEach(() => {
354+
clearSharedDiscoveryCache();
355+
delete (globalThis as unknown as Record<symbol, unknown>)[DISCOVERY_SLOT];
356+
});
357+
afterEach(() => {
358+
clearSharedDiscoveryCache();
359+
delete (globalThis as unknown as Record<symbol, unknown>)[DISCOVERY_SLOT];
360+
});
361+
362+
it('is sent in the same parse pass as get-session, before any bundle code runs', () => {
363+
localStorage.setItem('auth-session-token', TOKEN);
364+
runScript('applyEarlyBranding');
365+
runEarlySessionCheck();
366+
runScript('startEarlyDiscovery');
367+
368+
const urls = fetchStub.mock.calls.map(([input]) => urlOf(input));
369+
expect(urls).toEqual(['/api/v1/runtime/config', '/api/v1/auth/get-session', '/api/v1/discovery']);
370+
});
371+
372+
it('main.tsx starts the console reader on every boot, over the same server base', () => {
373+
expect(mainSource).toContain('void readConsoleDiscovery(SERVER_BASE)');
374+
});
375+
376+
it("the console reader takes the parse-time request, and the adapter's connect joins it: one discovery per load", async () => {
377+
runScript('startEarlyDiscovery', applyViteHtmlEnv(indexHtml, { VITE_SERVER_URL: SERVER }));
378+
await settle();
379+
380+
const consoleRead = readConsoleDiscovery(SERVER);
381+
// `ObjectStackAdapter.connect()` asks the same shared cache with a fetcher of its own.
382+
const adapterFetcher = vi.fn(async () => ({ from: 'adapter' }));
383+
const adapterRead = getSharedDiscovery(SERVER, adapterFetcher);
384+
385+
expect(await consoleRead).toBeNull();
386+
expect(await adapterRead).toBeNull();
387+
expect(adapterFetcher).not.toHaveBeenCalled();
388+
expect(discoveryCalls()).toHaveLength(1);
389+
expect(discoveryCalls()[0]![0]).toBe(`${SERVER}/api/v1/discovery`);
390+
});
391+
392+
const authOf = (call: unknown[]) => new Headers((call[1] as RequestInit | undefined)?.headers).get('Authorization');
393+
394+
it('carries the stored Bearer, in the parse-time request and in the reader\'s own, and none without one', async () => {
395+
localStorage.setItem('auth-session-token', TOKEN);
396+
runScript('startEarlyDiscovery');
397+
expect(authOf(discoveryCalls()[0]!)).toBe(`Bearer ${TOKEN}`);
398+
await readConsoleDiscovery('');
399+
expect(discoveryCalls()).toHaveLength(1);
400+
401+
// The reader's own request: no slot left to take.
402+
clearSharedDiscoveryCache();
403+
delete (globalThis as unknown as Record<symbol, unknown>)[DISCOVERY_SLOT];
404+
await readConsoleDiscovery('');
405+
expect(discoveryCalls()).toHaveLength(2);
406+
expect(authOf(discoveryCalls()[1]!)).toBe(`Bearer ${TOKEN}`);
407+
408+
localStorage.clear();
409+
clearSharedDiscoveryCache();
410+
runScript('startEarlyDiscovery');
411+
await readConsoleDiscovery('');
412+
expect(discoveryCalls()).toHaveLength(3);
413+
expect(authOf(discoveryCalls()[2]!)).toBeNull();
414+
});
415+
416+
it('a parse-time request sent with a token the preflight has since purged is not taken', async () => {
417+
localStorage.setItem('auth-session-token', 'tok_stale');
418+
runScript('startEarlyDiscovery');
419+
localStorage.removeItem('auth-session-token');
420+
421+
await readConsoleDiscovery('');
422+
423+
expect(discoveryCalls()).toHaveLength(2);
424+
expect(authOf(discoveryCalls()[1]!)).toBeNull();
425+
});
426+
427+
it('a parse-time request that never answers rejects as a timeout within the 10 s bound, and is not asked again', async () => {
428+
vi.useFakeTimers();
429+
try {
430+
(globalThis as unknown as Record<symbol, unknown>)[DISCOVERY_SLOT] = {
431+
url: '/api/v1/discovery',
432+
token: '',
433+
body: new Promise(() => {}),
434+
};
435+
const read = readConsoleDiscovery('');
436+
const outcome = read.then(() => 'answered', (err: Error) => err.message);
437+
await vi.advanceTimersByTimeAsync(9_999);
438+
let settled = false;
439+
void outcome.then(() => { settled = true; });
440+
await Promise.resolve();
441+
expect(settled).toBe(false);
442+
await vi.advanceTimersByTimeAsync(1);
443+
expect(await outcome).toBe('discovery timeout');
444+
expect(discoveryCalls()).toHaveLength(0);
445+
} finally {
446+
vi.useRealTimers();
447+
}
448+
});
449+
450+
it('the parse-time request itself is aborted at 10 s and hands over a timeout', async () => {
451+
vi.useFakeTimers();
452+
try {
453+
fetchStub.mockImplementationOnce(
454+
(_input: RequestInfo | URL, init?: RequestInit) =>
455+
new Promise<Response>((_, reject) => {
456+
init?.signal?.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })));
457+
}),
458+
);
459+
runScript('startEarlyDiscovery');
460+
const slot = (globalThis as unknown as Record<symbol, { body: Promise<unknown> }>)[DISCOVERY_SLOT]!;
461+
const outcome = slot.body.then(() => 'answered', (err: Error) => err.message);
462+
await vi.advanceTimersByTimeAsync(10_000);
463+
expect(await outcome).toBe('discovery timeout');
464+
} finally {
465+
vi.useRealTimers();
466+
}
467+
});
468+
469+
it('a failed parse-time request is not reused: the reader asks the server itself', async () => {
470+
fetchStub.mockImplementationOnce(async () => json({ error: 'boom' }, 503));
471+
runScript('startEarlyDiscovery');
472+
await settle();
473+
474+
await readConsoleDiscovery('');
475+
476+
expect(discoveryCalls()).toHaveLength(2);
477+
});
478+
});

‎ui/apps/console/src/languageSeed.ts‎

Lines changed: 2 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,9 @@
100100
*/
101101
import { cacheLanguageSeed, readCachedLanguageSeed, readStoredLanguage } from '@object-ui/i18n';
102102
import { getSessionOwnerChangeCount } from '@object-ui/auth';
103-
import { getSharedDiscovery } from '@object-ui/data-objectstack';
104103
import { sharedGetJson } from '@object-ui/types';
105104
import { resolveLocaleAmong } from '@objectstack/spec/system';
105+
import { readConsoleDiscovery } from './lib/early-discovery';
106106

107107
/**
108108
* How long a true first visit will wait for the resolved locale before booting
@@ -117,38 +117,9 @@ interface MeLocalizationResponse {
117117
locale?: string | null;
118118
}
119119

120-
/**
121-
* How long the console's discovery request may run before it is abandoned.
122-
* The request is shared with the data adapter's `connect()`, so this bound is
123-
* the adapter's too; it matches the shell's own discovery bound.
124-
*/
125-
const DISCOVERY_TIMEOUT_MS = 10_000;
126-
127120
/** This page-load's read of the language a choice-less read states, once started. */
128121
let preferredLocale: Promise<string | undefined> | null = null;
129122

130-
/** The discovery document, through the console's one shared request. */
131-
async function fetchDiscovery(serverBase: string): Promise<unknown> {
132-
return getSharedDiscovery(serverBase, async () => {
133-
const ctrl = new AbortController();
134-
const timer = setTimeout(() => ctrl.abort(), DISCOVERY_TIMEOUT_MS);
135-
try {
136-
const res = await fetch(`${serverBase}/api/v1/discovery`, {
137-
credentials: 'include',
138-
headers: { Accept: 'application/json' },
139-
signal: ctrl.signal,
140-
});
141-
if (!res.ok) {
142-
throw Object.assign(new Error(`discovery ${res.status}`), { status: res.status });
143-
}
144-
const body = await res.json();
145-
return body && typeof body.success === 'boolean' && 'data' in body ? body.data : body;
146-
} finally {
147-
clearTimeout(timer);
148-
}
149-
});
150-
}
151-
152123
/**
153124
* The language a read with no explicit choice states (objectstack#33985,
154125
* ruling 6915665005): the browser's language when the app lists it in
@@ -196,7 +167,7 @@ function readSupportedLocales(discovery: unknown): string[] {
196167
*/
197168
export function loadPreferredLocale(serverBase: string): Promise<string | undefined> {
198169
if (!preferredLocale) {
199-
preferredLocale = fetchDiscovery(serverBase).then(
170+
preferredLocale = readConsoleDiscovery(serverBase).then(
200171
(discovery) => {
201172
const browser = typeof navigator === 'undefined' ? undefined : navigator.language;
202173
return pickPreferredLocale(browser, readSupportedLocales(discovery));

0 commit comments

Comments
 (0)