Files
hertzbeat/web-next/lib/workbench-load-cache.ts
T
Logic 2de48d2caa feat: complete HertzBeat 2.0 novice workflows
Refine entity, monitor, alert, settings, observability, and shared operator workflows; add scale guards, route compatibility, release validation, and Product Design coverage.

AI assistance: used for draft implementation and test iteration.\nHuman validation: Node 22 production build; 426 frontend files and 3,398 tests; 59-route matrix; release budget 7.84 MiB / 8.00 MiB; focused backend tests and Browser QA.\nRisk notes: local scale proof covers 2,005 entities; sustained concurrent-ingestion SLA remains deployment-specific.
2026-07-10 14:54:43 +08:00

70 lines
1.7 KiB
TypeScript

type WorkbenchLoadCacheOptions = {
settledTtlMs?: number;
now?: () => number;
};
type WorkbenchLoadCacheEntry<T> = {
promise: Promise<T>;
settled: boolean;
expiresAt: number;
};
const workbenchLoadCache = new Map<string, WorkbenchLoadCacheEntry<unknown>>();
function resolveNow(options: WorkbenchLoadCacheOptions) {
return options.now ? options.now() : Date.now();
}
export function consumeWorkbenchLoad<T>(
cacheKey: string,
load: () => Promise<T>,
options: WorkbenchLoadCacheOptions = {}
) {
const now = resolveNow(options);
const existing = workbenchLoadCache.get(cacheKey) as WorkbenchLoadCacheEntry<T> | undefined;
if (existing && (!existing.settled || existing.expiresAt > now)) {
return existing.promise;
}
if (existing) {
workbenchLoadCache.delete(cacheKey);
}
const settledTtlMs = Math.max(0, options.settledTtlMs ?? 0);
let entry: WorkbenchLoadCacheEntry<T> | null = null;
const promise = load().then(
value => {
if (!entry) return value;
entry.settled = true;
if (settledTtlMs > 0) {
entry.expiresAt = resolveNow(options) + settledTtlMs;
} else if (workbenchLoadCache.get(cacheKey) === entry) {
workbenchLoadCache.delete(cacheKey);
}
return value;
},
error => {
if (entry && workbenchLoadCache.get(cacheKey) === entry) {
workbenchLoadCache.delete(cacheKey);
}
throw error;
}
);
entry = {
promise,
settled: false,
expiresAt: Number.POSITIVE_INFINITY,
};
workbenchLoadCache.set(cacheKey, entry);
return promise;
}
export function resetWorkbenchLoadCache() {
workbenchLoadCache.clear();
}
export function forgetWorkbenchLoad(cacheKey: string) {
workbenchLoadCache.delete(cacheKey);
}