Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/cloud-4964-i18n-locales-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/console': patch
---

fix(console): a signed-in open asks `GET /api/v1/i18n/locales` once, not twice

Clause-②: no
Metadata-protocol: none

The console has two readers of the locale list: the globe menu's locale codes (`loadLocales`) and the language load, which reads the server's declared fallback chain beside the active language's bundle (objectstack#36809). Each sent its own request, so every signed-in page open asked the server the same question twice. Both now share one answer per page load (`localesRead.ts`), and a language switch reuses it too. A failed read is not kept, so the next reader asks again, as before.
3 changes: 3 additions & 0 deletions ui/apps/console/src/__tests__/i18nAfterSignIn-12034.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ import { TokenStorage, type AuthClient, type AuthPublicConfig, type AuthUser } f
import { App } from '../App';
import { loadLanguage } from '../loadLanguage';
import { loadLocales } from '../loadLocales';
import { __resetLocalesRead } from '../localesRead';

const zh = builtInLocales['zh-Hans'];
const TOKEN = 'tok-12034';
Expand Down Expand Up @@ -325,6 +326,8 @@ beforeEach(() => {
});

afterEach(() => {
// One /i18n/locales read per page load (cloud#4964): each case is its own page load.
__resetLocalesRead();
cleanup();
vi.unstubAllGlobals();
vi.restoreAllMocks();
Expand Down
3 changes: 3 additions & 0 deletions ui/apps/console/src/loadLanguage.fallbackChain-36809.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
import { TokenStorage } from '@object-ui/auth';
import { loadLanguage } from './loadLanguage';
import { publishAuthState } from './i18nSession';
import { __resetLocalesRead } from './localesRead';

const FLOW = 'deal_review';
const ZH = { flows: { [FLOW]: { nodes: { score_deal: { label: '评分' } } } } };
Expand Down Expand Up @@ -63,6 +64,8 @@ beforeEach(() => {
});

afterEach(() => {
// One /i18n/locales read per page load (cloud#4964): each case is its own page load.
__resetLocalesRead();
vi.unstubAllGlobals();
vi.restoreAllMocks();
TokenStorage.clear();
Expand Down
3 changes: 3 additions & 0 deletions ui/apps/console/src/loadLanguage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { FlowRunner, type ScreenFlowState } from '@object-ui/app-shell';
import { TokenStorage } from '@object-ui/auth';
import { loadLanguage } from './loadLanguage';
import { publishAuthState } from './i18nSession';
import { __resetLocalesRead } from './localesRead';

/**
* Serve `body` as the endpoint's JSON answer. A real `Response`: the loader
Expand Down Expand Up @@ -63,6 +64,8 @@ beforeEach(() => {
});

afterEach(() => {
// One /i18n/locales read per page load (cloud#4964): each case is its own page load.
__resetLocalesRead();
vi.unstubAllGlobals();
vi.restoreAllMocks();
TokenStorage.clear();
Expand Down
21 changes: 15 additions & 6 deletions ui/apps/console/src/loadLanguage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@
* (`withDeclaredFlowsFallback`, `@object-ui/i18n`), where the flow-label
* readers find them, so a flow label `lang` does not carry reads the fallback
* locale's text, as the server's own reads do. A server that declares no chain
* costs nothing more than the locale-list read: the answer is exactly what it
* was. Either extra read failing degrades to that same answer.
* costs nothing more: the locale list is the page load's one shared read
* (`./localesRead.ts`, cloud#4964), the one `loadLocales` makes for the globe
* menu, and the answer is exactly what it was. Either extra read failing
* degrades to that same answer.
*/
import {
isSpecTranslationData,
Expand All @@ -44,6 +46,7 @@ import {
} from '@object-ui/i18n';
import { resolveLocaleAmong } from '@objectstack/spec/system';
import { i18nFetch, whenSessionAnswered } from './i18nSession';
import { readLocales } from './localesRead';

const serverUrl = () => import.meta.env.VITE_SERVER_URL || '';

Expand Down Expand Up @@ -75,10 +78,16 @@ interface DeclaredChain {
*/
async function fetchDeclaredChain(): Promise<DeclaredChain | null> {
try {
const res = await i18nFetch(`${serverUrl()}/api/v1/i18n/locales`);
if (!res.ok) return null;
const json = await res.json();
const body = json?.data && typeof json.data === 'object' ? json.data : json;
// The page load's one `/i18n/locales` read, shared with `loadLocales`
// (`./localesRead.ts`, cloud#4964).
const answer = await readLocales();
if (!answer.ok) return null;
const json = answer.body as { data?: unknown } | null;
const body = (json?.data && typeof json.data === 'object' ? json.data : json) as {
fallbackChain?: unknown;
sourceLocale?: unknown;
locales?: unknown;
} | null;
const chain: unknown[] = Array.isArray(body?.fallbackChain) ? body.fallbackChain : [];
const fallbackChain = chain.filter((code): code is string => typeof code === 'string' && code.length > 0);
if (fallbackChain.length === 0) return null;
Expand Down
3 changes: 3 additions & 0 deletions ui/apps/console/src/loadLocales.afterBootPaint-12980.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { TokenStorage } from '@object-ui/auth';
import { loadLocales, __resetBootPainted } from './loadLocales';
import { publishAuthState } from './i18nSession';
import { __resetLocalesRead } from './localesRead';

let splash: HTMLElement | null = null;
const someFrames = () => new Promise<void>((r) => setTimeout(r, 80));
Expand All @@ -31,6 +32,8 @@ beforeEach(() => {
});

afterEach(() => {
// One /i18n/locales read per page load (cloud#4964): each case is its own page load.
__resetLocalesRead();
splash?.remove();
splash = null;
vi.unstubAllGlobals();
Expand Down
3 changes: 3 additions & 0 deletions ui/apps/console/src/loadLocales.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { TokenStorage } from '@object-ui/auth';
import { loadLocales } from './loadLocales';
import { publishAuthState } from './i18nSession';
import { __resetLocalesRead } from './localesRead';

/**
* A real `Response`: the loader reads through the console's authenticated
Expand All @@ -34,6 +35,8 @@ beforeEach(() => {
});

afterEach(() => {
// One /i18n/locales read per page load (cloud#4964): each case is its own page load.
__resetLocalesRead();
vi.unstubAllGlobals();
vi.restoreAllMocks();
TokenStorage.clear();
Expand Down
53 changes: 26 additions & 27 deletions ui/apps/console/src/loadLocales.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
* which is itself applied after the paint. Until it answers, the provider
* offers the built-in packs, as it does for any `[]`.
*/
import { i18nFetch, whenSessionAnswered } from './i18nSession';
import { whenSessionAnswered } from './i18nSession';
import { readLocales } from './localesRead';

/** The boot splashes: `LoadingScreen`'s marker, and the pre-JS one in `index.html`. */
const BOOT_SPLASH_SELECTOR = '[data-boot-splash], #boot-splash';
Expand Down Expand Up @@ -85,32 +86,30 @@ export async function loadLocales(): Promise<string[]> {
// nothing rather than an anonymous read.
await whenBootPainted();
if (!(await whenSessionAnswered())) return [];
try {
const serverUrl = import.meta.env.VITE_SERVER_URL || '';
const res = await i18nFetch(`${serverUrl}/api/v1/i18n/locales`);
if (!res.ok) {
console.warn(`[i18n] Failed to load the app locale list: HTTP ${res.status}`);
return [];
}
const json = await res.json();
// Unwrap the spec REST API envelope when present; mock / local-dev servers
// may answer with the bare `{ locales: [...] }` body or a plain array.
const raw = json?.data?.locales ?? json?.locales ?? json;
if (!Array.isArray(raw)) {
console.warn('[i18n] Unexpected /i18n/locales payload; ignoring.');
return [];
}
const codes: string[] = [];
for (const entry of raw) {
// Descriptors are the contract; a bare string is tolerated only because
// `getLocales()` hands back `string[]` and older mocks pass it straight
// through — the very drift the shared descriptor mapping exists to stop.
const code = typeof entry === 'string' ? entry : entry?.code;
if (typeof code === 'string' && code.length > 0 && !codes.includes(code)) codes.push(code);
}
return codes;
} catch (err) {
console.warn('[i18n] Failed to load the app locale list:', err);
// One read per page load, shared with `loadLanguage`'s declared-chain read
// (`./localesRead.ts`, cloud#4964): by the time the paint releases this
// reader, that read has usually answered, and nothing more is sent.
const answer = await readLocales();
if (!answer.ok) {
if (answer.status !== undefined) console.warn(`[i18n] Failed to load the app locale list: HTTP ${answer.status}`);
else console.warn('[i18n] Failed to load the app locale list:', answer.error);
return [];
}
const json = answer.body as { data?: { locales?: unknown }; locales?: unknown } | null;
// Unwrap the spec REST API envelope when present; mock / local-dev servers
// may answer with the bare `{ locales: [...] }` body or a plain array.
const raw = json?.data?.locales ?? json?.locales ?? json;
if (!Array.isArray(raw)) {
console.warn('[i18n] Unexpected /i18n/locales payload; ignoring.');
return [];
}
const codes: string[] = [];
for (const entry of raw) {
// Descriptors are the contract; a bare string is tolerated only because
// `getLocales()` hands back `string[]` and older mocks pass it straight
// through — the very drift the shared descriptor mapping exists to stop.
const code = typeof entry === 'string' ? entry : entry?.code;
if (typeof code === 'string' && code.length > 0 && !codes.includes(code)) codes.push(code);
}
return codes;
}
94 changes: 94 additions & 0 deletions ui/apps/console/src/localesRead.sharedRead-4964.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* cloud#4964 — a signed-in open asks `GET /api/v1/i18n/locales` once.
*
* Two console readers want that answer: `loadLocales` (the globe menu's
* locale codes) and `loadLanguage` (the declared fallback chain beside the
* active language's bundle, objectstack#36809). Each sent its own request, so
* every warm open of a console page asked the server the same question twice,
* which the cloud control-plane call budget measured as a duplicate URL. Both
* now read one shared answer per page load (`./localesRead.ts`).
*/
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { TokenStorage } from '@object-ui/auth';
import { loadLanguage } from './loadLanguage';
import { loadLocales, __resetBootPainted } from './loadLocales';
import { publishAuthState } from './i18nSession';
import { __resetLocalesRead } from './localesRead';

const LOCALES = {
locales: [
{ code: 'zh-CN', label: 'zh-CN', isDefault: true },
{ code: 'en', label: 'en', isDefault: false },
],
sourceLocale: 'en',
fallbackChain: ['en'],
};

/** Serve the `/i18n` reads by URL and record each URL asked. */
function serve(localesStatus = 200) {
const asked: string[] = [];
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
asked.push(url);
if (url.endsWith('/api/v1/i18n/locales')) {
if (localesStatus !== 200) return new Response('{}', { status: localesStatus });
return new Response(JSON.stringify({ success: true, data: LOCALES }), { status: 200 });
}
const match = /\/api\/v1\/i18n\/translations\/([^/?]+)$/.exec(url);
if (match) {
return new Response(JSON.stringify({ success: true, data: { locale: match[1], translations: { app: {} } } }), { status: 200 });
}
return new Response('{}', { status: 404 });
}),
);
return asked;
}

const localesReads = (asked: string[]) => asked.filter((url) => url.endsWith('/api/v1/i18n/locales')).length;

beforeEach(() => {
__resetLocalesRead();
__resetBootPainted();
publishAuthState({ isAuthenticated: true, isLoading: false });
});

afterEach(() => {
__resetLocalesRead();
vi.unstubAllGlobals();
vi.restoreAllMocks();
TokenStorage.clear();
});

describe('one /i18n/locales read per page load (cloud#4964)', () => {
it('the boot: the language load and the locale list together ask once, and each gets its answer', async () => {
const asked = serve();

const [, codes] = await Promise.all([loadLanguage('zh-CN'), loadLocales()]);

expect(codes).toEqual(['zh-CN', 'en']);
expect(localesReads(asked)).toBe(1);
});

it('a later reader, and a language switch, reuse the answer', async () => {
const asked = serve();

await loadLanguage('zh-CN');
await loadLocales();
await loadLanguage('en');

expect(localesReads(asked)).toBe(1);
});

it('a failed read is not kept: the next reader asks again', async () => {
const asked = serve(503);
vi.spyOn(console, 'warn').mockImplementation(() => {});

await expect(loadLocales()).resolves.toEqual([]);
expect(localesReads(asked)).toBe(1);

await loadLanguage('zh-CN');
expect(localesReads(asked)).toBe(2);
});
});
59 changes: 59 additions & 0 deletions ui/apps/console/src/localesRead.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* One `GET /api/v1/i18n/locales` per page load, shared by the console's two
* readers of it (cloud#4964).
*
* `loadLocales` reads the held locales (`locales[].code`) for the globe menu;
* `loadLanguage` reads the declared fallback chain, the authored language and
* the same codes beside the active language's bundle (objectstack#36809). Each
* used to send its own request, so every signed-in open asked the server the
* same question twice. The answer is the deployment's locale declaration, not
* the reader's, so one answer serves both for the life of the page load,
* including `loadLanguage`'s later calls on a language switch.
*
* The parsed JSON body is shared and each reader keeps its own parse and its
* own degrade-quietly rule. A failed read (a non-2xx answer, a network error,
* an unparsable body) answers `null` and is not kept: the next reader asks
* again, as it did before the reads were shared. Callers are already signed in
* (`whenSessionAnswered`); this module adds no session rule of its own.
*/
import { i18nFetch } from './i18nSession';

/** What a failed read answers: the HTTP status when there was one. */
export interface LocalesReadFailure {
ok: false;
status?: number;
error?: unknown;
}

export type LocalesReadAnswer = { ok: true; body: unknown } | LocalesReadFailure;

let pending: Promise<LocalesReadAnswer> | null = null;

/**
* The `/i18n/locales` answer for this page load: one request however many
* readers ask, concurrently or later. A failure is handed to every reader that
* shared it, then forgotten, so a later reader asks again.
*/
export function readLocales(): Promise<LocalesReadAnswer> {
if (pending) return pending;
const serverUrl = import.meta.env.VITE_SERVER_URL || '';
const read: Promise<LocalesReadAnswer> = (async () => {
try {
const res = await i18nFetch(`${serverUrl}/api/v1/i18n/locales`);
if (!res.ok) return { ok: false, status: res.status };
return { ok: true, body: await res.json() };
} catch (error) {
return { ok: false, error };
}
})();
pending = read;
void read.then((answer) => {
if (!answer.ok && pending === read) pending = null;
});
return read;
}

/** Test seam: forget the shared answer, so a case reads afresh. Not public. */
export function __resetLocalesRead(): void {
pending = null;
}
Loading