@blogmcp/content-cache 0.12.0 → 0.14.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/dist/swr-cache.d.ts +13 -0
- package/dist/swr-cache.js +55 -35
- package/package.json +1 -1
- package/src/__tests__/swr-cache.test.ts +84 -0
- package/src/swr-cache.ts +25 -0
package/dist/swr-cache.d.ts
CHANGED
|
@@ -178,6 +178,19 @@ export declare class SwrCache<T = unknown> {
|
|
|
178
178
|
purge(key: string): Promise<void>;
|
|
179
179
|
/** Evict every key (or those starting with `prefix`) from memory AND durable; in-flight fetches as `purge`. */
|
|
180
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;
|
|
181
194
|
/** Test-only: clear the in-memory tiers (leaves the durable store intact). */
|
|
182
195
|
resetMemory(): void;
|
|
183
196
|
}
|
package/dist/swr-cache.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
class
|
|
1
|
+
class u {
|
|
2
2
|
store;
|
|
3
3
|
freshMs;
|
|
4
4
|
staleMs;
|
|
@@ -29,12 +29,12 @@ class f {
|
|
|
29
29
|
if (t !== void 0 && (!Number.isInteger(t) || t < 1))
|
|
30
30
|
throw new RangeError(`SwrCache: maxEntries must be a positive integer, got ${t}`);
|
|
31
31
|
this.maxEntries = t ?? Number.POSITIVE_INFINITY;
|
|
32
|
-
const
|
|
33
|
-
if (
|
|
34
|
-
throw new RangeError(`SwrCache: maxBytes must be a positive number, got ${
|
|
35
|
-
if (
|
|
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
36
|
throw new RangeError("SwrCache: maxBytes needs sizeOf");
|
|
37
|
-
this.maxBytes =
|
|
37
|
+
this.maxBytes = s ?? Number.POSITIVE_INFINITY, this.sizeOf = e.sizeOf;
|
|
38
38
|
const r = e.lkgMaxAgeMs;
|
|
39
39
|
if (r !== void 0 && (!Number.isFinite(r) || r < e.staleMs))
|
|
40
40
|
throw new RangeError(`SwrCache: lkgMaxAgeMs must be a number of at least staleMs (${e.staleMs}), got ${r}`);
|
|
@@ -70,18 +70,18 @@ class f {
|
|
|
70
70
|
* the bounds. A value heavier than the whole byte bound is not kept, and the
|
|
71
71
|
* key's previous entry goes with it (it would otherwise be served in its place).
|
|
72
72
|
*/
|
|
73
|
-
remember(e, t,
|
|
73
|
+
remember(e, t, s) {
|
|
74
74
|
const r = this.sizeOf ? this.sizeOf(t) : 0;
|
|
75
75
|
if (this.dropMem(e), !(r > this.maxBytes))
|
|
76
|
-
for (this.mem.set(e, { value: t, at:
|
|
77
|
-
const
|
|
78
|
-
if (
|
|
79
|
-
this.dropMem(
|
|
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
80
|
}
|
|
81
81
|
}
|
|
82
82
|
/** Record a failure for `key`, bounded like the memory tier. */
|
|
83
83
|
rememberFailure(e, t) {
|
|
84
|
-
this.neg.delete(e), this.neg.set(e, t),
|
|
84
|
+
this.neg.delete(e), this.neg.set(e, t), f(this.neg, this.maxEntries);
|
|
85
85
|
}
|
|
86
86
|
durableKey(e) {
|
|
87
87
|
return this.keyPrefix ? `${this.keyPrefix}${e}` : e;
|
|
@@ -95,11 +95,11 @@ class f {
|
|
|
95
95
|
* is returned to callers but NOT cached.
|
|
96
96
|
*/
|
|
97
97
|
runFetch(e, t) {
|
|
98
|
-
const
|
|
99
|
-
if (
|
|
98
|
+
const s = this.inflight.get(e);
|
|
99
|
+
if (s) return s;
|
|
100
100
|
const r = this.generation;
|
|
101
|
-
let
|
|
102
|
-
return
|
|
101
|
+
let i;
|
|
102
|
+
return i = (async () => {
|
|
103
103
|
try {
|
|
104
104
|
const h = await t();
|
|
105
105
|
return this.generation === r && (this.remember(e, h, this.now()), this.writeThrough(e, h), this.neg.delete(e)), h;
|
|
@@ -107,22 +107,22 @@ class f {
|
|
|
107
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
108
|
})), h;
|
|
109
109
|
} finally {
|
|
110
|
-
this.inflight.get(e) ===
|
|
110
|
+
this.inflight.get(e) === i && this.inflight.delete(e);
|
|
111
111
|
}
|
|
112
|
-
})(), this.inflight.set(e,
|
|
112
|
+
})(), this.inflight.set(e, i), i;
|
|
113
113
|
}
|
|
114
114
|
isDrop(e) {
|
|
115
115
|
return this.dropOnError?.(e) === !0;
|
|
116
116
|
}
|
|
117
117
|
/** A failed result, with the fetch's error when `exposeErrors` asks for it. */
|
|
118
|
-
failed(e, t,
|
|
119
|
-
return this.exposeErrors ? { value: e, source: t, error:
|
|
118
|
+
failed(e, t, s) {
|
|
119
|
+
return this.exposeErrors ? { value: e, source: t, error: s } : { value: e, source: t };
|
|
120
120
|
}
|
|
121
121
|
/** Persist to the durable tier without ever blocking/failing the request path. */
|
|
122
122
|
writeThrough(e, t) {
|
|
123
123
|
if (!this.store) return;
|
|
124
|
-
const
|
|
125
|
-
this.store.set(this.durableKey(e),
|
|
124
|
+
const s = { value: t, storedAt: this.now() };
|
|
125
|
+
this.store.set(this.durableKey(e), s).catch(() => {
|
|
126
126
|
});
|
|
127
127
|
}
|
|
128
128
|
/**
|
|
@@ -132,33 +132,33 @@ class f {
|
|
|
132
132
|
* is nothing cached in either tier.
|
|
133
133
|
*/
|
|
134
134
|
async get(e, t) {
|
|
135
|
-
const
|
|
136
|
-
let
|
|
137
|
-
if (
|
|
138
|
-
return this.touch(e,
|
|
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
139
|
const h = this.neg.get(e);
|
|
140
|
-
if (!
|
|
140
|
+
if (!i && h !== void 0) {
|
|
141
141
|
if (r - h < this.negTtlMs) return { value: null, source: "negative" };
|
|
142
142
|
this.neg.delete(e);
|
|
143
143
|
}
|
|
144
|
-
if (
|
|
145
|
-
return this.touch(e,
|
|
146
|
-
}), { value:
|
|
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" };
|
|
147
147
|
try {
|
|
148
148
|
return { value: await this.runFetch(e, t), source: "cold" };
|
|
149
149
|
} catch (n) {
|
|
150
150
|
if (this.isDrop(n)) return this.failed(null, "error", n);
|
|
151
|
-
const a = this.mem.get(e), l = a ?? (this.generation ===
|
|
151
|
+
const a = this.mem.get(e), l = a ?? (this.generation === s ? i : void 0);
|
|
152
152
|
if (l && this.now() - l.at < this.lkgMaxAgeMs)
|
|
153
153
|
return a && this.touch(e, a), this.failed(l.value, "lkg-memory", n);
|
|
154
154
|
if (this.store) {
|
|
155
155
|
const m = await this.store.get(this.durableKey(e)).catch(() => null);
|
|
156
156
|
if (m) {
|
|
157
157
|
const g = m.value;
|
|
158
|
-
return this.generation ===
|
|
158
|
+
return this.generation === s && this.remember(e, g, m.storedAt), this.failed(g, "lkg-durable", n);
|
|
159
159
|
}
|
|
160
160
|
}
|
|
161
|
-
return this.generation ===
|
|
161
|
+
return this.generation === s && this.rememberFailure(e, this.now()), this.failed(null, "error", n);
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
164
|
/**
|
|
@@ -179,12 +179,32 @@ class f {
|
|
|
179
179
|
} else
|
|
180
180
|
this.clearMem(), this.neg.clear(), this.inflight.clear(), this.store && await this.store.clear();
|
|
181
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);
|
|
201
|
+
}
|
|
182
202
|
/** Test-only: clear the in-memory tiers (leaves the durable store intact). */
|
|
183
203
|
resetMemory() {
|
|
184
204
|
this.clearMem(), this.neg.clear(), this.inflight.clear();
|
|
185
205
|
}
|
|
186
206
|
}
|
|
187
|
-
function
|
|
207
|
+
function f(o, e) {
|
|
188
208
|
for (; o.size > e; ) {
|
|
189
209
|
const t = o.keys().next();
|
|
190
210
|
if (t.done) return;
|
|
@@ -192,5 +212,5 @@ function u(o, e) {
|
|
|
192
212
|
}
|
|
193
213
|
}
|
|
194
214
|
export {
|
|
195
|
-
|
|
215
|
+
u as SwrCache
|
|
196
216
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blogmcp/content-cache",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.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,
|
|
@@ -584,3 +584,87 @@ describe('SwrCache in-flight fetches across a purge', () => {
|
|
|
584
584
|
expect(rider).not.toHaveBeenCalled();
|
|
585
585
|
});
|
|
586
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
|
@@ -400,6 +400,31 @@ export class SwrCache<T = unknown> {
|
|
|
400
400
|
}
|
|
401
401
|
}
|
|
402
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
|
+
|
|
403
428
|
/** Test-only: clear the in-memory tiers (leaves the durable store intact). */
|
|
404
429
|
resetMemory(): void {
|
|
405
430
|
this.clearMem();
|