Files
co-lite/solvway-admin-portal/app/lib/server/messages.ts
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

127 lines
4.8 KiB
TypeScript

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<string, string>;
expiresAt: number;
}
interface LocaleCatalogState {
/** Bounded: at most the current + previous version entries for this locale. */
byVersion: Map<string, CacheEntry>;
/** 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<string, LocaleCatalogState>();
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<string | null> {
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<string, string>, 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<Record<string, string> | null> {
const result = await callMobileApi<Record<string, string>>(
`/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<Record<string, string>> {
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;
}