@blogmcp/content-cache 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,6 +37,26 @@ const { value, source } = await articles.get(key, async () => {
37
37
  // source ∈ fresh | stale | cold | lkg-memory | lkg-durable | negative | error
38
38
  ```
39
39
 
40
+ ### Options
41
+
42
+ | option | meaning |
43
+ |---|---|
44
+ | `freshMs` | serve from memory without revalidating for this long after a success |
45
+ | `staleMs` | up to this age, serve the memory copy at once and revalidate in the background |
46
+ | `negTtlMs` | after a failure with nothing cached, answer `negative` for this long instead of asking the origin again |
47
+ | `store` | the durable tier (`CacheStore`); omit it for a memory-only cache |
48
+ | `keyPrefix` | namespace for the durable keys, so several caches can share one store |
49
+ | `maxEntries` | upper bound on the memory tier (default unlimited): past it the least recently used keys are evicted, a fresh, stale or last-known-good hit counting as a use; the negative cache is bounded the same way and the durable store not at all. `cache.size` reports the entries in memory |
50
+ | `maxBytes` + `sizeOf` | upper bound on the summed weight of the memory tier (default unlimited), evicting like `maxEntries`; `sizeOf(value)` gives one value's weight. A value heavier than the whole bound is returned but not kept. `cache.bytes` reports the sum |
51
+ | `lkgMaxAgeMs` | the oldest a memory copy may be and still be served as last-known-good (default unlimited; at least `staleMs`); an older entry is dropped on its next read |
52
+ | `dropOnError` | `(error) => boolean`: errors that mean the origin answered and the value is gone (a page that now answers 404), not that it failed. Such a fetch drops the key from memory, the negative cache and the durable store (fenced by a purge like a write-back), its callers get `error` and never a last-known-good copy, and the key is not negative-cached |
53
+ | `exposeErrors` | put what the fetch threw on failed results (`result.error`, the same error for every caller that rode the fetch), so a fetcher can hand an answer it refused to cache to all of them. Default false: a result keeps its two fields |
54
+ | `now` | clock injection for tests (default `Date.now`) |
55
+
56
+ `purge`/`purgeAll` also detach the fetches in flight for the keys they drop, so the
57
+ next reader fetches anew instead of riding a fetch that began before the purge, and a
58
+ fetch that then fails does not bring the purged copy back as last-known-good.
59
+
40
60
  Degradation ladder on a KB failure: prior in-memory value → durable store copy →
41
61
  `null` (negative-cached). Successful fetches write through to both tiers; the
42
62
  durable write is fire-and-forget (never blocks or fails the request path).
@@ -64,11 +84,14 @@ All satisfy the same interface, so adopting one is a constructor swap.
64
84
 
65
85
  ## Bounds
66
86
 
67
- The in-memory tier has no size cap or idle eviction — expired negative entries are
68
- reclaimed opportunistically on access, but distinct keys accumulate. Use it with a
69
- **bounded key space** (the storefront keys by tier + immutable id/filename + locale,
70
- and by nav scope + locale — dozens of entries). Don't key by unbounded/attacker-
71
- controlled input; a `maxEntries` LRU is a future add if a consumer needs one.
87
+ Without `maxEntries` the in-memory tier has no size cap or idle eviction — expired
88
+ negative entries are reclaimed opportunistically on access, but distinct keys
89
+ accumulate. That is fine for a **bounded key space** (the storefront keys by tier +
90
+ immutable id/filename + locale, and by nav scope + locale — dozens of entries). A
91
+ cache keyed by anything a visitor controls (a URL, a query string, a header) must set
92
+ `maxEntries`, and `maxBytes` when its values vary in size: the Nuxt managed blog's
93
+ page cache sets both (`server/utils/pageCache.ts`), so a crawler walking every query
94
+ variant evicts old pages instead of growing the process.
72
95
 
73
96
  ## Build / publish
74
97
 
@@ -13,8 +13,16 @@ export type SwrSource = 'fresh' | 'stale' | 'cold' | 'lkg-memory' | 'lkg-durable
13
13
  export interface SwrResult<T> {
14
14
  value: T | null;
15
15
  source: SwrSource;
16
+ /**
17
+ * With `exposeErrors`: what the fetch threw, for `lkg-memory`, `lkg-durable`
18
+ * and `error` results that came from a failed fetch (absent otherwise,
19
+ * `negative` included). Every caller that rode the same fetch gets the same
20
+ * error, so a fetcher can hand its callers an answer it refused to cache by
21
+ * throwing it.
22
+ */
23
+ error?: unknown;
16
24
  }
17
- export interface SwrCacheOptions {
25
+ export interface SwrCacheOptions<T = unknown> {
18
26
  /**
19
27
  * Durable backing tier — the last-known-good floor that survives a process
20
28
  * restart. OMIT for an in-memory-only cache (e.g. gated/member content that
@@ -31,6 +39,50 @@ export interface SwrCacheOptions {
31
39
  keyPrefix?: string;
32
40
  /** Clock injection point (defaults to `Date.now`) — for deterministic tests. */
33
41
  now?: () => number;
42
+ /**
43
+ * Upper bound on the in-memory tier (default: unlimited). When a write-back
44
+ * would leave more than this many entries in memory, the least recently used
45
+ * ones are evicted: a memory hit (fresh or stale) counts as a use, so a key
46
+ * readers keep asking for stays while one-off keys fall out. The negative
47
+ * cache is bounded the same way. The durable store is never touched by the
48
+ * bound — an evicted key is still its last-known-good floor. Set it whenever
49
+ * the key space is open-ended (a page cache keyed by URL and query).
50
+ */
51
+ maxEntries?: number;
52
+ /**
53
+ * Upper bound on the summed {@link SwrCacheOptions.sizeOf} of the in-memory
54
+ * tier (default: unlimited; requires `sizeOf`). Evicts least recently used keys
55
+ * like `maxEntries`, which counts entries whatever their size: set this one when
56
+ * values vary widely in size (rendered pages). A single value larger than the
57
+ * whole bound is returned to its callers but not kept in memory (and the key's
58
+ * older memory entry is dropped, so it is not served in its place).
59
+ */
60
+ maxBytes?: number;
61
+ /** The weight of one value for `maxBytes`, in whatever unit `maxBytes` uses (an estimate of bytes held). */
62
+ sizeOf?: (value: T) => number;
63
+ /**
64
+ * The oldest a memory entry may be and still be served at all (default:
65
+ * unlimited). Past `staleMs` an entry is only ever served as `lkg-memory`
66
+ * (the origin failed); without this bound such a copy can be any age. With it,
67
+ * an entry older than this is dropped on its next read and the origin's
68
+ * failure is reported as such. Must be at least `staleMs`.
69
+ */
70
+ lkgMaxAgeMs?: number;
71
+ /**
72
+ * Errors that mean "the origin answered, and the value is gone" rather than
73
+ * "the origin failed" (a page that now answers 404). A fetch that throws one
74
+ * drops the key from memory, from the negative cache and from the durable
75
+ * store, and its callers get `error` (never a last-known-good copy) — also
76
+ * when the fetch was the background revalidation of a stale copy. The drop is
77
+ * fenced like a write-back: a fetch that started before a purge drops nothing.
78
+ * The key is not negative-cached, since the origin did not fail.
79
+ */
80
+ dropOnError?: (error: unknown) => boolean;
81
+ /**
82
+ * Put the fetch's error on failed results (`SwrResult.error`; default false,
83
+ * so a result keeps its two fields for callers that compare it whole).
84
+ */
85
+ exposeErrors?: boolean;
34
86
  }
35
87
  /**
36
88
  * Two-tier read-through cache: a per-process in-memory hot tier for latency, over
@@ -55,6 +107,13 @@ export declare class SwrCache<T = unknown> {
55
107
  private readonly negTtlMs;
56
108
  private readonly keyPrefix;
57
109
  private readonly now;
110
+ private readonly maxEntries;
111
+ private readonly maxBytes;
112
+ private readonly sizeOf?;
113
+ private readonly lkgMaxAgeMs;
114
+ private readonly dropOnError?;
115
+ private readonly exposeErrors;
116
+ private memBytes;
58
117
  private readonly mem;
59
118
  private readonly neg;
60
119
  private readonly inflight;
@@ -66,7 +125,29 @@ export declare class SwrCache<T = unknown> {
66
125
  * (possibly stale, possibly coalesced) fetch. Fences the "lost purge" race.
67
126
  */
68
127
  private generation;
69
- constructor(opts: SwrCacheOptions);
128
+ constructor(opts: SwrCacheOptions<T>);
129
+ /** Entries in the in-memory tier (positive values only; the negative cache is not counted). */
130
+ get size(): number;
131
+ /** The summed `sizeOf` of the in-memory tier (0 without `sizeOf`). */
132
+ get bytes(): number;
133
+ /**
134
+ * Mark `key` most recently used. A `Map` iterates in insertion order, so
135
+ * re-inserting moves the key to the end and the first key is always the
136
+ * least recently used one.
137
+ */
138
+ private touch;
139
+ /** Remove `key` from the memory tier, keeping the byte count right. */
140
+ private dropMem;
141
+ /** Empty the memory tier. */
142
+ private clearMem;
143
+ /**
144
+ * Write `value` to memory as the most recent key, then drop the oldest beyond
145
+ * the bounds. A value heavier than the whole byte bound is not kept, and the
146
+ * key's previous entry goes with it (it would otherwise be served in its place).
147
+ */
148
+ private remember;
149
+ /** Record a failure for `key`, bounded like the memory tier. */
150
+ private rememberFailure;
70
151
  private durableKey;
71
152
  /**
72
153
  * Coalesce concurrent fetches for the same key onto one in-flight promise, and
@@ -77,6 +158,9 @@ export declare class SwrCache<T = unknown> {
77
158
  * is returned to callers but NOT cached.
78
159
  */
79
160
  private runFetch;
161
+ private isDrop;
162
+ /** A failed result, with the fetch's error when `exposeErrors` asks for it. */
163
+ private failed;
80
164
  /** Persist to the durable tier without ever blocking/failing the request path. */
81
165
  private writeThrough;
82
166
  /**
@@ -86,10 +170,27 @@ export declare class SwrCache<T = unknown> {
86
170
  * is nothing cached in either tier.
87
171
  */
88
172
  get(key: string, fetcher: () => Promise<T>): Promise<SwrResult<T>>;
89
- /** Immediately evict one key from memory AND the durable store. */
173
+ /**
174
+ * Immediately evict one key from memory AND the durable store. A fetch of it
175
+ * still in flight is fenced (its result is not cached) and detached, so the
176
+ * next reader fetches anew instead of riding a pre-purge fetch.
177
+ */
90
178
  purge(key: string): Promise<void>;
91
- /** Evict every key (or those starting with `prefix`) from memory AND durable. */
179
+ /** Evict every key (or those starting with `prefix`) from memory AND durable; in-flight fetches as `purge`. */
92
180
  purgeAll(prefix?: string): Promise<void>;
181
+ /**
182
+ * Make every key (or those starting with `prefix`) due for a fetch on its next read, WITHOUT
183
+ * giving up what is held: the memory copy stays as last-known-good and the durable store is not
184
+ * touched. The next reader fetches; if the origin fails, it is served the copy it would have
185
+ * been served before, instead of nothing.
186
+ *
187
+ * This is the purge for "the content changed": `purge`/`purgeAll` also delete the durable copy,
188
+ * which is right for "this must no longer be served" and wrong for a routine publish — a purge
189
+ * that arrives while the origin is down would otherwise take the site's offline floor with it.
190
+ * In-flight fetches are fenced and detached as in `purge` (a fetch that started before the
191
+ * change must not be cached as fresh), and the negative cache is cleared.
192
+ */
193
+ expireAll(prefix?: string): void;
93
194
  /** Test-only: clear the in-memory tiers (leaves the durable store intact). */
94
195
  resetMemory(): void;
95
196
  }
package/dist/swr-cache.js CHANGED
@@ -1,10 +1,17 @@
1
- class o {
1
+ class u {
2
2
  store;
3
3
  freshMs;
4
4
  staleMs;
5
5
  negTtlMs;
6
6
  keyPrefix;
7
7
  now;
8
+ maxEntries;
9
+ maxBytes;
10
+ sizeOf;
11
+ lkgMaxAgeMs;
12
+ dropOnError;
13
+ exposeErrors;
14
+ memBytes = 0;
8
15
  mem = /* @__PURE__ */ new Map();
9
16
  neg = /* @__PURE__ */ new Map();
10
17
  inflight = /* @__PURE__ */ new Map();
@@ -16,11 +23,68 @@ class o {
16
23
  * (possibly stale, possibly coalesced) fetch. Fences the "lost purge" race.
17
24
  */
18
25
  generation = 0;
19
- constructor(t) {
20
- this.store = t.store, this.freshMs = t.freshMs, this.staleMs = t.staleMs, this.negTtlMs = t.negTtlMs, this.keyPrefix = t.keyPrefix ?? "", this.now = t.now ?? (() => Date.now());
26
+ constructor(e) {
27
+ this.store = e.store, this.freshMs = e.freshMs, this.staleMs = e.staleMs, this.negTtlMs = e.negTtlMs, this.keyPrefix = e.keyPrefix ?? "", this.now = e.now ?? (() => Date.now());
28
+ const t = e.maxEntries;
29
+ if (t !== void 0 && (!Number.isInteger(t) || t < 1))
30
+ throw new RangeError(`SwrCache: maxEntries must be a positive integer, got ${t}`);
31
+ this.maxEntries = t ?? Number.POSITIVE_INFINITY;
32
+ const s = e.maxBytes;
33
+ if (s !== void 0 && (!Number.isFinite(s) || s <= 0))
34
+ throw new RangeError(`SwrCache: maxBytes must be a positive number, got ${s}`);
35
+ if (s !== void 0 && !e.sizeOf)
36
+ throw new RangeError("SwrCache: maxBytes needs sizeOf");
37
+ this.maxBytes = s ?? Number.POSITIVE_INFINITY, this.sizeOf = e.sizeOf;
38
+ const r = e.lkgMaxAgeMs;
39
+ if (r !== void 0 && (!Number.isFinite(r) || r < e.staleMs))
40
+ throw new RangeError(`SwrCache: lkgMaxAgeMs must be a number of at least staleMs (${e.staleMs}), got ${r}`);
41
+ this.lkgMaxAgeMs = r ?? Number.POSITIVE_INFINITY, this.dropOnError = e.dropOnError, this.exposeErrors = e.exposeErrors === !0;
21
42
  }
22
- durableKey(t) {
23
- return this.keyPrefix ? `${this.keyPrefix}${t}` : t;
43
+ /** Entries in the in-memory tier (positive values only; the negative cache is not counted). */
44
+ get size() {
45
+ return this.mem.size;
46
+ }
47
+ /** The summed `sizeOf` of the in-memory tier (0 without `sizeOf`). */
48
+ get bytes() {
49
+ return this.memBytes;
50
+ }
51
+ /**
52
+ * Mark `key` most recently used. A `Map` iterates in insertion order, so
53
+ * re-inserting moves the key to the end and the first key is always the
54
+ * least recently used one.
55
+ */
56
+ touch(e, t) {
57
+ this.mem.delete(e), this.mem.set(e, t);
58
+ }
59
+ /** Remove `key` from the memory tier, keeping the byte count right. */
60
+ dropMem(e) {
61
+ const t = this.mem.get(e);
62
+ t && (this.mem.delete(e), this.memBytes -= t.bytes);
63
+ }
64
+ /** Empty the memory tier. */
65
+ clearMem() {
66
+ this.mem.clear(), this.memBytes = 0;
67
+ }
68
+ /**
69
+ * Write `value` to memory as the most recent key, then drop the oldest beyond
70
+ * the bounds. A value heavier than the whole byte bound is not kept, and the
71
+ * key's previous entry goes with it (it would otherwise be served in its place).
72
+ */
73
+ remember(e, t, s) {
74
+ const r = this.sizeOf ? this.sizeOf(t) : 0;
75
+ if (this.dropMem(e), !(r > this.maxBytes))
76
+ for (this.mem.set(e, { value: t, at: s, bytes: r }), this.memBytes += r; this.mem.size > this.maxEntries || this.memBytes > this.maxBytes; ) {
77
+ const i = this.mem.keys().next();
78
+ if (i.done) return;
79
+ this.dropMem(i.value);
80
+ }
81
+ }
82
+ /** Record a failure for `key`, bounded like the memory tier. */
83
+ rememberFailure(e, t) {
84
+ this.neg.delete(e), this.neg.set(e, t), f(this.neg, this.maxEntries);
85
+ }
86
+ durableKey(e) {
87
+ return this.keyPrefix ? `${this.keyPrefix}${e}` : e;
24
88
  }
25
89
  /**
26
90
  * Coalesce concurrent fetches for the same key onto one in-flight promise, and
@@ -30,24 +94,35 @@ class o {
30
94
  * FETCH-START: if a purge bumped it while the fetch was outstanding, the result
31
95
  * is returned to callers but NOT cached.
32
96
  */
33
- runFetch(t, e) {
34
- const i = this.inflight.get(t);
35
- if (i) return i;
36
- const n = this.generation, s = (async () => {
97
+ runFetch(e, t) {
98
+ const s = this.inflight.get(e);
99
+ if (s) return s;
100
+ const r = this.generation;
101
+ let i;
102
+ return i = (async () => {
37
103
  try {
38
- const r = await e();
39
- return this.generation === n && (this.mem.set(t, { value: r, at: this.now() }), this.writeThrough(t, r), this.neg.delete(t)), r;
104
+ const h = await t();
105
+ return this.generation === r && (this.remember(e, h, this.now()), this.writeThrough(e, h), this.neg.delete(e)), h;
106
+ } catch (h) {
107
+ throw this.isDrop(h) && this.generation === r && (this.dropMem(e), this.neg.delete(e), this.store && this.store.delete(this.durableKey(e)).catch(() => {
108
+ })), h;
40
109
  } finally {
41
- this.inflight.delete(t);
110
+ this.inflight.get(e) === i && this.inflight.delete(e);
42
111
  }
43
- })();
44
- return this.inflight.set(t, s), s;
112
+ })(), this.inflight.set(e, i), i;
113
+ }
114
+ isDrop(e) {
115
+ return this.dropOnError?.(e) === !0;
116
+ }
117
+ /** A failed result, with the fetch's error when `exposeErrors` asks for it. */
118
+ failed(e, t, s) {
119
+ return this.exposeErrors ? { value: e, source: t, error: s } : { value: e, source: t };
45
120
  }
46
121
  /** Persist to the durable tier without ever blocking/failing the request path. */
47
- writeThrough(t, e) {
122
+ writeThrough(e, t) {
48
123
  if (!this.store) return;
49
- const i = { value: e, storedAt: this.now() };
50
- this.store.set(this.durableKey(t), i).catch(() => {
124
+ const s = { value: t, storedAt: this.now() };
125
+ this.store.set(this.durableKey(e), s).catch(() => {
51
126
  });
52
127
  }
53
128
  /**
@@ -56,51 +131,86 @@ class o {
56
131
  * value is cached. Returns `{ value: null }` only when the origin fails and there
57
132
  * is nothing cached in either tier.
58
133
  */
59
- async get(t, e) {
60
- const i = this.generation, n = this.now(), s = this.mem.get(t);
61
- if (s && n - s.at < this.freshMs)
62
- return { value: s.value, source: "fresh" };
63
- const r = this.neg.get(t);
64
- if (!s && r !== void 0) {
65
- if (n - r < this.negTtlMs) return { value: null, source: "negative" };
66
- this.neg.delete(t);
134
+ async get(e, t) {
135
+ const s = this.generation, r = this.now();
136
+ let i = this.mem.get(e);
137
+ if (i && r - i.at >= this.lkgMaxAgeMs && (this.dropMem(e), i = void 0), i && r - i.at < this.freshMs)
138
+ return this.touch(e, i), { value: i.value, source: "fresh" };
139
+ const h = this.neg.get(e);
140
+ if (!i && h !== void 0) {
141
+ if (r - h < this.negTtlMs) return { value: null, source: "negative" };
142
+ this.neg.delete(e);
67
143
  }
68
- if (s && n - s.at < this.staleMs)
69
- return this.runFetch(t, e).catch(() => {
70
- }), { value: s.value, source: "stale" };
144
+ if (i && r - i.at < this.staleMs)
145
+ return this.touch(e, i), this.runFetch(e, t).catch(() => {
146
+ }), { value: i.value, source: "stale" };
71
147
  try {
72
- return { value: await this.runFetch(t, e), source: "cold" };
73
- } catch {
74
- if (s)
75
- return { value: s.value, source: "lkg-memory" };
148
+ return { value: await this.runFetch(e, t), source: "cold" };
149
+ } catch (n) {
150
+ if (this.isDrop(n)) return this.failed(null, "error", n);
151
+ const a = this.mem.get(e), l = a ?? (this.generation === s ? i : void 0);
152
+ if (l && this.now() - l.at < this.lkgMaxAgeMs)
153
+ return a && this.touch(e, a), this.failed(l.value, "lkg-memory", n);
76
154
  if (this.store) {
77
- const h = await this.store.get(this.durableKey(t)).catch(() => null);
78
- if (h) {
79
- const a = h.value;
80
- return this.generation === i && this.mem.set(t, { value: a, at: h.storedAt }), { value: a, source: "lkg-durable" };
155
+ const m = await this.store.get(this.durableKey(e)).catch(() => null);
156
+ if (m) {
157
+ const g = m.value;
158
+ return this.generation === s && this.remember(e, g, m.storedAt), this.failed(g, "lkg-durable", n);
81
159
  }
82
160
  }
83
- return this.generation === i && this.neg.set(t, this.now()), { value: null, source: "error" };
161
+ return this.generation === s && this.rememberFailure(e, this.now()), this.failed(null, "error", n);
84
162
  }
85
163
  }
86
- /** Immediately evict one key from memory AND the durable store. */
87
- async purge(t) {
88
- this.generation++, this.mem.delete(t), this.neg.delete(t), this.store && await this.store.delete(this.durableKey(t));
164
+ /**
165
+ * Immediately evict one key from memory AND the durable store. A fetch of it
166
+ * still in flight is fenced (its result is not cached) and detached, so the
167
+ * next reader fetches anew instead of riding a pre-purge fetch.
168
+ */
169
+ async purge(e) {
170
+ this.generation++, this.dropMem(e), this.neg.delete(e), this.inflight.delete(e), this.store && await this.store.delete(this.durableKey(e));
89
171
  }
90
- /** Evict every key (or those starting with `prefix`) from memory AND durable. */
91
- async purgeAll(t) {
92
- if (this.generation++, t) {
93
- for (const e of [...this.mem.keys()]) e.startsWith(t) && this.mem.delete(e);
94
- for (const e of [...this.neg.keys()]) e.startsWith(t) && this.neg.delete(e);
95
- this.store && await this.store.clear(this.durableKey(t));
172
+ /** Evict every key (or those starting with `prefix`) from memory AND durable; in-flight fetches as `purge`. */
173
+ async purgeAll(e) {
174
+ if (this.generation++, e) {
175
+ for (const t of [...this.mem.keys()]) t.startsWith(e) && this.dropMem(t);
176
+ for (const t of [...this.neg.keys()]) t.startsWith(e) && this.neg.delete(t);
177
+ for (const t of [...this.inflight.keys()]) t.startsWith(e) && this.inflight.delete(t);
178
+ this.store && await this.store.clear(this.durableKey(e));
96
179
  } else
97
- this.mem.clear(), this.neg.clear(), this.store && await this.store.clear();
180
+ this.clearMem(), this.neg.clear(), this.inflight.clear(), this.store && await this.store.clear();
181
+ }
182
+ /**
183
+ * Make every key (or those starting with `prefix`) due for a fetch on its next read, WITHOUT
184
+ * giving up what is held: the memory copy stays as last-known-good and the durable store is not
185
+ * touched. The next reader fetches; if the origin fails, it is served the copy it would have
186
+ * been served before, instead of nothing.
187
+ *
188
+ * This is the purge for "the content changed": `purge`/`purgeAll` also delete the durable copy,
189
+ * which is right for "this must no longer be served" and wrong for a routine publish — a purge
190
+ * that arrives while the origin is down would otherwise take the site's offline floor with it.
191
+ * In-flight fetches are fenced and detached as in `purge` (a fetch that started before the
192
+ * change must not be cached as fresh), and the negative cache is cleared.
193
+ */
194
+ expireAll(e) {
195
+ this.generation++;
196
+ const t = this.now() - this.staleMs;
197
+ for (const [s, r] of this.mem)
198
+ e && !s.startsWith(e) || r.at > t && (r.at = t);
199
+ for (const s of [...this.neg.keys()]) (!e || s.startsWith(e)) && this.neg.delete(s);
200
+ for (const s of [...this.inflight.keys()]) (!e || s.startsWith(e)) && this.inflight.delete(s);
98
201
  }
99
202
  /** Test-only: clear the in-memory tiers (leaves the durable store intact). */
100
203
  resetMemory() {
101
- this.mem.clear(), this.neg.clear(), this.inflight.clear();
204
+ this.clearMem(), this.neg.clear(), this.inflight.clear();
205
+ }
206
+ }
207
+ function f(o, e) {
208
+ for (; o.size > e; ) {
209
+ const t = o.keys().next();
210
+ if (t.done) return;
211
+ o.delete(t.value);
102
212
  }
103
213
  }
104
214
  export {
105
- o as SwrCache
215
+ u as SwrCache
106
216
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/content-cache",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Server-only durable content cache for blogmcp presentation layers: pluggable storage adapters (filesystem now; S3/Postgres later) behind an SWR + last-known-good read-through.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -238,3 +238,433 @@ describe('SwrCache', () => {
238
238
  expect(await store.keys()).toEqual([]);
239
239
  });
240
240
  });
241
+
242
+ describe('SwrCache maxEntries (the LRU bound on the memory tier)', () => {
243
+ const ok = (v: string) => async () => v;
244
+ const down = async (): Promise<string> => {
245
+ throw new Error('down');
246
+ };
247
+
248
+ it('is unlimited by default', async () => {
249
+ const cache = new SwrCache<string>({ ...TTL });
250
+ for (let i = 0; i < 50; i++) await cache.get(`k${i}`, ok(`v${i}`));
251
+ expect(cache.size).toBe(50);
252
+ });
253
+
254
+ it('refuses a bound that is not a positive integer', () => {
255
+ for (const maxEntries of [0, -1, 1.5, Number.NaN]) {
256
+ expect(() => new SwrCache<string>({ ...TTL, maxEntries })).toThrow(RangeError);
257
+ }
258
+ });
259
+
260
+ it('evicts the oldest keys first once a write-back passes the bound', async () => {
261
+ const cache = new SwrCache<string>({ ...TTL, maxEntries: 2 });
262
+ await cache.get('a', ok('A'));
263
+ await cache.get('b', ok('B'));
264
+ expect(cache.size).toBe(2);
265
+ await cache.get('c', ok('C')); // a is the least recently used → out
266
+ expect(cache.size).toBe(2);
267
+ const refetch = vi.fn(ok('A2'));
268
+ expect(await cache.get('a', refetch)).toEqual({ value: 'A2', source: 'cold' });
269
+ expect(refetch).toHaveBeenCalledTimes(1);
270
+ // That write-back evicted b (now the oldest); c is still served from memory.
271
+ const cFetcher = vi.fn(ok('never'));
272
+ expect(await cache.get('c', cFetcher)).toEqual({ value: 'C', source: 'fresh' });
273
+ expect(cFetcher).not.toHaveBeenCalled();
274
+ expect((await cache.get('b', ok('B2'))).source).toBe('cold');
275
+ });
276
+
277
+ it('a fresh hit refreshes recency', async () => {
278
+ const cache = new SwrCache<string>({ ...TTL, maxEntries: 2 });
279
+ await cache.get('a', ok('A'));
280
+ await cache.get('b', ok('B'));
281
+ expect((await cache.get('a', ok('x'))).source).toBe('fresh'); // a is now the most recent
282
+ await cache.get('c', ok('C')); // so b goes, not a
283
+ expect(await cache.get('a', ok('x'))).toEqual({ value: 'A', source: 'fresh' });
284
+ expect((await cache.get('b', ok('B2'))).source).toBe('cold');
285
+ });
286
+
287
+ it('a stale hit refreshes recency too', async () => {
288
+ const clock = makeClock();
289
+ const cache = new SwrCache<string>({ ...TTL, maxEntries: 2, now: clock.now });
290
+ await cache.get('a', ok('A'));
291
+ await cache.get('b', ok('B'));
292
+ clock.advance(200); // both stale
293
+ // The background revalidation of a never settles here, so only the hit itself can re-rank a.
294
+ const pending = new Promise<string>(() => {});
295
+ expect(await cache.get('a', () => pending)).toEqual({ value: 'A', source: 'stale' });
296
+ await cache.get('c', ok('C')); // b is the least recently used now
297
+ expect((await cache.get('a', ok('x'))).source).toBe('stale');
298
+ expect((await cache.get('b', ok('B2'))).source).toBe('cold');
299
+ });
300
+
301
+ it('bounds the negative cache the same way', async () => {
302
+ const cache = new SwrCache<string>({ ...TTL, maxEntries: 2 });
303
+ for (const k of ['a', 'b', 'c']) expect((await cache.get(k, down)).source).toBe('error');
304
+ // a fell out of the negative cache, so it is asked again; c is still short-circuited.
305
+ const again = vi.fn(down);
306
+ expect((await cache.get('a', again)).source).toBe('error');
307
+ expect(again).toHaveBeenCalledTimes(1);
308
+ expect((await cache.get('c', down)).source).toBe('negative');
309
+ expect(cache.size).toBe(0); // failures are not memory entries
310
+ });
311
+
312
+ it('leaves the durable store untouched: an evicted key is still its last-known-good floor', async () => {
313
+ const store = new MemoryStore();
314
+ const cache = new SwrCache<string>({ ...TTL, store, keyPrefix: 'p:', maxEntries: 1 });
315
+ await cache.get('a', ok('A'));
316
+ await cache.get('b', ok('B')); // a evicted from memory
317
+ await flush();
318
+ expect((await store.keys()).sort()).toEqual(['p:a', 'p:b']);
319
+ expect(cache.size).toBe(1);
320
+ expect(await cache.get('a', down)).toEqual({ value: 'A', source: 'lkg-durable' });
321
+ expect(cache.size).toBe(1); // the hydration obeys the bound as well
322
+ });
323
+
324
+ it('size counts memory entries and purge resets it', async () => {
325
+ const cache = new SwrCache<string>({ ...TTL, maxEntries: 10 });
326
+ await cache.get('x:1', ok('1'));
327
+ await cache.get('x:2', ok('2'));
328
+ await cache.get('y:1', ok('3'));
329
+ expect(cache.size).toBe(3);
330
+ await cache.purge('y:1');
331
+ expect(cache.size).toBe(2);
332
+ await cache.purgeAll('x:');
333
+ expect(cache.size).toBe(0);
334
+ await cache.get('z', ok('4'));
335
+ await cache.purgeAll();
336
+ expect(cache.size).toBe(0);
337
+ });
338
+ });
339
+
340
+ describe('SwrCache maxBytes (the weight bound on the memory tier)', () => {
341
+ const ok = (v: string) => async () => v;
342
+ const byLength = { sizeOf: (v: string) => v.length };
343
+
344
+ it('refuses a bound that is not a positive number, or one without sizeOf', () => {
345
+ for (const maxBytes of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
346
+ expect(() => new SwrCache<string>({ ...TTL, ...byLength, maxBytes })).toThrow(RangeError);
347
+ }
348
+ expect(() => new SwrCache<string>({ ...TTL, maxBytes: 10 })).toThrow(RangeError);
349
+ });
350
+
351
+ it('evicts the least recently used keys until the summed weight fits, and reports it', async () => {
352
+ const cache = new SwrCache<string>({ ...TTL, ...byLength, maxBytes: 10 });
353
+ await cache.get('a', ok('aaaa')); // 4
354
+ await cache.get('b', ok('bbbb')); // 8
355
+ expect(cache.bytes).toBe(8);
356
+ await cache.get('a', ok('x')); // fresh hit: a is the most recent now
357
+ await cache.get('c', ok('ccc')); // 11 > 10 → b (the oldest) goes
358
+ expect(cache.size).toBe(2);
359
+ expect(cache.bytes).toBe(7);
360
+ expect((await cache.get('a', ok('x'))).source).toBe('fresh');
361
+ expect((await cache.get('b', ok('bbbb'))).source).toBe('cold');
362
+ });
363
+
364
+ it('keeps the count right when a key is replaced by a revalidation', async () => {
365
+ const clock = makeClock();
366
+ const cache = new SwrCache<string>({ ...TTL, ...byLength, maxBytes: 100, now: clock.now });
367
+ await cache.get('a', ok('aaaa'));
368
+ clock.advance(200);
369
+ await cache.get('a', ok('aa')); // stale; the background fetch replaces the value
370
+ await flush();
371
+ expect(cache.bytes).toBe(2);
372
+ expect(await cache.get('a', ok('never'))).toEqual({ value: 'aa', source: 'fresh' });
373
+ });
374
+
375
+ it('a value heavier than the whole bound is served but not kept, and its older copy is dropped', async () => {
376
+ const clock = makeClock();
377
+ const cache = new SwrCache<string>({ ...TTL, ...byLength, maxBytes: 5, now: clock.now });
378
+ await cache.get('a', ok('aaa'));
379
+ await cache.get('b', ok('bb'));
380
+ clock.advance(200);
381
+ expect(await cache.get('a', ok('a-very-long-value'))).toEqual({ value: 'aaa', source: 'stale' });
382
+ await flush();
383
+ expect(cache.size).toBe(1); // b only: the old a went with the oversized revalidation
384
+ expect(cache.bytes).toBe(2);
385
+ expect(await cache.get('a', ok('a-very-long-value'))).toEqual({ value: 'a-very-long-value', source: 'cold' });
386
+ expect(cache.size).toBe(1);
387
+ });
388
+
389
+ it('purge, purgeAll and a dropping fetch subtract what they drop', async () => {
390
+ const clock = makeClock();
391
+ const gone = new Error('gone');
392
+ const cache = new SwrCache<string>({ ...TTL, ...byLength, maxBytes: 100, now: clock.now, dropOnError: (e) => e === gone });
393
+ await cache.get('x:1', ok('1111'));
394
+ await cache.get('x:2', ok('22'));
395
+ await cache.get('y:1', ok('3'));
396
+ clock.advance(2_000); // past stale: x:2's next read waits for the origin
397
+ await cache.get('x:2', async () => {
398
+ throw gone;
399
+ });
400
+ expect(cache.bytes).toBe(5);
401
+ await cache.purge('y:1');
402
+ expect(cache.bytes).toBe(4);
403
+ await cache.purgeAll('x:');
404
+ expect(cache.bytes).toBe(0);
405
+ });
406
+ });
407
+
408
+ describe('SwrCache lkgMaxAgeMs (the age bound on last-known-good)', () => {
409
+ const down = async (): Promise<string> => {
410
+ throw new Error('down');
411
+ };
412
+
413
+ it('refuses a bound below staleMs', () => {
414
+ expect(() => new SwrCache<string>({ ...TTL, lkgMaxAgeMs: 999 })).toThrow(RangeError);
415
+ expect(() => new SwrCache<string>({ ...TTL, lkgMaxAgeMs: 1_000 })).not.toThrow();
416
+ });
417
+
418
+ it('serves a copy past staleMs as lkg-memory only while it is younger than the bound', async () => {
419
+ const clock = makeClock();
420
+ const cache = new SwrCache<string>({ ...TTL, lkgMaxAgeMs: 5_000, now: clock.now });
421
+ await cache.get('k', async () => 'v1');
422
+ clock.advance(2_000);
423
+ expect(await cache.get('k', down)).toEqual({ value: 'v1', source: 'lkg-memory' });
424
+ clock.advance(3_000); // 5 000 ms old: too old to be served at all
425
+ expect(await cache.get('k', down)).toEqual({ value: null, source: 'error' });
426
+ expect(cache.size).toBe(0);
427
+ });
428
+
429
+ it('without the bound a copy of any age is last-known-good (the default, unchanged)', async () => {
430
+ const clock = makeClock();
431
+ const cache = new SwrCache<string>({ ...TTL, now: clock.now });
432
+ await cache.get('k', async () => 'v1');
433
+ clock.advance(10_000_000);
434
+ expect(await cache.get('k', down)).toEqual({ value: 'v1', source: 'lkg-memory' });
435
+ });
436
+ });
437
+
438
+ describe('SwrCache dropOnError (the origin says the value is gone)', () => {
439
+ const gone = new Error('404');
440
+ const isGone = (e: unknown) => e === gone;
441
+ const answersGone = async (): Promise<string> => {
442
+ throw gone;
443
+ };
444
+
445
+ it('drops the key: no last-known-good copy, no negative entry, the next read asks the origin again', async () => {
446
+ const clock = makeClock();
447
+ const cache = new SwrCache<string>({ ...TTL, now: clock.now, dropOnError: isGone });
448
+ await cache.get('k', async () => 'v1');
449
+ clock.advance(2_000); // past stale
450
+ expect(await cache.get('k', answersGone)).toEqual({ value: null, source: 'error' });
451
+ expect(cache.size).toBe(0);
452
+ const next = vi.fn(async () => 'v2');
453
+ expect(await cache.get('k', next)).toEqual({ value: 'v2', source: 'cold' }); // not `negative`
454
+ expect(next).toHaveBeenCalledTimes(1);
455
+ });
456
+
457
+ it('any other error still falls back to the last-known-good copy', async () => {
458
+ const clock = makeClock();
459
+ const cache = new SwrCache<string>({ ...TTL, now: clock.now, dropOnError: isGone });
460
+ await cache.get('k', async () => 'v1');
461
+ clock.advance(2_000);
462
+ expect(await cache.get('k', async () => Promise.reject(new Error('down')))).toEqual({ value: 'v1', source: 'lkg-memory' });
463
+ expect(cache.size).toBe(1);
464
+ });
465
+
466
+ it('the stale window’s background revalidation drops it too: the next read is cold', async () => {
467
+ const clock = makeClock();
468
+ const cache = new SwrCache<string>({ ...TTL, now: clock.now, dropOnError: isGone });
469
+ await cache.get('k', async () => 'v1');
470
+ clock.advance(200); // stale
471
+ expect(await cache.get('k', answersGone)).toEqual({ value: 'v1', source: 'stale' });
472
+ await flush();
473
+ expect(cache.size).toBe(0);
474
+ expect((await cache.get('k', async () => 'v2')).source).toBe('cold');
475
+ });
476
+
477
+ it('deletes the durable copy as well, so it cannot come back as lkg-durable', async () => {
478
+ const store = new MemoryStore();
479
+ const clock = makeClock();
480
+ const cache = new SwrCache<string>({ ...TTL, store, now: clock.now, dropOnError: isGone });
481
+ await cache.get('k', async () => 'v1');
482
+ await flush();
483
+ expect(store.map.size).toBe(1);
484
+ clock.advance(2_000);
485
+ await cache.get('k', answersGone);
486
+ await flush();
487
+ expect(store.map.size).toBe(0);
488
+ cache.resetMemory();
489
+ expect(await cache.get('k', async () => Promise.reject(new Error('down')))).toEqual({ value: null, source: 'error' });
490
+ });
491
+
492
+ it('every caller riding the dropping fetch gets the error, never the old copy (exposeErrors hands them the same error)', async () => {
493
+ const clock = makeClock();
494
+ const cache = new SwrCache<string>({ ...TTL, now: clock.now, dropOnError: isGone, exposeErrors: true });
495
+ await cache.get('k', async () => 'v1');
496
+ clock.advance(2_000); // past stale: the next reads wait for the origin
497
+ let fail!: () => void;
498
+ const leader = cache.get('k', () => new Promise<string>((_, reject) => (fail = () => reject(gone))));
499
+ const rider = cache.get('k', async () => 'never');
500
+ fail();
501
+ expect(await leader).toEqual({ value: null, source: 'error', error: gone });
502
+ expect(await rider).toEqual({ value: null, source: 'error', error: gone });
503
+ expect(cache.size).toBe(0);
504
+ });
505
+
506
+ it('is fenced by a purge: a fetch that began before it does not drop the copy stored after it', async () => {
507
+ const cache = new SwrCache<string>({ ...TTL, dropOnError: isGone });
508
+ let failOld!: () => void;
509
+ const old = cache.get('k', () => new Promise<string>((_, reject) => (failOld = () => reject(gone))));
510
+ await cache.purgeAll();
511
+ expect(await cache.get('k', async () => 'new')).toEqual({ value: 'new', source: 'cold' });
512
+ failOld();
513
+ expect((await old).source).toBe('error');
514
+ expect(await cache.get('k', async () => 'never')).toEqual({ value: 'new', source: 'fresh' });
515
+ });
516
+ });
517
+
518
+ describe('SwrCache failed results', () => {
519
+ it('carry the fetch’s error only with exposeErrors (two fields otherwise, as before)', async () => {
520
+ const down = new Error('down');
521
+ const plain = new SwrCache<string>({ ...TTL });
522
+ const r = await plain.get('k', async () => Promise.reject(down));
523
+ expect(Object.keys(r).sort()).toEqual(['source', 'value']);
524
+ const exposed = new SwrCache<string>({ ...TTL, exposeErrors: true });
525
+ expect(await exposed.get('k', async () => Promise.reject(down))).toEqual({ value: null, source: 'error', error: down });
526
+ expect(await exposed.get('k', async () => 'never')).toEqual({ value: null, source: 'negative' }); // no fetch, no error
527
+ });
528
+
529
+ it('a failed fetch serves what memory holds now: a copy stored meanwhile wins over the one read at the start', async () => {
530
+ const clock = makeClock();
531
+ const cache = new SwrCache<string>({ ...TTL, now: clock.now });
532
+ await cache.get('k', async () => 'v1');
533
+ clock.advance(2_000); // past stale
534
+ let failOld!: () => void;
535
+ const old = cache.get('k', () => new Promise<string>((_, reject) => (failOld = () => reject(new Error('down')))));
536
+ await cache.purgeAll(); // detaches the old fetch
537
+ expect(await cache.get('k', async () => 'v2')).toEqual({ value: 'v2', source: 'cold' });
538
+ failOld();
539
+ expect(await old).toEqual({ value: 'v2', source: 'lkg-memory' });
540
+ });
541
+
542
+ it('a purge while the fetch was out: the copy it evicted does not come back as last-known-good', async () => {
543
+ const clock = makeClock();
544
+ const cache = new SwrCache<string>({ ...TTL, now: clock.now });
545
+ await cache.get('k', async () => 'v1');
546
+ clock.advance(2_000);
547
+ let failOld!: () => void;
548
+ const old = cache.get('k', () => new Promise<string>((_, reject) => (failOld = () => reject(new Error('down')))));
549
+ await cache.purgeAll();
550
+ failOld();
551
+ expect(await old).toEqual({ value: null, source: 'error' });
552
+ });
553
+ });
554
+
555
+ describe('SwrCache in-flight fetches across a purge', () => {
556
+ it('a reader after a purge does not ride the fetch that started before it', async () => {
557
+ const cache = new SwrCache<string>({ ...TTL });
558
+ let releaseOld!: (v: string) => void;
559
+ const before = cache.get('k', () => new Promise<string>((r) => (releaseOld = r)));
560
+ await cache.purgeAll();
561
+ const fresh = vi.fn(async () => 'new');
562
+ expect(await cache.get('k', fresh)).toEqual({ value: 'new', source: 'cold' });
563
+ expect(fresh).toHaveBeenCalledTimes(1);
564
+ releaseOld('old');
565
+ expect(await before).toEqual({ value: 'old', source: 'cold' }); // its own caller still gets it…
566
+ expect(await cache.get('k', async () => 'never')).toEqual({ value: 'new', source: 'fresh' }); // …but it is not cached
567
+ });
568
+
569
+ it('a purged fetch settling later does not detach the fetch that replaced it', async () => {
570
+ const cache = new SwrCache<string>({ ...TTL });
571
+ let releaseOld!: (v: string) => void;
572
+ let releaseNew!: (v: string) => void;
573
+ const old = cache.get('k', () => new Promise<string>((r) => (releaseOld = r)));
574
+ await cache.purge('k');
575
+ const replacement = cache.get('k', () => new Promise<string>((r) => (releaseNew = r)));
576
+ releaseOld('old');
577
+ await old;
578
+ // A third reader still coalesces onto the replacement (the old fetch's `finally` left it in place).
579
+ const rider = vi.fn(async () => 'third');
580
+ const third = cache.get('k', rider);
581
+ releaseNew('new');
582
+ expect(await replacement).toEqual({ value: 'new', source: 'cold' });
583
+ expect(await third).toEqual({ value: 'new', source: 'cold' });
584
+ expect(rider).not.toHaveBeenCalled();
585
+ });
586
+ });
587
+
588
+ describe('expireAll', () => {
589
+ it('makes the next read fetch, and serves the new value', async () => {
590
+ const clock = makeClock();
591
+ const cache = new SwrCache<number>({ ...TTL, now: clock.now });
592
+ let n = 1;
593
+ const fetcher = vi.fn(async () => n);
594
+ await cache.get('k', fetcher);
595
+ n = 2;
596
+ cache.expireAll();
597
+ expect(await cache.get('k', fetcher)).toEqual({ value: 2, source: 'cold' });
598
+ expect(fetcher).toHaveBeenCalledTimes(2);
599
+ expect(await cache.get('k', fetcher)).toEqual({ value: 2, source: 'fresh' });
600
+ });
601
+
602
+ it('keeps the copy as last-known-good: an origin that fails after the expiry is served it', async () => {
603
+ const clock = makeClock();
604
+ const store = new MemoryStore();
605
+ const cache = new SwrCache<number>({ ...TTL, now: clock.now, store });
606
+ await cache.get('k', async () => 1);
607
+ await flush();
608
+ cache.expireAll();
609
+ const failing = vi.fn(async () => {
610
+ throw new Error('origin down');
611
+ });
612
+ expect(await cache.get('k', failing)).toMatchObject({ value: 1, source: 'lkg-memory' });
613
+ // The durable copy was not touched either: a new process still finds the floor.
614
+ expect(await store.keys()).toHaveLength(1);
615
+ const cold = new SwrCache<number>({ ...TTL, now: clock.now, store });
616
+ expect(await cold.get('k', failing)).toMatchObject({ value: 1, source: 'lkg-durable' });
617
+ });
618
+
619
+ it('purgeAll, for comparison, gives the floor up', async () => {
620
+ const clock = makeClock();
621
+ const store = new MemoryStore();
622
+ const cache = new SwrCache<number>({ ...TTL, now: clock.now, store });
623
+ await cache.get('k', async () => 1);
624
+ await flush();
625
+ await cache.purgeAll();
626
+ expect(await store.keys()).toHaveLength(0);
627
+ expect((await cache.get('k', async () => { throw new Error('origin down'); })).value).toBeNull();
628
+ });
629
+
630
+ it('expires only the keys under a prefix', async () => {
631
+ const clock = makeClock();
632
+ const cache = new SwrCache<number>({ ...TTL, now: clock.now });
633
+ const a = vi.fn(async () => 1);
634
+ const b = vi.fn(async () => 2);
635
+ await cache.get('nav:a', a);
636
+ await cache.get('page:b', b);
637
+ cache.expireAll('nav:');
638
+ expect((await cache.get('nav:a', a)).source).toBe('cold');
639
+ expect((await cache.get('page:b', b)).source).toBe('fresh');
640
+ });
641
+
642
+ it('never makes an old copy look newer, and forgets a remembered failure', async () => {
643
+ const clock = makeClock();
644
+ const cache = new SwrCache<number>({ ...TTL, now: clock.now, lkgMaxAgeMs: 5_000 });
645
+ await cache.get('old', async () => 1);
646
+ clock.advance(4_000); // older than staleMs, younger than lkgMaxAgeMs
647
+ cache.expireAll();
648
+ clock.advance(1_500); // 5 500 ms after it was stored: past lkgMaxAgeMs by its OWN age
649
+ expect((await cache.get('old', async () => { throw new Error('down'); })).value).toBeNull();
650
+
651
+ await cache.get('bad', async () => { throw new Error('down'); });
652
+ cache.expireAll();
653
+ const ok = vi.fn(async () => 7);
654
+ expect(await cache.get('bad', ok)).toEqual({ value: 7, source: 'cold' });
655
+ });
656
+
657
+ it('a fetch that started before the expiry is not cached as fresh', async () => {
658
+ const clock = makeClock();
659
+ const cache = new SwrCache<number>({ ...TTL, now: clock.now });
660
+ let release!: (v: number) => void;
661
+ const slow = vi.fn(() => new Promise<number>((resolve) => (release = resolve)));
662
+ const pending = cache.get('k', slow);
663
+ cache.expireAll();
664
+ release(1); // the pre-change answer
665
+ await pending;
666
+ await flush();
667
+ const fresh = vi.fn(async () => 2);
668
+ expect(await cache.get('k', fresh)).toEqual({ value: 2, source: 'cold' });
669
+ });
670
+ });
package/src/swr-cache.ts CHANGED
@@ -22,9 +22,17 @@ export type SwrSource =
22
22
  export interface SwrResult<T> {
23
23
  value: T | null;
24
24
  source: SwrSource;
25
+ /**
26
+ * With `exposeErrors`: what the fetch threw, for `lkg-memory`, `lkg-durable`
27
+ * and `error` results that came from a failed fetch (absent otherwise,
28
+ * `negative` included). Every caller that rode the same fetch gets the same
29
+ * error, so a fetcher can hand its callers an answer it refused to cache by
30
+ * throwing it.
31
+ */
32
+ error?: unknown;
25
33
  }
26
34
 
27
- export interface SwrCacheOptions {
35
+ export interface SwrCacheOptions<T = unknown> {
28
36
  /**
29
37
  * Durable backing tier — the last-known-good floor that survives a process
30
38
  * restart. OMIT for an in-memory-only cache (e.g. gated/member content that
@@ -41,11 +49,57 @@ export interface SwrCacheOptions {
41
49
  keyPrefix?: string;
42
50
  /** Clock injection point (defaults to `Date.now`) — for deterministic tests. */
43
51
  now?: () => number;
52
+ /**
53
+ * Upper bound on the in-memory tier (default: unlimited). When a write-back
54
+ * would leave more than this many entries in memory, the least recently used
55
+ * ones are evicted: a memory hit (fresh or stale) counts as a use, so a key
56
+ * readers keep asking for stays while one-off keys fall out. The negative
57
+ * cache is bounded the same way. The durable store is never touched by the
58
+ * bound — an evicted key is still its last-known-good floor. Set it whenever
59
+ * the key space is open-ended (a page cache keyed by URL and query).
60
+ */
61
+ maxEntries?: number;
62
+ /**
63
+ * Upper bound on the summed {@link SwrCacheOptions.sizeOf} of the in-memory
64
+ * tier (default: unlimited; requires `sizeOf`). Evicts least recently used keys
65
+ * like `maxEntries`, which counts entries whatever their size: set this one when
66
+ * values vary widely in size (rendered pages). A single value larger than the
67
+ * whole bound is returned to its callers but not kept in memory (and the key's
68
+ * older memory entry is dropped, so it is not served in its place).
69
+ */
70
+ maxBytes?: number;
71
+ /** The weight of one value for `maxBytes`, in whatever unit `maxBytes` uses (an estimate of bytes held). */
72
+ sizeOf?: (value: T) => number;
73
+ /**
74
+ * The oldest a memory entry may be and still be served at all (default:
75
+ * unlimited). Past `staleMs` an entry is only ever served as `lkg-memory`
76
+ * (the origin failed); without this bound such a copy can be any age. With it,
77
+ * an entry older than this is dropped on its next read and the origin's
78
+ * failure is reported as such. Must be at least `staleMs`.
79
+ */
80
+ lkgMaxAgeMs?: number;
81
+ /**
82
+ * Errors that mean "the origin answered, and the value is gone" rather than
83
+ * "the origin failed" (a page that now answers 404). A fetch that throws one
84
+ * drops the key from memory, from the negative cache and from the durable
85
+ * store, and its callers get `error` (never a last-known-good copy) — also
86
+ * when the fetch was the background revalidation of a stale copy. The drop is
87
+ * fenced like a write-back: a fetch that started before a purge drops nothing.
88
+ * The key is not negative-cached, since the origin did not fail.
89
+ */
90
+ dropOnError?: (error: unknown) => boolean;
91
+ /**
92
+ * Put the fetch's error on failed results (`SwrResult.error`; default false,
93
+ * so a result keeps its two fields for callers that compare it whole).
94
+ */
95
+ exposeErrors?: boolean;
44
96
  }
45
97
 
46
98
  interface MemEntry<T> {
47
99
  value: T;
48
100
  at: number;
101
+ /** `sizeOf(value)`, kept so an eviction or a replacement can subtract it. */
102
+ bytes: number;
49
103
  }
50
104
 
51
105
  /**
@@ -71,6 +125,13 @@ export class SwrCache<T = unknown> {
71
125
  private readonly negTtlMs: number;
72
126
  private readonly keyPrefix: string;
73
127
  private readonly now: () => number;
128
+ private readonly maxEntries: number;
129
+ private readonly maxBytes: number;
130
+ private readonly sizeOf?: (value: T) => number;
131
+ private readonly lkgMaxAgeMs: number;
132
+ private readonly dropOnError?: (error: unknown) => boolean;
133
+ private readonly exposeErrors: boolean;
134
+ private memBytes = 0;
74
135
  private readonly mem = new Map<string, MemEntry<T>>();
75
136
  private readonly neg = new Map<string, number>();
76
137
  private readonly inflight = new Map<string, Promise<T>>();
@@ -83,7 +144,7 @@ export class SwrCache<T = unknown> {
83
144
  */
84
145
  private generation = 0;
85
146
 
86
- constructor(opts: SwrCacheOptions) {
147
+ constructor(opts: SwrCacheOptions<T>) {
87
148
  this.store = opts.store;
88
149
  this.freshMs = opts.freshMs;
89
150
  this.staleMs = opts.staleMs;
@@ -92,6 +153,86 @@ export class SwrCache<T = unknown> {
92
153
  // Call `Date.now()` at read time (not a captured reference) so a test that installs
93
154
  // fake timers AFTER construction still controls this cache's clock.
94
155
  this.now = opts.now ?? (() => Date.now());
156
+ const max = opts.maxEntries;
157
+ if (max !== undefined && (!Number.isInteger(max) || max < 1)) {
158
+ throw new RangeError(`SwrCache: maxEntries must be a positive integer, got ${max}`);
159
+ }
160
+ this.maxEntries = max ?? Number.POSITIVE_INFINITY;
161
+ const maxBytes = opts.maxBytes;
162
+ if (maxBytes !== undefined && (!Number.isFinite(maxBytes) || maxBytes <= 0)) {
163
+ throw new RangeError(`SwrCache: maxBytes must be a positive number, got ${maxBytes}`);
164
+ }
165
+ if (maxBytes !== undefined && !opts.sizeOf) {
166
+ throw new RangeError('SwrCache: maxBytes needs sizeOf');
167
+ }
168
+ this.maxBytes = maxBytes ?? Number.POSITIVE_INFINITY;
169
+ this.sizeOf = opts.sizeOf;
170
+ const lkgMax = opts.lkgMaxAgeMs;
171
+ if (lkgMax !== undefined && (!Number.isFinite(lkgMax) || lkgMax < opts.staleMs)) {
172
+ throw new RangeError(`SwrCache: lkgMaxAgeMs must be a number of at least staleMs (${opts.staleMs}), got ${lkgMax}`);
173
+ }
174
+ this.lkgMaxAgeMs = lkgMax ?? Number.POSITIVE_INFINITY;
175
+ this.dropOnError = opts.dropOnError;
176
+ this.exposeErrors = opts.exposeErrors === true;
177
+ }
178
+
179
+ /** Entries in the in-memory tier (positive values only; the negative cache is not counted). */
180
+ get size(): number {
181
+ return this.mem.size;
182
+ }
183
+
184
+ /** The summed `sizeOf` of the in-memory tier (0 without `sizeOf`). */
185
+ get bytes(): number {
186
+ return this.memBytes;
187
+ }
188
+
189
+ /**
190
+ * Mark `key` most recently used. A `Map` iterates in insertion order, so
191
+ * re-inserting moves the key to the end and the first key is always the
192
+ * least recently used one.
193
+ */
194
+ private touch(key: string, entry: MemEntry<T>): void {
195
+ this.mem.delete(key);
196
+ this.mem.set(key, entry);
197
+ }
198
+
199
+ /** Remove `key` from the memory tier, keeping the byte count right. */
200
+ private dropMem(key: string): void {
201
+ const old = this.mem.get(key);
202
+ if (!old) return;
203
+ this.mem.delete(key);
204
+ this.memBytes -= old.bytes;
205
+ }
206
+
207
+ /** Empty the memory tier. */
208
+ private clearMem(): void {
209
+ this.mem.clear();
210
+ this.memBytes = 0;
211
+ }
212
+
213
+ /**
214
+ * Write `value` to memory as the most recent key, then drop the oldest beyond
215
+ * the bounds. A value heavier than the whole byte bound is not kept, and the
216
+ * key's previous entry goes with it (it would otherwise be served in its place).
217
+ */
218
+ private remember(key: string, value: T, at: number): void {
219
+ const bytes = this.sizeOf ? this.sizeOf(value) : 0;
220
+ this.dropMem(key);
221
+ if (bytes > this.maxBytes) return;
222
+ this.mem.set(key, { value, at, bytes });
223
+ this.memBytes += bytes;
224
+ while (this.mem.size > this.maxEntries || this.memBytes > this.maxBytes) {
225
+ const oldest = this.mem.keys().next();
226
+ if (oldest.done) return;
227
+ this.dropMem(oldest.value);
228
+ }
229
+ }
230
+
231
+ /** Record a failure for `key`, bounded like the memory tier. */
232
+ private rememberFailure(key: string, at: number): void {
233
+ this.neg.delete(key);
234
+ this.neg.set(key, at);
235
+ evictOldest(this.neg, this.maxEntries);
95
236
  }
96
237
 
97
238
  private durableKey(key: string): string {
@@ -110,23 +251,45 @@ export class SwrCache<T = unknown> {
110
251
  const existing = this.inflight.get(key);
111
252
  if (existing) return existing;
112
253
  const gen = this.generation;
113
- const p = (async () => {
254
+ // `let`, so the `finally` below can compare against it (it runs after the assignment).
255
+ let p: Promise<T> | undefined = undefined;
256
+ p = (async () => {
114
257
  try {
115
258
  const value = await fetcher();
116
259
  if (this.generation === gen) {
117
- this.mem.set(key, { value, at: this.now() });
260
+ this.remember(key, value, this.now());
118
261
  this.writeThrough(key, value);
119
262
  this.neg.delete(key);
120
263
  }
121
264
  return value;
265
+ } catch (error) {
266
+ // The origin said the value is gone: drop it, unless a purge since this
267
+ // fetch began means what memory holds now is newer than this answer.
268
+ if (this.isDrop(error) && this.generation === gen) {
269
+ this.dropMem(key);
270
+ this.neg.delete(key);
271
+ if (this.store) void this.store.delete(this.durableKey(key)).catch(() => {});
272
+ }
273
+ throw error;
122
274
  } finally {
123
- this.inflight.delete(key);
275
+ // A purge drops in-flight fetches from the map (so the next reader fetches
276
+ // anew); only remove the entry when it is still this fetch's own.
277
+ if (this.inflight.get(key) === p) this.inflight.delete(key);
124
278
  }
125
279
  })();
126
280
  this.inflight.set(key, p);
127
281
  return p;
128
282
  }
129
283
 
284
+ private isDrop(error: unknown): boolean {
285
+ return this.dropOnError?.(error) === true;
286
+ }
287
+
288
+ /** A failed result, with the fetch's error when `exposeErrors` asks for it. */
289
+ private failed(value: T | null, source: SwrSource, error: unknown): SwrResult<T> {
290
+ return this.exposeErrors ? { value, source, error } : { value, source };
291
+ }
292
+
130
293
  /** Persist to the durable tier without ever blocking/failing the request path. */
131
294
  private writeThrough(key: string, value: T): void {
132
295
  if (!this.store) return;
@@ -143,9 +306,16 @@ export class SwrCache<T = unknown> {
143
306
  async get(key: string, fetcher: () => Promise<T>): Promise<SwrResult<T>> {
144
307
  const gen = this.generation; // snapshot for purge-fencing the failure-path writes
145
308
  const now = this.now();
146
- const entry = this.mem.get(key);
309
+ let entry = this.mem.get(key);
310
+ if (entry && now - entry.at >= this.lkgMaxAgeMs) {
311
+ // Too old to be served even as last-known-good: forget it, so a failure
312
+ // below is reported as one instead of resurrecting an ancient copy.
313
+ this.dropMem(key);
314
+ entry = undefined;
315
+ }
147
316
 
148
317
  if (entry && now - entry.at < this.freshMs) {
318
+ this.touch(key, entry);
149
319
  return { value: entry.value, source: 'fresh' };
150
320
  }
151
321
 
@@ -159,6 +329,7 @@ export class SwrCache<T = unknown> {
159
329
 
160
330
  if (entry && now - entry.at < this.staleMs) {
161
331
  // Serve stale immediately; revalidate in the background (populates via runFetch).
332
+ this.touch(key, entry);
162
333
  void this.runFetch(key, fetcher).catch(() => {});
163
334
  return { value: entry.value, source: 'stale' };
164
335
  }
@@ -166,14 +337,24 @@ export class SwrCache<T = unknown> {
166
337
  try {
167
338
  const value = await this.runFetch(key, fetcher);
168
339
  return { value, source: 'cold' };
169
- } catch {
340
+ } catch (error) {
341
+ // The origin answered that the value is gone (`dropOnError`): no copy of it
342
+ // may stand in, and the key is not negative-cached (the origin did not fail).
343
+ if (this.isDrop(error)) return this.failed(null, 'error', error);
170
344
  // Origin failed. Degrade: in-memory LKG → durable LKG → null (negative-cached).
171
- // We deliberately DON'T advance `entry.at` here — serving last-known-good must
345
+ // We deliberately DON'T advance the entry's `at` here — serving last-known-good must
172
346
  // not masquerade as `fresh` nor delay recovery; the very next request retries
173
347
  // the origin and picks up a recovered KB immediately (parity with the origin
174
348
  // storefront swrGet).
175
- if (entry) {
176
- return { value: entry.value, source: 'lkg-memory' };
349
+ // What memory holds NOW wins over the entry read at the start (a newer copy may
350
+ // have landed meanwhile); that older entry only stands in while no purge has
351
+ // intervened (a purge evicted it on purpose) and while it is young enough.
352
+ const current = this.mem.get(key);
353
+ const lkg = current ?? (this.generation === gen ? entry : undefined);
354
+ if (lkg && this.now() - lkg.at < this.lkgMaxAgeMs) {
355
+ // Still a use of the key; only re-ranked while it is in memory (the bound may have evicted it).
356
+ if (current) this.touch(key, current);
357
+ return this.failed(lkg.value, 'lkg-memory', error);
177
358
  }
178
359
  if (this.store) {
179
360
  const durable = await this.store.get(this.durableKey(key)).catch(() => null);
@@ -181,41 +362,82 @@ export class SwrCache<T = unknown> {
181
362
  const value = durable.value as T;
182
363
  // Hydrate memory with the durable entry's OWN timestamp (not `now`), so it
183
364
  // isn't served as `fresh`, and skip the write if a purge intervened.
184
- if (this.generation === gen) this.mem.set(key, { value, at: durable.storedAt });
185
- return { value, source: 'lkg-durable' };
365
+ if (this.generation === gen) this.remember(key, value, durable.storedAt);
366
+ return this.failed(value, 'lkg-durable', error);
186
367
  }
187
368
  }
188
- if (this.generation === gen) this.neg.set(key, this.now());
189
- return { value: null, source: 'error' };
369
+ if (this.generation === gen) this.rememberFailure(key, this.now());
370
+ return this.failed(null, 'error', error);
190
371
  }
191
372
  }
192
373
 
193
- /** Immediately evict one key from memory AND the durable store. */
374
+ /**
375
+ * Immediately evict one key from memory AND the durable store. A fetch of it
376
+ * still in flight is fenced (its result is not cached) and detached, so the
377
+ * next reader fetches anew instead of riding a pre-purge fetch.
378
+ */
194
379
  async purge(key: string): Promise<void> {
195
380
  this.generation++; // fence any in-flight fetch from re-populating what we evict
196
- this.mem.delete(key);
381
+ this.dropMem(key);
197
382
  this.neg.delete(key);
383
+ this.inflight.delete(key);
198
384
  if (this.store) await this.store.delete(this.durableKey(key));
199
385
  }
200
386
 
201
- /** Evict every key (or those starting with `prefix`) from memory AND durable. */
387
+ /** Evict every key (or those starting with `prefix`) from memory AND durable; in-flight fetches as `purge`. */
202
388
  async purgeAll(prefix?: string): Promise<void> {
203
389
  this.generation++; // fence in-flight fetches (see `generation`)
204
390
  if (prefix) {
205
- for (const k of [...this.mem.keys()]) if (k.startsWith(prefix)) this.mem.delete(k);
391
+ for (const k of [...this.mem.keys()]) if (k.startsWith(prefix)) this.dropMem(k);
206
392
  for (const k of [...this.neg.keys()]) if (k.startsWith(prefix)) this.neg.delete(k);
393
+ for (const k of [...this.inflight.keys()]) if (k.startsWith(prefix)) this.inflight.delete(k);
207
394
  if (this.store) await this.store.clear(this.durableKey(prefix));
208
395
  } else {
209
- this.mem.clear();
396
+ this.clearMem();
210
397
  this.neg.clear();
398
+ this.inflight.clear();
211
399
  if (this.store) await this.store.clear();
212
400
  }
213
401
  }
214
402
 
403
+ /**
404
+ * Make every key (or those starting with `prefix`) due for a fetch on its next read, WITHOUT
405
+ * giving up what is held: the memory copy stays as last-known-good and the durable store is not
406
+ * touched. The next reader fetches; if the origin fails, it is served the copy it would have
407
+ * been served before, instead of nothing.
408
+ *
409
+ * This is the purge for "the content changed": `purge`/`purgeAll` also delete the durable copy,
410
+ * which is right for "this must no longer be served" and wrong for a routine publish — a purge
411
+ * that arrives while the origin is down would otherwise take the site's offline floor with it.
412
+ * In-flight fetches are fenced and detached as in `purge` (a fetch that started before the
413
+ * change must not be cached as fresh), and the negative cache is cleared.
414
+ */
415
+ expireAll(prefix?: string): void {
416
+ this.generation++; // fence in-flight fetches (see `generation`)
417
+ // Old enough to be neither fresh nor stale-while-revalidate; an entry that is older already
418
+ // keeps its own time, so expiring never makes a copy look newer than it is.
419
+ const expiredAt = this.now() - this.staleMs;
420
+ for (const [key, entry] of this.mem) {
421
+ if (prefix && !key.startsWith(prefix)) continue;
422
+ if (entry.at > expiredAt) entry.at = expiredAt;
423
+ }
424
+ for (const key of [...this.neg.keys()]) if (!prefix || key.startsWith(prefix)) this.neg.delete(key);
425
+ for (const key of [...this.inflight.keys()]) if (!prefix || key.startsWith(prefix)) this.inflight.delete(key);
426
+ }
427
+
215
428
  /** Test-only: clear the in-memory tiers (leaves the durable store intact). */
216
429
  resetMemory(): void {
217
- this.mem.clear();
430
+ this.clearMem();
218
431
  this.neg.clear();
219
432
  this.inflight.clear();
220
433
  }
221
434
  }
435
+
436
+ /** Delete the first (least recently used) keys of `map` until it holds at most `max`. */
437
+ function evictOldest(map: Map<string, unknown>, max: number): void {
438
+ while (map.size > max) {
439
+ const oldest = map.keys().next();
440
+ if (oldest.done) return;
441
+ map.delete(oldest.value);
442
+ }
443
+ }