@ultimat3/cache 30.9.0 → 31.0.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.
@@ -0,0 +1,215 @@
1
+ // Single responsibility: the hop that carries cache invalidations between replicas over Redis
2
+ // pub/sub — what a fleet with `REDIS_URL` and no NATS publishes its busts on. The CLI boot picks
3
+ // it (`packages/cli/src/runtime-cache-bus.ts`); this file only speaks the protocol.
4
+
5
+ import { logger, renderThrowable } from '@ultimat3/core';
6
+ import { REDIS_CLIENT_OPTIONS } from '@ultimat3/core/redis';
7
+ import type { RedisClient } from 'bun';
8
+
9
+ export type PubSubListener = (message: string, channel: string) => void;
10
+
11
+ /** The part of a connection in subscriber mode this hop drives — structurally `Bun.RedisClient`. */
12
+ export interface RedisSubscriberLike {
13
+ subscribe(channel: string, listener: PubSubListener): Promise<number>;
14
+ unsubscribe(channel: string): Promise<void>;
15
+ /** Fired on EVERY connect, the first included. The only reconnect signal Bun gives. */
16
+ onconnect: ((this: RedisClient) => void) | null;
17
+ close(): void;
18
+ }
19
+
20
+ /**
21
+ * The publishing connection — a dedicated one, never core's shared client: its `onconnect` is how
22
+ * the hop hears the publisher is back, and a shared client's one slot is every holder's.
23
+ */
24
+ export interface RedisPublisherLike {
25
+ publish(channel: string, message: string): Promise<number>;
26
+ readonly connected: boolean;
27
+ /** Resolves once connected; against a server that is down, Bun's never settles. */
28
+ connect(): Promise<void>;
29
+ /** Fired on EVERY connect, the first included. */
30
+ onconnect: ((this: RedisClient) => void) | null;
31
+ close(): void;
32
+ }
33
+
34
+ /**
35
+ * How long a publish waits for a publisher that is not connected — ONCE per outage, never per
36
+ * publish: the client dials in the background with no offline queue, so a bust in a process's
37
+ * first milliseconds was refused (measured: a replica that booted and wrote at once told no peer),
38
+ * and a bust just after a restart likewise. Past this a publish refuses at once and the hop defers
39
+ * it; the publisher's `onconnect` then announces the return, and the deferred busts are sent.
40
+ */
41
+ export const PUBLISHER_CONNECT_WAIT_MS = 1_000;
42
+
43
+ export interface InvalidationSubscription {
44
+ unsubscribe(): void;
45
+ }
46
+
47
+ /**
48
+ * The shape the CLI's invalidation hop reads off a bus: `@ultimat3/realtime`'s `Transport` has it
49
+ * too, which is how one hop runs over either (realtime is tier 3; this package cannot name it).
50
+ */
51
+ export interface InvalidationBus {
52
+ readonly name: string;
53
+ publish(subject: string, payload: string): Promise<void>;
54
+ subscribe(subject: string, handler: (payload: string) => void): Promise<InvalidationSubscription>;
55
+ onReconnect(listener: () => void): () => void;
56
+ close(): Promise<void>;
57
+ }
58
+
59
+ export interface RedisPubSubOptions {
60
+ readonly publisher: RedisPublisherLike;
61
+ /**
62
+ * A connection of its own: one in subscriber mode refuses every other command, so handing it
63
+ * the shared client would refuse every cache read in the process.
64
+ */
65
+ readonly subscriber: RedisSubscriberLike;
66
+ }
67
+
68
+ /**
69
+ * Pub/sub over two connections. What Bun 1.4.4 does on a dropped connection, measured on Redis 7
70
+ * (`CLIENT KILL TYPE pubsub`): it reconnects and fires `onconnect`, the SERVER has forgotten the
71
+ * subscription (`PUBSUB NUMSUB` 0), and the CLIENT still holds the old listener — so a bare
72
+ * re-`SUBSCRIBE` delivers every message twice. Each reconnect therefore unsubscribes, subscribes
73
+ * afresh, and only then tells `onReconnect` — whose listener drops what this process holds,
74
+ * because whatever was published while it was away is gone (pub/sub keeps nothing). The first
75
+ * connect is announced as well, and so is every connect of the PUBLISHER: each is when a bust
76
+ * refused while it was away can be published (Redis restarted, the subscriber came back first,
77
+ * the settle was refused by a publisher still down — and nothing else would say it was back).
78
+ *
79
+ * Every SUBSCRIBE/UNSUBSCRIBE runs in one lane: two resubscribes that overlapped (a flapping
80
+ * connection), or a `subscribe` beside one, registered `dispatch` twice and delivered every bust
81
+ * twice.
82
+ */
83
+ export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
84
+ const { publisher, subscriber } = options;
85
+ const handlers = new Map<string, Set<(payload: string) => void>>();
86
+ const listeners = new Set<() => void>();
87
+ let closed = false;
88
+ /** This outage's one bounded wait for the publisher; cleared when it connects. */
89
+ let waiting: Promise<unknown> | undefined;
90
+ let lane: Promise<unknown> = Promise.resolve();
91
+ /** Runs `step` after every subscriber command queued before it, success or not. */
92
+ const inLane = <T>(step: () => Promise<T>): Promise<T> => {
93
+ const run = lane.then(step, step);
94
+ lane = run.catch(() => undefined);
95
+ return run;
96
+ };
97
+ const announce = (): void => {
98
+ for (const listener of listeners) listener();
99
+ };
100
+
101
+ const dispatch: PubSubListener = (message, channel) => {
102
+ for (const handler of handlers.get(channel) ?? []) handler(message);
103
+ };
104
+
105
+ /**
106
+ * Bun 1.4.4 THROWS, synchronously, `ERR_REDIS_INVALID_STATE` from `unsubscribe` on a client that
107
+ * holds no listener (measured) — a `.catch()` on its result never sees it, and the first
108
+ * subscribe of a fresh connection failed forever. Nothing to drop is the answer here.
109
+ */
110
+ const unsubscribeQuietly = async (channel: string): Promise<void> => {
111
+ try {
112
+ await subscriber.unsubscribe(channel);
113
+ } catch {
114
+ // Not subscribed, or the connection is away: either way no listener is left to double.
115
+ }
116
+ };
117
+
118
+ /**
119
+ * `channel` held by exactly one `dispatch`: UNSUBSCRIBE first, because Bun keeps a listener the
120
+ * server forgot. In the lane this is idempotent, so a `subscribe` queued behind a resubscribe
121
+ * that already covered its channel registers nothing twice.
122
+ */
123
+ const subscribeOnce = async (channel: string): Promise<void> => {
124
+ await unsubscribeQuietly(channel);
125
+ await subscriber.subscribe(channel, dispatch);
126
+ };
127
+
128
+ const resubscribe = async (): Promise<void> => {
129
+ try {
130
+ for (const channel of [...handlers.keys()]) await subscribeOnce(channel);
131
+ } catch (error) {
132
+ // The connection went again before the subscribe landed; its next `onconnect` retries.
133
+ logger.warn('cache.broadcast.resubscribe-failed', { error: renderThrowable(error) });
134
+ return;
135
+ }
136
+ announce();
137
+ };
138
+
139
+ // The first connect too: whatever the hop could not publish or subscribe before it is owed now.
140
+ subscriber.onconnect = () => {
141
+ if (!closed) void inLane(resubscribe);
142
+ };
143
+ publisher.onconnect = () => {
144
+ waiting = undefined;
145
+ if (!closed) announce();
146
+ };
147
+
148
+ return {
149
+ name: 'redis',
150
+ async publish(subject, payload) {
151
+ if (!publisher.connected) {
152
+ waiting ??= Promise.race([
153
+ publisher.connect().catch(() => undefined),
154
+ Bun.sleep(PUBLISHER_CONNECT_WAIT_MS),
155
+ ]);
156
+ await waiting;
157
+ }
158
+ await publisher.publish(subject, payload);
159
+ },
160
+ async subscribe(subject, handler) {
161
+ const held = handlers.get(subject) ?? new Set();
162
+ const first = held.size === 0;
163
+ held.add(handler);
164
+ handlers.set(subject, held);
165
+ if (first) {
166
+ try {
167
+ await inLane(() => subscribeOnce(subject));
168
+ } catch (error) {
169
+ held.delete(handler);
170
+ if (held.size === 0) handlers.delete(subject);
171
+ throw error;
172
+ }
173
+ }
174
+ return {
175
+ unsubscribe(): void {
176
+ held.delete(handler);
177
+ if (held.size > 0 || handlers.get(subject) !== held) return;
178
+ handlers.delete(subject);
179
+ if (!closed) void inLane(() => unsubscribeQuietly(subject));
180
+ },
181
+ };
182
+ },
183
+ onReconnect(listener) {
184
+ listeners.add(listener);
185
+ return () => listeners.delete(listener);
186
+ },
187
+ async close() {
188
+ closed = true;
189
+ listeners.clear();
190
+ handlers.clear();
191
+ subscriber.onconnect = null;
192
+ publisher.onconnect = null;
193
+ subscriber.close();
194
+ publisher.close();
195
+ },
196
+ };
197
+ }
198
+
199
+ /**
200
+ * The bus for `url`: two connections of its own, each built with core's options
201
+ * (`REDIS_CLIENT_OPTIONS` — no offline queue, never give up reconnecting). Two sockets per process
202
+ * on top of core's shared client: the price of a subscriber that takes no other command and a
203
+ * publisher whose return the hop can hear. `close()` closes both.
204
+ */
205
+ export function redisPubSubAt(url: string): InvalidationBus {
206
+ const subscriber = new Bun.RedisClient(url, { ...REDIS_CLIENT_OPTIONS });
207
+ const publisher = new Bun.RedisClient(url, { ...REDIS_CLIENT_OPTIONS });
208
+ const bus = redisPubSub({ publisher, subscriber });
209
+ // why: refused while the server is away like every command; the subscribe retry and the deferred
210
+ // publish are where the caller learns of it. Unhandled, it would kill a process booting before
211
+ // its Redis.
212
+ subscriber.connect().catch(() => undefined);
213
+ publisher.connect().catch(() => undefined);
214
+ return bus;
215
+ }
package/src/redis.ts CHANGED
@@ -1,14 +1,22 @@
1
1
  // Tier 2: shared cache over core's `redisClient()` (no client dependency — the runtime ships one).
