@ultimat3/cache 30.9.0 → 31.1.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/src/invalidate.ts CHANGED
@@ -1,15 +1,15 @@
1
1
  // THE single invalidation entry point. `action.cache.invalidates`, `x cache bust`, the MCP
2
2
  // tool and the admin panel all call this one function — nothing else may talk to a tier's
3
- // `invalidateTags` directly. One hop reaches memo, LRU, Redis, ISR routes and the CDN, and
4
- // the returned report is what the `/_x` cache panel renders, so "did it actually clear?" is
5
- // answerable without a log dive.
3
+ // `invalidateTags` directly. One hop reaches memo, LRU, Redis, ISR routes and the CDN; the
4
+ // returned report answers the caller, and one `cache.invalidate` event answers every subscriber
5
+ // (the `/_x` cache panel keeps its own buffer), so "did it actually clear?" needs no log dive.
6
6
 
7
7
  import {
8
8
  CACHE_TIERS,
9
9
  currentSpan,
10
+ instrument,
10
11
  logger,
11
12
  renderThrowable,
12
- systemClock,
13
13
  withSpan,
14
14
  } from '@ultimat3/core';
15
15
  import { markAllInvalidated, markInvalidated } from './fence';
@@ -17,7 +17,6 @@ import { dependentsOfKind, graphSnapshot } from './graph';
17
17
  import { logPartial, resetPartialLog } from './partial-log';
18
18
  import type { CacheTag } from './tags';
19
19
  import { assertKnownTags, knownTags, parseTag, serializeTags } from './tags';
20
- import { isolateTierFailures, resetTierFailures } from './tier-failures';
21
20
  import type { CacheTier, TierInvalidation } from './tiers';
22
21
  import { sortTiers } from './tiers';
23
22
 
@@ -63,48 +62,6 @@ export interface InvalidationReport {
63
62
  readonly errors: readonly { tier: string; message: string }[];
64
63
  }
65
64
 
66
- /** One completed `invalidateTags` call, kept for the `/_x` cache panel. */
67
- export interface InvalidationEvent {
68
- /** ISO-8601, from core's `systemClock` — never `new Date()`. */
69
- readonly at: string;
70
- /** Wire-form tags, exactly `report.tags`. */
71
- readonly tags: readonly string[];
72
- /**
73
- * Everything the fan-out actually cleared: every tier key — the `cdn` tier's accepted purge
74
- * keys included — plus the ISR paths and the live queries.
75
- *
76
- * Deliberately NOT `report.cdn`: that is the dependency graph's answer to "what depends on
77
- * these tags", and folding it in here reported a path as busted when no `cdn` tier was
78
- * registered to purge it. A partial bust that reads as a clean one is the failure this log
79
- * exists to catch.
80
- */
81
- readonly busted: readonly string[];
82
- /**
83
- * What triggered it: the name of the span active when `invalidateTags` was called, or
84
- * `'invalidateTags'`.
85
- */
86
- readonly source: string;
87
- readonly durationMs: number;
88
- /** Tier failures, verbatim from the report — a partial bust must not read as a clean one. */
89
- readonly errors: readonly { readonly tier: string; readonly message: string }[];
90
- }
91
-
92
- // A dev log, not an audit trail — capped so a long-lived `x dev` process cannot grow it forever.
93
- const MAX_INVALIDATION_LOG = 100;
94
-
95
- /** Newest first. Module-private; read it through `recentInvalidations()`. */
96
- const invalidationLog: InvalidationEvent[] = [];
97
-
98
- function recordInvalidation(event: InvalidationEvent): void {
99
- invalidationLog.unshift(event);
100
- invalidationLog.length = Math.min(invalidationLog.length, MAX_INVALIDATION_LOG);
101
- }
102
-
103
- /** What the `/_x` cache panel renders: newest first, capped, a copy of the live log. */
104
- export function recentInvalidations(): readonly InvalidationEvent[] {
105
- return [...invalidationLog];
106
- }
107
-
108
65
  const registry: CacheTier[] = [];
109
66
  let revalidator: Revalidator | undefined;
110
67
  let tagRevalidator: TagRevalidator | undefined;
