import "server-only"; import { callMobileApi } from "@/app/lib/server/mobileApi"; // Version-aware in-memory per-locale catalog cache (catalog-cache-invalidation // spec). loadMessageCatalog first fetches the cheap catalog version // (/api/admin/messages/catalog-version) and caches the catalog under a // `locale@version` key. A version bump — any message or locale save in // services-system — makes the old key unreachable, so the next request // refetches: immediate, cross-instance, no fixed-TTL wait. This is the durable // equivalent of backoffice's per-pod PubSub reload, with no PubSub infra. // // Degrades, never blanks: a version-fetch failure serves the last-known cached // catalog (or today's plain-TTL behaviour when nothing is cached yet); a // catalog-fetch failure at a known version serves the last-known catalog. // clearMessageCache() remains the explicit seam (used by tests). // // Bounded retention (review fix): per locale only the current + previous // version entries are kept — every edit bumps the version, and without // eviction the old `locale@version` map would grow forever. `lastKnown` is a // separate in-place reference (the most recent versioned catalog) so the // stale-serve fallback survives eviction and even TTL expiry. const TTL_MS = 15 * 60 * 1000; interface CacheEntry { data: Record; expiresAt: number; } interface LocaleCatalogState { /** Bounded: at most the current + previous version entries for this locale. */ byVersion: Map; /** Most recent versioned catalog, kept regardless of eviction/TTL — the stale-serve floor. */ lastKnown: CacheEntry | undefined; /** Plain-TTL entry for the no-version path (pre-rollout / version-endpoint outage). */ legacy: CacheEntry | undefined; } const cache = new Map(); export function clearMessageCache(): void { cache.clear(); } /** Test seam: how many versioned entries are retained for a locale (bounded by eviction). */ export function cachedCatalogEntryCount(locale: string): number { return cache.get(locale)?.byVersion.size ?? 0; } /** Cheap catalog version fetch; null on any failure so callers degrade, never throw. */ async function fetchCatalogVersion(): Promise { try { const result = await callMobileApi<{ version?: number }>("/api/admin/messages/catalog-version"); if (!result.ok || typeof result.data?.version !== "number") { return null; } return String(result.data.version); } catch { return null; } } function ensureState(locale: string): LocaleCatalogState { let state = cache.get(locale); if (!state) { state = { byVersion: new Map(), lastKnown: undefined, legacy: undefined }; cache.set(locale, state); } return state; } /** Inserts a versioned entry and evicts all but the two most recent versions for the locale. */ function setVersioned(state: LocaleCatalogState, version: string, data: Record, now: number): void { const entry: CacheEntry = { data, expiresAt: now + TTL_MS }; state.lastKnown = entry; state.byVersion.set(version, entry); if (state.byVersion.size > 2) { const versions = [...state.byVersion.keys()].sort((a, b) => Number(b) - Number(a)); for (const oldVersion of versions.slice(2)) { state.byVersion.delete(oldVersion); } } } async function fetchCatalog(locale: string): Promise | null> { const result = await callMobileApi>( `/api/admin/messages/catalog/${encodeURIComponent(locale)}`, ); return result.ok && result.data ? result.data : null; } /** Load the message catalog for a locale, keyed on the catalog version. `now` is injectable for tests. */ export async function loadMessageCatalog( locale: string, now: number = Date.now(), ): Promise> { const version = await fetchCatalogVersion(); if (version !== null) { const state = ensureState(locale); const hit = state.byVersion.get(version); if (hit && hit.expiresAt > now) return hit.data; const data = await fetchCatalog(locale); if (data) { setVersioned(state, version, data, now); return data; } // Catalog fetch failed at this version: serve the last-known catalog rather than blank. return state.lastKnown?.data ?? {}; } // Version fetch failed: serve the last-known catalog if any, else today's plain-TTL // behaviour (catalog keyed on the locale alone) so pre-rollout / version-outage still works. const state = cache.get(locale); if (state?.lastKnown) return state.lastKnown.data; const legacyHit = state?.legacy; if (legacyHit && legacyHit.expiresAt > now) return legacyHit.data; const data = await fetchCatalog(locale); if (!data) { return legacyHit?.data ?? {}; } ensureState(locale).legacy = { data, expiresAt: now + TTL_MS }; return data; }