2
- // A tag -> keys SET is maintained alongside every write so `invalidateTags` is ONE round
3
- // trip via a server-side script, not a KEYS scan. KEYS is O(n) and blocks the server; a
4
- // framework that ships it as the invalidation path is shipping an outage.
2
+ // A tag -> keys bucket is maintained alongside every write (`redis-buckets.ts`), so a bust reads
3
+ // what it must delete instead of scanning with KEYS — O(n) over the whole server, an outage
4
+ // shipped as the invalidation path.
5
5
 
6
6
  import type { Clock } from '@ultimat3/core';
7
7
  import { appVersion, logger, systemClock } from '@ultimat3/core';
8
8
  import type { DeadlineTimer } from '@ultimat3/core/outbound';
9
9
  import { redisClient } from '@ultimat3/core/redis';
10
- import { CacheDriverUnavailableError } from './errors';
10
+ import { CacheDriverUnavailableError, CacheTooLargeError } from './errors';
11
11
  import type { FenceScope } from './fence';
12
+ import {
13
+ bucketLayout,
14
+ joinBuckets,
15
+ lostMembership,
16
+ readBucket,
17
+ sweepBuckets,
18
+ unlinkAll,
19
+ } from './redis-buckets';
12
20
  import type { DeadlinedRedis } from './redis-deadline';
