From 7e40d251e8fb007ed58403461b0855948cb77d61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=85=E8=86=80?= Date: Fri, 23 Oct 2026 23:21:30 +0800 Subject: [PATCH] fix(i18n): bound and cache translation loads Repeated misses and simultaneous override loads spend KV reads for the same language. Cache confirmed misses and share bounded loads without caching read failures as missing translations. --- server/lib/lib/i18n.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/server/lib/lib/i18n.ts b/server/lib/lib/i18n.ts index bcaa3fa..2c85704 100644 --- a/server/lib/lib/i18n.ts +++ b/server/lib/lib/i18n.ts @@ -1,5 +1,6 @@ import { en } from "./locales/en"; import { zh } from "./locales/zh"; +import { sharedFlight, type Flight } from "./shared-flight"; type NestedStrings = { [key: string]: string | NestedStrings }; export type Translations = NestedStrings; @@ -22,6 +23,13 @@ function interpolate(template: string, params: Record): const cache = new Map(); +/** Languages found without an override, until when (a read failure is not one). */ +const missing = new Map(); +const MISSING_RECHECK_MS = 5 * 60_000; +const MAX_MISSING = 100; +/** Override reads in flight: concurrent asks for one language share a KV read. */ +const loading = new Map>(); + export async function loadTranslations( lang: string, kv?: { get(key: string, type: "json"): Promise }, @@ -31,9 +39,19 @@ export async function loadTranslations( const cached = cache.get(lang); if (cached) return cached; + // A language with no override is not looked up again for a while: every + // dispatch asks for each group's language, and each ask is a KV read. + if ((missing.get(lang) ?? 0) > Date.now()) return en; if (!kv) return en; + return sharedFlight(loading, lang, () => readOverride(lang, kv), 10_000); +} + +async function readOverride( + lang: string, + kv: { get(key: string, type: "json"): Promise }, +): Promise { try { const stored = await kv.get>(`i18n:${lang}`, "json"); if (stored) { @@ -41,6 +59,8 @@ export async function loadTranslations( cache.set(lang, merged); return merged; } + if (missing.size >= MAX_MISSING) missing.clear(); + missing.set(lang, Date.now() + MISSING_RECHECK_MS); } catch { // KV read failed, fall back to EN }