|
| 1 | +import NodeCache from "node-cache"; |
| 2 | +import { childLogger } from "../logger.js"; |
| 3 | + |
| 4 | +const logger = childLogger("response-cache"); |
| 5 | + |
| 6 | +export interface ResponseCache<T> { |
| 7 | + getOrLoad(key: string, loader: () => Promise<T>): Promise<T>; |
| 8 | + /** Drops a single key. Mostly useful from a script or a future write path. */ |
| 9 | + invalidate(key: string): void; |
| 10 | +} |
| 11 | + |
| 12 | +export interface ResponseCacheOptions { |
| 13 | + /** How long a loaded value stays fresh. */ |
| 14 | + ttlSeconds: number; |
| 15 | + /** |
| 16 | + * Hard ceiling on stored entries. Required, not defaulted: these caches sit |
| 17 | + * in front of public endpoints and store misses, so the caller has to state |
| 18 | + * how much memory the endpoint is allowed to hold. |
| 19 | + */ |
| 20 | + maxKeys: number; |
| 21 | + /** Identifies the cache in logs. */ |
| 22 | + name: string; |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * A short-lived, in-process read cache for hot endpoints whose backing data |
| 27 | + * rarely changes. |
| 28 | + * |
| 29 | + * Two things happen here. Resolved values (including `null`, so misses are |
| 30 | + * cached too) are held for `ttlSeconds`, and concurrent loads of the same key |
| 31 | + * collapse into a single in-flight promise, so a burst of requests arriving on |
| 32 | + * a cold key costs one round trip instead of one per request. |
| 33 | + * |
| 34 | + * Rejections are never cached: the key is left empty and the next caller |
| 35 | + * retries. |
| 36 | + * |
| 37 | + * This lives in the process, not in Mongo or Redis. Every container holds its |
| 38 | + * own copy, so a write made elsewhere becomes visible only once the TTL lapses. |
| 39 | + * Only cache data where that staleness window is acceptable. |
| 40 | + * |
| 41 | + * Storage is capped at `maxKeys`. Callers are public endpoints that cache |
| 42 | + * misses, so a client walking valid-but-nonexistent keys would otherwise grow |
| 43 | + * the heap unchecked until the TTL swept it. At the cap we stop admitting new |
| 44 | + * keys and serve those loads straight from the loader, rather than evicting to |
| 45 | + * make room: refusing admission keeps the genuinely hot entries resident, while |
| 46 | + * LRU or FIFO eviction would let a flood of one-shot keys push them out. The |
| 47 | + * effect of a flood is that the cache stops helping for unseen keys, never that |
| 48 | + * the process runs out of memory. |
| 49 | + * |
| 50 | + * `useClones: false` means callers share the stored object. Treat anything |
| 51 | + * returned as read-only. |
| 52 | + */ |
| 53 | +export function createResponseCache<T>( |
| 54 | + opts: ResponseCacheOptions |
| 55 | +): ResponseCache<T> { |
| 56 | + const cache = new NodeCache({ |
| 57 | + stdTTL: opts.ttlSeconds, |
| 58 | + checkperiod: opts.ttlSeconds, |
| 59 | + useClones: false, |
| 60 | + maxKeys: opts.maxKeys, |
| 61 | + }); |
| 62 | + const inFlight = new Map<string, Promise<T>>(); |
| 63 | + |
| 64 | + // node-cache throws ECACHEFULL from `set` once maxKeys is reached. That is a |
| 65 | + // normal, self-healing state (the next checkperiod sweep frees slots), so it |
| 66 | + // must never fail the request. Log it at most once per TTL window: a flood |
| 67 | + // would otherwise emit a line per request, which is its own resource problem. |
| 68 | + let lastFullWarnAt = 0; |
| 69 | + |
| 70 | + const admit = (key: string, value: T) => { |
| 71 | + try { |
| 72 | + cache.set(key, value); |
| 73 | + } catch (err) { |
| 74 | + const now = Date.now(); |
| 75 | + if (now - lastFullWarnAt >= opts.ttlSeconds * 1000) { |
| 76 | + lastFullWarnAt = now; |
| 77 | + logger.warn( |
| 78 | + { err, cache: opts.name, maxKeys: opts.maxKeys, keys: cache.keys().length }, |
| 79 | + "Response cache is full; new keys are being served uncached" |
| 80 | + ); |
| 81 | + } |
| 82 | + } |
| 83 | + }; |
| 84 | + |
| 85 | + return { |
| 86 | + async getOrLoad(key: string, loader: () => Promise<T>): Promise<T> { |
| 87 | + // `has` rather than a truthiness check on `get`, so a cached `null` is a |
| 88 | + // hit instead of falling through to the loader on every request. |
| 89 | + if (cache.has(key)) { |
| 90 | + logger.debug({ cache: opts.name, key }, "Cache hit"); |
| 91 | + return cache.get<T>(key) as T; |
| 92 | + } |
| 93 | + |
| 94 | + const existing = inFlight.get(key); |
| 95 | + if (existing) { |
| 96 | + return existing; |
| 97 | + } |
| 98 | + |
| 99 | + const pending = (async () => { |
| 100 | + const value = await loader(); |
| 101 | + admit(key, value); |
| 102 | + return value; |
| 103 | + })(); |
| 104 | + |
| 105 | + inFlight.set(key, pending); |
| 106 | + |
| 107 | + try { |
| 108 | + return await pending; |
| 109 | + } finally { |
| 110 | + inFlight.delete(key); |
| 111 | + } |
| 112 | + }, |
| 113 | + |
| 114 | + invalidate(key: string) { |
| 115 | + cache.del(key); |
| 116 | + }, |
| 117 | + }; |
| 118 | +} |
0 commit comments