13
21
  import { DEFAULT_REDIS_COMMAND_TIMEOUT_MS, withinDeadline } from './redis-deadline';
14
22
  import { bumpGenerations, sampleGenerations } from './redis-fence';
@@ -22,7 +30,7 @@ import type {
22
30
  TierInvalidation,
23
31
  TtlJitter,
24
32
  } from './tiers';
25
- import { assertFiniteDurationMs, assertTtl, nowMs } from './tiers';
33
+ import { assertFiniteCapacity, assertFiniteDurationMs, assertTtl, nowMs } from './tiers';
26
34
  import { decodeCacheValue, encodeCacheValue } from './value-codec';
27
35
 
28
36
  /** The slice of Bun's Redis client this tier uses. Narrow on purpose: easy to fake in tests. */
@@ -50,7 +58,7 @@ export interface RedisTierOptions {
50
58
  readonly client?: RedisLike;
51
59
  /**
52
60
  * How long one value-path command may take, in ms. Default `DEFAULT_REDIS_COMMAND_TIMEOUT_MS`
53
- * (150). A miss is `X_CACHE_DRIVER_UNAVAILABLE` in `recentTierFailures()`, read as a cache miss,
61
+ * (150). A miss is `X_CACHE_DRIVER_UNAVAILABLE` as a `cache.tier_failure` event, read as a cache miss,
54
62
  * and parks the value path for `REDIS_PARK_MS`. A bust has its own, longer, unparked deadline.
55
63
  */
56
64
  readonly commandTimeoutMs?: number;
@@ -60,8 +68,26 @@ export interface RedisTierOptions {
60
68
  readonly clock?: Clock;
61
69
  /** TTL spread, in `[0, 1)`. Default `DEFAULT_TTL_JITTER_FRACTION`; `0` disables it. */
62
70
  readonly jitterFraction?: number;
63
- /** Injected so a jittered `EX` is deterministic; `() => 0` is the full lease. */
71
+ /** Injected so a jittered `PX` is deterministic; `() => 0` is the full lease. */
64
72
  readonly rng?: Rng;
73
+ /**
74
+ * The largest encoded value one `set` may write, in UTF-8 bytes. Default
75
+ * `DEFAULT_REDIS_MAX_VALUE_BYTES` (1 MiB). Over it is `X_CACHE_TOO_LARGE`, as the LRU's
76
+ * `maxBytes` is: a multi-megabyte value blocks the shared server for every replica.
77
+ */
78
+ readonly maxValueBytes?: number;
79
+ }
80
+
81
+ /** 1 MiB. A value past it costs the shared server more than the load it saves. */
82
+ export const DEFAULT_REDIS_MAX_VALUE_BYTES = 1_048_576;
83
+
84
+ const utf8 = new TextEncoder();
85
+
86
+ /** Refuse a value over the tier's budget. Cheap when it is far under: bytes <= 3 × UTF-16 length. */
87
+ function assertWithinBudget(key: string, text: string, maxBytes: number): void {
88
+ if (text.length * 3 <= maxBytes) return;
89
+ const bytes = utf8.encode(text).byteLength;
90
+ if (bytes > maxBytes) throw new CacheTooLargeError({ key, bytes, maxBytes, tier: 'redis' });
65
91
  }
66
92
 
67
93
  /**
@@ -85,72 +111,6 @@ interface StoredEntry {
85
111
  readonly t: readonly string[];
86
112
  }
87
113
 
88
- /**
89
- * Read the tag sets out. It deletes nothing at all, and both halves of that are deliberate.
90
- *
91
- * A script may only touch keys it was handed in `KEYS`, and the members of a tag set are not
92
- * among them: they are value keys hashing to slots this node may not even own. `DEL`ing them from
93
- * inside the script therefore raised "attempted to access a non-local key in a cluster node" on
94
- * Redis Cluster and in Dragonfly's strict mode — swallowed into `report.errors`, so a bust read
95
- * as "partial", the write that triggered it still succeeded, and stale rows served until TTL.
96
- *
97
- * The buckets themselves used to go, atomically with the `SMEMBERS` that read them. That made one
98
- * failure permanent: a refused `DEL` in the client-side batch left its member with no bucket to
99
- * be found in again, so the retry the error asks for answered `keys: []` and those rows served
100
- * until their own TTL. The tier now `SREM`s exactly the members it managed to delete, which is
101
- * strictly more precise — a member added by a concurrent write between the two halves is not in
102
- * that list, so it keeps its membership instead of being silently orphaned by the bust.
103
- *
104
- * That is HALF the cluster story. The other half is `KEYS` itself: one `EVAL` carrying every tag's
105
- * buckets is rejected with `CROSSSLOT` before the script runs, because `<ns>:t:post` and
106
- * `<ns>:t:user` hash to different slots. So the buckets carry a `{entity}` hash tag and the tier
107
- * issues ONE call per tag — every key of a call then hashes on the same entity, by construction.
108
- */
109
- const INVALIDATE_SCRIPT = `
110
- local removed = {}
111
- for i, tagKey in ipairs(KEYS) do
112
- local members = redis.call('SMEMBERS', tagKey)
113
- for _, key in ipairs(members) do
114
- table.insert(removed, key)
115
- end
116
- end
117
- return removed
118
- `.trim();
119
-
120
- /**
121
- * Join a value key to one tag set, and never let that set outlive its members by more than the
122
- * grace — one key in `KEYS`, so it is slot-local under every topology.
123
- *
124
- * A tag set with no expiry is unbounded. Value keys die after five minutes; their membership never
125
- * did, so after a month `SMEMBERS <ns>:t:{post}` returned several million dead keys — hundreds of
126
- * milliseconds of blocked event loop, a multi-megabyte reply, and millions of client-side `DEL`s.
127
- * One publish became a Redis outage, and the set itself was unbounded memory in the shared store.
128
- *
129
- * The TTL only ever GROWS, which is the half that has to be atomic: a 60s member must not shorten
130
- * a bucket a 1h member is in, or that value key becomes unreachable by tag and serves stale until
131
- * its own lease runs out. `EXPIRE ... GT` says exactly this in one command but treats a key with
132
- * no TTL as infinite — so a FRESH bucket would keep no expiry at all, which is the bug being
133
- * fixed. Read-then-set inside the script covers both cases, and needs no Redis 7.
134
- */
135
- const TAG_MEMBER_SCRIPT = `
136
- redis.call('SADD', KEYS[1], ARGV[1])
137
- local ttl = tonumber(ARGV[2])
138
- local current = redis.call('TTL', KEYS[1])
139
- if current < 0 or current < ttl then
140
- redis.call('EXPIRE', KEYS[1], ttl)
141
- end
142
- return 1
143
- `.trim();
144
-
145
- /** Concurrent `DEL`s per flush. Bun pipelines them, so this bounds memory, not round trips. */
146
- const DELETE_BATCH = 128;
147
-
148
- /** Seconds a tag set outlives its newest member. See `TAG_MEMBER_SCRIPT`. */
149
- const TAG_TTL_GRACE_SECONDS = 60;
150
-
151
- const toStrings = (value: unknown): string[] =>
152
- Array.isArray(value) ? value.map((item) => String(item)) : [];
153
-
154
114
  /**
155
115
  * What `PTTL` said about a key the `GET` beside it just answered for. `-1` and `-2` are sentinels,
156
116
  * not durations — and they mean different things here: `-1` is a key with no lease (one written
@@ -166,24 +126,13 @@ function leaseFrom(reply: unknown): Lease {
166
126
  return pttl > 0 ? { ms: pttl } : { kind: 'none' };
167
127
  }
168
128
 
169
- /**
170
- * `SISMEMBER` answered a literal `0`, and nothing else counts. A reply this cannot read is not
171
- * evidence: treating one as "gone" deletes every value the tier writes, which is a cache that
172
- * never caches.
173
- */
174
- function saysAbsent(reply: unknown): boolean {
175
- if (typeof reply === 'number') return reply === 0;
176
- if (typeof reply === 'string') return Number(reply) === 0;
177
- return false;
178
- }
179
-
180
129
  /**
181
130
  * The first refusal, verbatim when it is one — `fanOut` renders `message` into `report.errors`, so
182
131
  * the operator sees which key the store refused rather than a count.
183
132
  *
184
133
  * The `fix:` is the call, not a command: there is no `x cache` in this build, and the retry is one
185
134
  * line of the app's own code. It is safe to repeat because every key the store refused kept its
186
- * tag membership — the bust `SREM`s only what it deleted.
135
+ * tag membership — the bust `ZREM`s only what it deleted.
187
136
  */
188
137
  function raiseSweepFailure(failures: readonly unknown[], attempted: number): never {
189
138
  const first = failures[0];
@@ -203,6 +152,11 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
203
152
  options.defaultTtlMs ?? 300_000,
204
153
  );
205
154
  const clock = options.clock ?? systemClock;
155
+ const maxValueBytes = assertFiniteCapacity(
156
+ 'redis',
157
+ 'maxValueBytes',
158
+ options.maxValueBytes ?? DEFAULT_REDIS_MAX_VALUE_BYTES,
159
+ );
206
160
  const jitter: TtlJitter = {
207
161
  ...(options.jitterFraction === undefined ? {} : { jitterFraction: options.jitterFraction }),
208
162
  ...(options.rng === undefined ? {} : { rng: options.rng }),
@@ -229,53 +183,7 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
229
183
  // A bust skips the park: skipped for a stall, it leaves stale rows serving until TTL.
230
184
  const bustConn = (): RedisLike => views().bust;
231
185
 
232
- const valueKey = (key: string): string => `${ns}:c:${key}`;
233
- // `{entity}` is a Redis Cluster hash tag, not decoration: it is what makes a row's bucket and
234
- // its collection's bucket hash to ONE slot, so a script may take both in `KEYS`.
235
- const tagKey = (owned: CacheTag): string =>
236
- owned.id === undefined ? `${ns}:t:{${owned.entity}}` : `${ns}:t:{${owned.entity}}:${owned.id}`;
237
- // Every key carrying ANY tag of this entity — `LruCache`'s `entityIndex`, on the wire. A SECOND
238
- // bucket rather than a reuse of `tagKey({ entity })`, and that is the whole fix: one key serving
239
- // both roles is what made a row bust over-reach.
240
- const entityKey = (entity: string): string => `${ns}:e:{${entity}}`;
241
-
242
- // A write joins the bucket of the tag it declared, plus its entity's index — so a collection
243
- // bust reaches a row-tagged key without that row's tag having to live in the collection's bucket.
244
- const writeBucketsFor = (owned: CacheTag): string[] => [tagKey(owned), entityKey(owned.entity)];
245
-
246
- /**
247
- * `tagMatches` expressed in keys, which is the point: the LRU and the request memo both answer a
248
- * bust through that predicate and this tier did not.
249
- *
250
- * A COLLECTION bust matches every tag of the entity, so it reads the entity index. A ROW bust
251
- * matches its own tag and the bare collection tag ONLY — `post:2` survives a bust of `post:1` —
252
- * so it reads the row's bucket and the collection tag's, never the index. Reusing the collection
253
- * bucket as the index meant `invalidateTags([tag('post', '1')])` returned every post-tagged key
254
- * in the store and deleted them: one row write emptied the shared tier for that whole entity,
255
- * while the in-process tier one rung closer kept exactly the row that had changed.
256
- *
257
- * A collection bust also reads `tagKey(owned)`, a strict subset of the index in this layout. That
258
- * extra `SMEMBERS` is bought deliberately: a deployment pinned to `buildId: null` upgrades into
259
- * this layout with the old two-role buckets still leased, and reading them keeps a collection
260
- * bust from MISSING those keys. Over-reading a subset costs a round trip; under-reading is stale.
261
- */
262
- const bustBucketsFor = (owned: CacheTag): string[] =>
263
- owned.id === undefined
264
- ? [entityKey(owned.entity), tagKey(owned)]
265
- : [tagKey(owned), tagKey({ entity: owned.entity })];
266
-
267
- /**
268
- * The buckets a bust CLEANS UP, which is not the set it reads — and the asymmetry is the point.
269
- *
270
- * A row bust must not READ the entity index: it holds every key of the entity, so the bust would
271
- * delete them all. It must still SREM from it. `set` joins the index on every write, so a row
272
- * bust that deletes a value key and leaves its membership there leaves a corpse no later bust
273
- * can reach — while `TAG_MEMBER_SCRIPT` renews that index's lease on every write, which is the
274
- * unbounded `SMEMBERS` the lease exists to prevent, rebuilt out of dead keys. Removing a member
275
- * cannot over-reach the way reading one can: only what this bust actually deleted leaves.
276
- */
277
- const sweepBucketsFor = (owned: CacheTag): string[] =>
278
- owned.id === undefined ? [] : [entityKey(owned.entity)];
186
+ const { valueKey, writeBucketsFor, bustBucketsFor, sweepBucketsFor } = bucketLayout(ns);
279
187
 
280
188
  return {
281
189
  name: 'redis',
@@ -320,12 +228,13 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
320
228
  },
321
229
 
322
230
  /**
323
- * The value key gets a lease and so does every bucket it joins — see `TAG_MEMBER_SCRIPT`.
231
+ * The value key gets a lease, and every bucket it joins is pruned and re-leased
232
+ * (`joinBuckets`).
324
233
  *
325
234
  * The buckets are joined FIRST and the membership is re-checked LAST, because this write and
326
235
  * a bust of the same tag are two clients with no lock between them. Writing the value first
327
- * left a window where the bust's `SMEMBERS` found an empty bucket and the value it should
328
- * have cleared survived its own invalidation for the full TTL. Joining first moves the window
236
+ * left a window where the bust's read found an empty bucket and the value it should have
237
+ * cleared survived its own invalidation for the full TTL. Joining first moves the window
329
238
  * somewhere observable: `invalidateTags` removes a member only when it deleted that member's
330
239
  * value key, so a membership gone by the time the `SET` lands means this write was busted
331
240
  * while it was in the air — and the value goes with it, because a row nothing can reach by
@@ -335,29 +244,21 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
335
244
  const tags = setOptions?.tags ?? [];
336
245
  const ttlMs = assertTtl(key, setOptions?.ttlMs ?? defaultTtlMs, 'redis', jitter);
337
246
  const payload: StoredEntry = { v: value, t: tags.map(serializeTag) };
338
- // Before any bucket is joined: an unencodable value is refused with nothing left behind.
247
+ // Before any bucket is joined: an unencodable or oversized value is refused with nothing
248
+ // left behind.
339
249
  const text = encodeCacheValue(payload, { key, tier: 'redis' });
250
+ assertWithinBudget(key, text, maxValueBytes);
340
251
  const stored = valueKey(key);
341
- // `PX`, not `EX`: the value's lease is spent in the milliseconds it was validated and
342
- // jittered in. `Math.ceil(ttlMs / 1000)` honoured a 1,001ms lease as 2s — rounding toward
343
- // STALENESS, the opposite of what the jitter beside it protects, and a disagreement with
344
- // the LRU tier about when the same entry dies. The BUCKET keeps whole seconds and keeps
345
- // rounding up: a tag set has to outlive every member it holds.
346
- const bucketTtlSeconds = String(Math.max(1, Math.ceil(ttlMs / 1000)) + TAG_TTL_GRACE_SECONDS);
347
252
  // Deduped: two tags of one entity share the entity index, and joining it twice is a round
348
- // trip that changes nothing. Issued together — one key each, so still slot-local.
253
+ // trip that changes nothing.
349
254
  const buckets = [...new Set(tags.flatMap(writeBucketsFor))];
350
- await Promise.all(
351
- buckets.map((bucket) =>
352
- conn().send('EVAL', [TAG_MEMBER_SCRIPT, '1', bucket, stored, bucketTtlSeconds]),
353
- ),
354
- );
255
+ await joinBuckets(conn(), buckets, stored, nowMs(clock), ttlMs);
256
+ // `PX`, not `EX`: the value's lease is spent in the milliseconds it was validated and
257
+ // jittered in. A whole-second `EX` honoured a 1,001ms lease as 2s — rounding toward
258
+ // staleness, and a disagreement with the LRU tier about when the same entry dies.
355
259
  await conn().send('SET', [stored, text, 'PX', String(Math.ceil(ttlMs))]);
356
260
  if (buckets.length === 0) return;
357
- const membership = await Promise.all(
358
- buckets.map((bucket) => conn().send('SISMEMBER', [bucket, stored])),
359
- );
360
- if (membership.some(saysAbsent)) await conn().send('DEL', [stored]);
261
+ if (await lostMembership(conn(), buckets, stored)) await conn().send('DEL', [stored]);
361
262
  },
362
263
 
363
264
  async del(key: string): Promise<void> {
@@ -368,69 +269,50 @@ export function redisTier(options: RedisTierOptions = {}): CacheTier {
368
269
  fence: (scope: FenceScope) => sampleGenerations(conn(), ns, clock, scope),
369
270
 
370
271
  /**
371
- * ONE script call per tag, never one for the batch. Every key a call is handed comes from a
372
- * single tag and therefore carries the same `{entity}` hash tag, so it is one slot on Redis
373
- * Cluster; the batched form was rejected with `CROSSSLOT` before the script ever ran, which
374
- * landed in `report.errors` as a partial bust with stale rows serving until TTL.
272
+ * Read every bucket the tags match, a page per round trip and the buckets concurrently;
273
+ * `UNLINK` what they held, one key per command; then `ZREM` exactly what died. Every command
274
+ * names one key, so a bust is slot-local on Redis Cluster whatever tags it carries.
375
275
  */
376
276
  async invalidateTags(tags: readonly CacheTag[]): Promise<TierInvalidation> {
377
277
  const claimed = new Set<string>();
378
278
  const perTag: { read: string[]; sweep: string[] }[] = [];
379
279
  for (const owned of tags) {
380
- // A bucket already claimed by an earlier tag is dropped rather than re-sent: a collection
381
- // tag and one of its rows overlap, and the second call would read the same members.
280
+ // A bucket already claimed by an earlier tag is not read twice: a collection tag and one
281
+ // of its rows overlap.
382
282
  const read = bustBucketsFor(owned).filter((bucket) => !claimed.has(bucket));
383
283
  for (const bucket of read) claimed.add(bucket);
384
- if (read.length > 0) perTag.push({ read, sweep: [...read, ...sweepBucketsFor(owned)] });
284
+ if (read.length > 0) perTag.push({ read, sweep: sweepBucketsFor(owned) });
385
285
  }
386
286
  if (perTag.length === 0) return { tier: 'redis', keys: [] };
387
287
  // Before the buckets are read, and awaited: see `bumpGenerations` for why the order is the
388
288
  // guarantee. A refusal here rejects the bust into `report.errors` with nothing deleted, so
389
289
  // the retry it asks for repeats the whole thing.
390
290
  await bumpGenerations(bustConn(), ns, tags);
391
- const replies = await Promise.all(
392
- perTag.map(({ read }) =>
393
- bustConn().send('EVAL', [INVALIDATE_SCRIPT, String(read.length), ...read]),
394
- ),
395
- );
396
- // A member may sit in two tag sets; deleting it twice is harmless but reporting it twice
291
+ const buckets = [...claimed];
292
+ const pages = await Promise.all(buckets.map((bucket) => readBucket(bustConn(), bucket)));
293
+ const held = new Map(buckets.map((bucket, i) => [bucket, pages[i] ?? []]));
294
+ // A member may sit in two buckets; deleting it twice is harmless but reporting it twice
397
295
  // makes the `/_x` panel overstate what cleared.
398
- const members = [...new Set(replies.flatMap(toStrings))];
399
- const deleted = new Set<string>();
400
- const failures: unknown[] = [];
401
- for (let start = 0; start < members.length; start += DELETE_BATCH) {
402
- // One key per DEL — always slot-local. Issued together so the batch costs one round trip.
403
- // `allSettled`, because which ones died decides what leaves the buckets below.
404
- const batch = members.slice(start, start + DELETE_BATCH);
405
- const settled = await Promise.allSettled(
406
- batch.map((member) => bustConn().send('DEL', [member])),
407
- );
408
- settled.forEach((result, index) => {
409
- const member = batch[index];
410
- if (member === undefined) return;
411
- if (result.status === 'fulfilled') deleted.add(member);
412
- else failures.push(result.reason);
413
- });
414
- }
296
+ const members = [...new Set(pages.flat())];
297
+ const { deleted, failures } = await unlinkAll(bustConn(), members);
415
298
 
416
- // Only what actually died leaves its bucket. A member the store refused to delete keeps its
417
- // membership, so the retry `report.errors` asks for still finds it; the script no longer
418
- // drops the bucket, which is what made that failure permanent.
419
- for (let i = 0; i < perTag.length; i += 1) {
420
- const gone = [...new Set(toStrings(replies[i]))].filter((member) => deleted.has(member));
421
- for (const bucket of perTag[i]?.sweep ?? []) {
422
- for (let start = 0; start < gone.length; start += DELETE_BATCH) {
423
- await bustConn().send('SREM', [bucket, ...gone.slice(start, start + DELETE_BATCH)]);
424
- }
299
+ // Only what actually died leaves its buckets. A member the store refused to delete keeps its
300
+ // membership, so the retry `report.errors` asks for still finds it.
301
+ const gone = new Map<string, Set<string>>();
302
+ for (const { read, sweep } of perTag) {
303
+ const died = read.flatMap((bucket) => held.get(bucket) ?? []).filter((m) => deleted.has(m));
304
+ if (died.length === 0) continue;
305
+ for (const bucket of sweep) {
306
+ const into = gone.get(bucket) ?? new Set<string>();
307
+ for (const member of died) into.add(member);
308
+ gone.set(bucket, into);
425
309
  }
426
310
  }
311
+ await sweepBuckets(bustConn(), gone);
427
312
 
428
313
  if (failures.length > 0) raiseSweepFailure(failures, members.length);
429
- const stripped = [...deleted].map((key) => key.slice(`${ns}:c:`.length));
314
+ const stripped = [...deleted].map((key) => key.slice(valueKey('').length));
430
315
  return { tier: 'redis', keys: stripped };
431
316
  },
432
317
  };
433
318
  }
434
-
435
- export const REDIS_INVALIDATE_SCRIPT = INVALIDATE_SCRIPT;
436
- export const REDIS_TAG_MEMBER_SCRIPT = TAG_MEMBER_SCRIPT;
package/src/tags.ts CHANGED
@@ -125,8 +125,7 @@ export function resetDeclaredTags(): void {
125
125
  * afterAll(restoreTags);
126
126
  *
127
127
  * This is the shape every process-global registry in this package is undone with — `isolateGraph()`
128
- * in `graph.ts`, `isolateTiers()` in `invalidate.ts`, `isolateTierFailures()` in
129
- * `tier-failures.ts` — and one reason covers all four: `@ultimat3/testing`'s leak guard compares
128
+ * in `graph.ts`, `isolateTiers()` in `invalidate.ts` — and one reason covers all three: `@ultimat3/testing`'s leak guard compares
130
129
  * its before/after samples for ADDITIONS only, so a file that DELETES what a neighbour registered
131
130
  * is invisible to it and surfaces instead as a failure in an innocent file with nothing in it to
132
131
  * explain the missing state. A reset in a test file is the one leak no mechanism catches for you.