| 40 | * @returns A memoized version of the function |
| 41 | */ |
| 42 | export function memoizeWithTTL<Args extends unknown[], Result>( |
| 43 | f: (...args: Args) => Result, |
| 44 | cacheLifetimeMs: number = 5 * 60 * 1000, // Default 5 minutes |
| 45 | ): MemoizedFunction<Args, Result> { |
| 46 | const cache = new Map<string, CacheEntry<Result>>() |
| 47 | |
| 48 | const memoized = (...args: Args): Result => { |
| 49 | const key = jsonStringify(args) |
| 50 | const cached = cache.get(key) |
| 51 | const now = Date.now() |
| 52 | |
| 53 | // Populate cache |
| 54 | if (!cached) { |
| 55 | const value = f(...args) |
| 56 | cache.set(key, { |
| 57 | value, |
| 58 | timestamp: now, |
| 59 | refreshing: false, |
| 60 | }) |
| 61 | return value |
| 62 | } |
| 63 | |
| 64 | // If we have a stale cache entry and it's not already refreshing |
| 65 | if ( |
| 66 | cached && |
| 67 | now - cached.timestamp > cacheLifetimeMs && |
| 68 | !cached.refreshing |
| 69 | ) { |
| 70 | // Mark as refreshing to prevent multiple parallel refreshes |
| 71 | cached.refreshing = true |
| 72 | |
| 73 | // Schedule async refresh (non-blocking). Both .then and .catch are |
| 74 | // identity-guarded: a concurrent cache.clear() + cold-miss stores a |
| 75 | // newer entry while this microtask is queued. .then overwriting with |
| 76 | // the stale refresh's result is worse than .catch deleting (persists |
| 77 | // wrong data for full TTL vs. self-correcting on next call). |
| 78 | Promise.resolve() |
| 79 | .then(() => { |
| 80 | const newValue = f(...args) |
| 81 | if (cache.get(key) === cached) { |
| 82 | cache.set(key, { |
| 83 | value: newValue, |
| 84 | timestamp: Date.now(), |
| 85 | refreshing: false, |
| 86 | }) |
| 87 | } |
| 88 | }) |
| 89 | .catch(e => { |
| 90 | logError(e) |
| 91 | if (cache.get(key) === cached) { |
| 92 | cache.delete(key) |
| 93 | } |
| 94 | }) |
| 95 | |
| 96 | // Return the stale value immediately |
| 97 | return cached.value |
| 98 | } |
| 99 | |