@@ -122,24 +79,22 @@ export function registeredTiers(): readonly CacheTier[] {
122
79
  }
123
80
 
124
81
  /**
125
- * Test seam: drops every registered tier, the revalidator, the invalidation log and the
126
- * swallowed-failure log. One reset, so a suite cannot clear half the recorded state.
82
+ * Test seam: drops every registered tier, the revalidators and the broadcast. One reset, so a
83
+ * suite cannot clear half the registered state.
127
84
  */
128
85
  export function resetTiers(): void {
129
86
  registry.length = 0;
130
87
  revalidator = undefined;
131
88
  tagRevalidator = undefined;
132
89
  broadcast = undefined;
133
- invalidationLog.length = 0;
134
- resetTierFailures();
135
90
  resetPartialLog();
136
91
  }
137
92
 
138
93
  /**
139
94
  * `isolateDeclaredTags()`'s contract over everything `resetTiers()` drops — `tags.ts` carries the
140
95
  * why. It must live here because three of the four pieces are unreachable from a test file: the
141
- * revalidator has no reader, and neither log has a writer, so a suite that reset them could put
142
- * back only the tier registry:
96
+ * revalidators and the broadcast have no reader, so a suite that reset them could put back only
97
+ * the tier registry:
143
98
  *
144
99
  * const restoreTiers = isolateTiers();
145
100
  * afterAll(restoreTiers);
@@ -152,8 +107,6 @@ export function isolateTiers(): () => void {
152
107
  const capturedRevalidator = revalidator;
153
108
  const capturedTagRevalidator = tagRevalidator;
154
109
  const capturedBroadcast = broadcast;
155
- const capturedLog = [...invalidationLog];
156
- const restoreFailures = isolateTierFailures();
157
110
 
158
111
  return () => {
159
112
  resetTiers();
@@ -161,8 +114,6 @@ export function isolateTiers(): () => void {
161
114
  revalidator = capturedRevalidator;
162
115
  tagRevalidator = capturedTagRevalidator;
163
116
  broadcast = capturedBroadcast;
164
- invalidationLog.push(...capturedLog);
165
- restoreFailures();
166
117
  };
167
118
  }
168
119
 
@@ -220,6 +171,7 @@ export function receiveInvalidationBroadcast(wire: readonly string[]): Promise<I
220
171
  }
221
172
 
222
173
  interface FanOutOptions {
174
+ /** What triggered the bust — the `cache.invalidate` event's `source`, the `/_x` panel's column. */
223
175
  readonly source: string;
224
176
  /** Never widened to a public parameter: see `receiveInvalidationBroadcast`. */
225
177
  readonly emit: boolean;
@@ -322,15 +274,18 @@ function fanOut(tags: readonly CacheTag[], options: FanOutOptions): Promise<Inva
322
274
  errors,
323
275
  };
324
276
 
325
- recordInvalidation({
326
- at: systemClock.now().toISOString(),
277
+ // `busted` is everything the fan-out actually cleared — deliberately NOT `report.cdn`, the
278
+ // graph's answer to "what depends on these tags": folding it in reported a path as busted
279
+ // when no `cdn` tier was registered to purge it, and a partial bust that reads as a clean one
280
+ // is the failure this event exists to catch.
281
+ instrument('cache.invalidate', {
327
282
  tags: report.tags,
283
+ source,
328
284
  busted: dedupe([
329
285
  ...report.tiers.flatMap((entry) => entry.keys),
330
286
  ...report.isr,
331
287
  ...report.liveQueries,
332
288
  ]),
333
- source,
334
289
  durationMs: report.durationMs,
335
290
  errors: report.errors,
336
291
  });
@@ -402,74 +357,78 @@ export const FLUSH_ALL_TAG = '*';
402
357
  * Never throws; the cost is one cold cache.
403
358
  */
404
359
  export function flushProcessTiers(source: string): Promise<InvalidationReport> {
405
- return withSpan('cache.flush', async (): Promise<InvalidationReport> => {
406
- const startedAt = performance.now();
407
- markAllInvalidated();
408
- const tiers: TierInvalidation[] = [];
409
- const errors: { tier: string; message: string }[] = [];
410
- for (const tier of sortTiers(registry)) {
411
- if (tier.clear === undefined) continue;
412
- try {
413
- await tier.clear();
414
- tiers.push({ tier: tier.name, keys: [] });
415
- } catch (error) {
416
- errors.push({ tier: tier.name, message: renderThrowable(error) });
360
+ return withSpan(
361
+ 'cache.flush',
362
+ async (): Promise<InvalidationReport> => {
363
+ const startedAt = performance.now();
364
+ markAllInvalidated();
365
+ const tiers: TierInvalidation[] = [];
366
+ const errors: { tier: string; message: string }[] = [];
367
+ for (const tier of sortTiers(registry)) {
368
+ if (tier.clear === undefined) continue;
369
+ try {
370
+ await tier.clear();
371
+ tiers.push({ tier: tier.name, keys: [] });
372
+ } catch (error) {
373
+ errors.push({ tier: tier.name, message: renderThrowable(error) });
374
+ }
417
375
  }
418
- }
419
- // Read BEFORE the pages are revalidated: a purged page leaves the graph, and its tags are
420
- // what the edge is purged by below.
421
- const tagged = graphSnapshot().filter((entry) =>
422
- entry.dependents.some((dep) => dep.kind === 'isr-route'),
423
- );
424
- const isrPaths = new Set(
425
- tagged.flatMap((entry) =>
426
- entry.dependents.filter((dep) => dep.kind === 'isr-route').map((dep) => dep.id),
427
- ),
428
- );
429
- for (const path of isrPaths) {
376
+ // Read BEFORE the pages are revalidated: a purged page leaves the graph, and its tags are
377
+ // what the edge is purged by below.
378
+ const tagged = graphSnapshot().filter((entry) =>
379
+ entry.dependents.some((dep) => dep.kind === 'isr-route'),
380
+ );
381
+ const isrPaths = new Set(
382
+ tagged.flatMap((entry) =>
383
+ entry.dependents.filter((dep) => dep.kind === 'isr-route').map((dep) => dep.id),
384
+ ),
385
+ );
386
+ for (const path of isrPaths) {
387
+ try {
388
+ await revalidator?.(path);
389
+ } catch (error) {
390
+ errors.push({ tier: 'isr', message: renderThrowable(error) });
391
+ }
392
+ }
393
+ // And every page the holder has that the graph never named — as a bust asks it, by tag. A
394
+ // flush is at least a bust of everything: under `onInvalidate: 'purge'` those pages are deleted.
430
395
  try {
431
- await revalidator?.(path);
396
+ for (const path of (await tagRevalidator?.(EVERY_TAG)) ?? []) isrPaths.add(path);
432
397
  } catch (error) {
433
398
  errors.push({ tier: 'isr', message: renderThrowable(error) });
434
399
  }
435
- }
436
- // And every page the holder has that the graph never named — as a bust asks it, by tag. A
437
- // flush is at least a bust of everything: under `onInvalidate: 'purge'` those pages are deleted.
438
- try {
439
- for (const path of (await tagRevalidator?.(EVERY_TAG)) ?? []) isrPaths.add(path);
440
- } catch (error) {
441
- errors.push({ tier: 'isr', message: renderThrowable(error) });
442
- }
443
- const isr = [...isrPaths];
444
- // The edge LAST, as in a bust, and for the pages THIS process could have handed it while it
445
- // was deaf: a hit it answered from a copy a peer had already purged went out public, and the
446
- // peer's own edge purge had run by then. Shared read tiers stay untouched — the sender's.
447
- await purgeEdge(
448
- sortTiers(registry),
449
- tagged.map((entry) => parseTag(entry.tag)),
450
- tiers,
451
- errors,
452
- );
453
- const report: InvalidationReport = {
454
- tags: [FLUSH_ALL_TAG],
455
- tiers,
456
- isr,
457
- cdn: [],
458
- liveQueries: [],
459
- durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
460
- errors,
461
- };
462
- recordInvalidation({
463
- at: systemClock.now().toISOString(),
464
- tags: report.tags,
465
- busted: [...isr],
466
- source,
467
- durationMs: report.durationMs,
468
- errors,
469
- });
470
- if (errors.length > 0) logger.warn('cache.flush.partial', { ...report });
471
- return report;
472
- });
400
+ const isr = [...isrPaths];
401
+ // The edge LAST, as in a bust, and for the pages THIS process could have handed it while it
402
+ // was deaf: a hit it answered from a copy a peer had already purged went out public, and the
403
+ // peer's own edge purge had run by then. Shared read tiers stay untouched — the sender's.
404
+ await purgeEdge(
405
+ sortTiers(registry),
406
+ tagged.map((entry) => parseTag(entry.tag)),
407
+ tiers,
408
+ errors,
409
+ );
410
+ const report: InvalidationReport = {
411
+ tags: [FLUSH_ALL_TAG],
412
+ tiers,
413
+ isr,
414
+ cdn: [],
415
+ liveQueries: [],
416
+ durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
417
+ errors,
418
+ };
419
+ instrument('cache.invalidate', {
420
+ tags: report.tags,
421
+ source,
422
+ busted: [...isr],
423
+ durationMs: report.durationMs,
424
+ errors,
425
+ });
426
+ if (errors.length > 0) logger.warn('cache.flush.partial', { ...report });
427
+ return report;
428
+ },
429
+ // Who asked for the flush rides on its span: the trace is where "why is the cache cold?" is read.
430
+ { attributes: { 'ultimate.cache.flush_source': source } },
431
+ );
473
432
  }
474
433
 
475
434
  /** First-seen order kept — a union of what actually changed, not a sorted report. */
@@ -0,0 +1,203 @@
1
+ // The shared tier's tag -> keys layout and every command that reads or writes it. A bucket is a
2
+ // sorted set scored by when its member may be forgotten, so every write prunes the dead and a
3
+ // bucket holds live keys only; a bust reads it in pages. One key per command, always: slot-local
4
+ // on Redis Cluster and Dragonfly by construction, and plain commands the recording fake can hold.
5
+
6
+ import { CacheDriverUnavailableError } from './errors';
7
+ import type { RedisLike } from './redis';
8
+ import type { CacheTag } from './tags';
9
+
10
+ /**
11
+ * How long a member outlives its value key, in ms. The score is the WRITER's clock and the prune
12
+ * is the next writer's: a pod running ahead would forget a member whose value key still lives, and
13
+ * that key would serve stale with no tag left to reach it. Skew under the grace cannot do that.
14
+ */
15
+ export const TAG_GRACE_MS = 60_000;
16
+
17
+ /** The `COUNT` hint of one `ZSCAN`. A whole bucket in one reply blocks the shared server. */
18
+ export const BUST_PAGE_SIZE = 1_000;
19
+
20
+ /** Value keys `UNLINK`ed per pipelined burst. Bounds client memory, not round trips. */
21
+ const UNLINK_BATCH = 1_024;
22
+
23
+ /** Members per `ZREM`, and how many of those are in flight at once. */
24
+ const SWEEP_CHUNK = 1_000;
25
+ const SWEEP_CONCURRENCY = 8;
26
+
27
+ /**
28
+ * The bucket's own lease, which only ever GROWS: a 60s member must not shorten a bucket a 1h member
29
+ * is in, or that value key becomes unreachable by tag. `EXPIRE … GT` treats a key with no TTL as
30
+ * infinite, so a fresh bucket would keep none — read-then-set inside a script covers both, with no
31
+ * Redis 7. The prune bounds a bucket that is written; this lease removes one that is not.
32
+ */
33
+ export const REDIS_TAG_LEASE_SCRIPT = `
34
+ local ttl = tonumber(ARGV[1])
35
+ local current = redis.call('TTL', KEYS[1])
36
+ if current < 0 or current < ttl then
37
+ redis.call('EXPIRE', KEYS[1], ttl)
38
+ end
39
+ return 1
40
+ `.trim();
41
+
42
+ /**
43
+ * The key layout. `t2:` is a TAG's bucket and `e2:` its ENTITY's index — one key is never both, or a
44
+ * row bust over-reaches. The `2` is the sorted-set generation: a v30 pod's `t:`/`e:` plain sets
45
+ * never collide with these on a shared server, and expire on their own lease.
46
+ *
47
+ * `{entity}` is a Redis Cluster hash tag, not decoration: a row's bucket and its collection's
48
+ * hash to one slot.
49
+ */
50
+ export function bucketLayout(ns: string) {
51
+ const tagKey = (owned: CacheTag): string =>
52
+ owned.id === undefined
53
+ ? `${ns}:t2:{${owned.entity}}`
54
+ : `${ns}:t2:{${owned.entity}}:${owned.id}`;
55
+ const entityKey = (entity: string): string => `${ns}:e2:{${entity}}`;
56
+ return {
57
+ valueKey: (key: string): string => `${ns}:c:${key}`,
58
+ /** A write joins its tag's bucket plus its entity's index. */
59
+ writeBucketsFor: (owned: CacheTag): string[] => [tagKey(owned), entityKey(owned.entity)],
60
+ /**
61
+ * `tagMatches` in keys. A COLLECTION bust reads the entity index, which holds every key of the
62
+ * entity. A ROW bust reads its own bucket and the bare collection tag's — never the index, or
63
+ * `post:2` dies with `post:1`.
64
+ */
65
+ bustBucketsFor: (owned: CacheTag): string[] =>
66
+ owned.id === undefined
67
+ ? [entityKey(owned.entity)]
68
+ : [tagKey(owned), tagKey({ entity: owned.entity })],
69
+ /**
70
+ * The buckets a bust CLEANS, a superset of what it reads. A row bust never reads the index but
71
+ * must still `ZREM` what it deleted from it; a collection bust cleans the collection tag's
72
+ * bucket it skipped reading. Removing can never over-reach: only what this bust deleted leaves.
73
+ */
74
+ sweepBucketsFor: (owned: CacheTag): string[] =>
75
+ owned.id === undefined
76
+ ? [entityKey(owned.entity), tagKey({ entity: owned.entity })]
77
+ : [tagKey(owned), tagKey({ entity: owned.entity }), entityKey(owned.entity)],
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Join `member` to every bucket, prune the dead, and extend the lease — three commands per bucket,
83
+ * issued together, so one pipelined round trip. The order within a bucket is irrelevant: the prune
84
+ * removes only members whose score is already past, and this member's lies `ttl + grace` ahead.
85
+ */
86
+ export async function joinBuckets(
87
+ client: RedisLike,
88
+ buckets: readonly string[],
89
+ member: string,
90
+ now: number,
91
+ ttlMs: number,
92
+ ): Promise<void> {
93
+ const score = String(Math.ceil(now + ttlMs) + TAG_GRACE_MS);
94
+ const leaseSeconds = String(Math.ceil((ttlMs + TAG_GRACE_MS) / 1_000));
95
+ await Promise.all(
96
+ buckets.flatMap((bucket) => [
97
+ client.send('ZADD', [bucket, score, member]),
98
+ client.send('ZREMRANGEBYSCORE', [bucket, '-inf', `(${String(now)}`]),
99
+ client.send('EVAL', [REDIS_TAG_LEASE_SCRIPT, '1', bucket, leaseSeconds]),
100
+ ]),
101
+ );
102
+ }
103
+
104
+ /**
105
+ * `ZSCORE` answered nil for some bucket: a bust removed this member while its write was in the
106
+ * air. Only a literal `null` counts — a reply this cannot read is not evidence, and reading one as
107
+ * "gone" deletes every value the tier writes.
108
+ */
109
+ export async function lostMembership(
110
+ client: RedisLike,
111
+ buckets: readonly string[],
112
+ member: string,
113
+ ): Promise<boolean> {
114
+ const scores = await Promise.all(
115
+ buckets.map((bucket) => client.send('ZSCORE', [bucket, member])),
116
+ );
117
+ return scores.some((reply) => reply === null);
118
+ }
119
+
120
+ /** `[cursor, [member, score, …]]` — flat in RESP2 and RESP3 alike; `[member, score]` pairs read too. */
121
+ function scanPage(reply: unknown, bucket: string): { readonly cursor: string; members: string[] } {
122
+ if (!Array.isArray(reply) || reply.length !== 2 || !Array.isArray(reply[1])) {
123
+ throw unreadable(bucket);
124
+ }
125
+ const [cursor, entries] = reply as [unknown, unknown[]];
126
+ if (typeof cursor !== 'string' && typeof cursor !== 'number') throw unreadable(bucket);
127
+ const members = entries.every(Array.isArray)
128
+ ? (entries as unknown[][]).map(([member]) => member)
129
+ : entries.filter((_, i) => i % 2 === 0);
130
+ if (!members.every((member) => typeof member === 'string')) throw unreadable(bucket);
131
+ return { cursor: String(cursor), members: members as string[] };
132
+ }
133
+
134
+ const unreadable = (bucket: string): CacheDriverUnavailableError =>
135
+ new CacheDriverUnavailableError({
136
+ driver: 'redis',
137
+ cause: `ZSCAN on "${bucket}" answered a reply that is not a cursor and a member list`,
138
+ fix: 'redis-cli -u "$REDIS_URL" HELLO — the tier needs a Redis or Valkey server speaking RESP2 or RESP3; point REDIS_URL at one',
139
+ });
140
+
141
+ /**
142
+ * Every member of one bucket, `ZSCAN … COUNT BUST_PAGE_SIZE` per round trip. `ZSCAN`, never a
143
+ * score cursor: Redis guarantees a scan returns every member present from its first call to its
144
+ * last, whatever is added, removed or re-scored meanwhile. A `(score, offset)` cursor broke on
145
+ * exactly those — a concurrent prune of a read page of tied dead members, or a re-write moving a
146
+ * read tie member up, shifted the offset past live keys, which served stale until TTL. A scan
147
+ * may return a member twice; the set dedupes.
148
+ */
149
+ export async function readBucket(client: RedisLike, bucket: string): Promise<string[]> {
150
+ const members = new Set<string>();
151
+ let cursor = '0';
152
+ do {
153
+ const reply = await client.send('ZSCAN', [bucket, cursor, 'COUNT', String(BUST_PAGE_SIZE)]);
154
+ const page = scanPage(reply, bucket);
155
+ for (const member of page.members) members.add(member);
156
+ cursor = page.cursor;
157
+ } while (cursor !== '0');
158
+ return [...members];
159
+ }
160
+
161
+ /** `UNLINK` each key on its own (slot-local), pipelined per batch; which ones died is the answer. */
162
+ export async function unlinkAll(
163
+ client: RedisLike,
164
+ keys: readonly string[],
165
+ ): Promise<{ readonly deleted: Set<string>; readonly failures: unknown[] }> {
166
+ const deleted = new Set<string>();
167
+ const failures: unknown[] = [];
168
+ for (let start = 0; start < keys.length; start += UNLINK_BATCH) {
169
+ const batch = keys.slice(start, start + UNLINK_BATCH);
170
+ const settled = await Promise.allSettled(batch.map((key) => client.send('UNLINK', [key])));
171
+ settled.forEach((result, index) => {
172
+ const key = batch[index];
173
+ if (key === undefined) return;
174
+ if (result.status === 'fulfilled') deleted.add(key);
175
+ else failures.push(result.reason);
176
+ });
177
+ }
178
+ return { deleted, failures };
179
+ }
180
+
181
+ /** `ZREM` what died from every bucket that held it, `SWEEP_CONCURRENCY` commands in flight. */
182
+ export async function sweepBuckets(
183
+ client: RedisLike,
184
+ gone: ReadonlyMap<string, ReadonlySet<string>>,
185
+ ): Promise<void> {
186
+ const work: (() => Promise<unknown>)[] = [];
187
+ for (const [bucket, members] of gone) {
188
+ const list = [...members];
189
+ for (let start = 0; start < list.length; start += SWEEP_CHUNK) {
190
+ const chunk = list.slice(start, start + SWEEP_CHUNK);
191
+ work.push(() => client.send('ZREM', [bucket, ...chunk]));
192
+ }
193
+ }
194
+ let next = 0;
195
+ const worker = async (): Promise<void> => {
196
+ while (next < work.length) {
197
+ const task = work[next];
198
+ next += 1;
199
+ if (task !== undefined) await task();
200
+ }
201
+ };
202
+ await Promise.all(Array.from({ length: Math.min(SWEEP_CONCURRENCY, work.length) }, worker));
203
+ }