@ultimat3/cache 31.19.0 → 31.21.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/CLAUDE.md CHANGED
@@ -210,7 +210,7 @@ Tier 1. Tagged caching + THE invalidation graph.
210
210
  | `lru.ts` | byte-budgeted LRU (linked list + map + tag index) |
211
211
  | `value-codec.ts` | the one value encoding every tier stores and decodes |
212
212
  | `redis.ts` | the shared tier over core's `redisClient()` (`@ultimat3/core/redis`, never `Bun.redis`), build-namespaced keys, the value budget, the write/bust order |
213
- | `redis-pubsub.ts` | `redisPubSub`/`redisPubSubAt`: invalidations between replicas over Redis pub/sub, resubscribe on every connect |
213
+ | `redis-pubsub.ts` | `redisPubSub`/`redisPubSubAt`: invalidations between replicas over Redis pub/sub, resubscribe on every connect, each command bounded, a refused resubscribe retried on a backoff |
214
214
  | `redis-deadline.ts` | `withinDeadline`: a per-command deadline (150 ms, `commandTimeoutMs`), a 5 s park of the value path after one is missed, and the bust view that skips the park on its own 1,000 ms |
215
215
  | `cdn.ts` | `Cache-Control`/`Surrogate-Key` emission, `surrogateKeys`, the purge key list, the `PurgeDriver` seam |
216
216
  | `purge-http.ts` | the HTTP half both remote drivers share: one POST, batching, key guard, and core's retryable table re-exported |
package/README.md CHANGED
@@ -404,7 +404,13 @@ registers the listener twice — then fires `onReconnect`; the CLI's listener ca
404
404
  busts it deferred. A publisher connect fires `onReconnect` too: after a Redis restart the
405
405
  subscriber may be back first, and the deferred busts are refused until the publisher is. A publish
406
406
  on a disconnected publisher waits up to `PUBLISHER_CONNECT_WAIT_MS` (1 s) once per outage, then
407
- refuses at once and is deferred. The channel is the hop's one subject,
407
+ refuses at once and is deferred. Each SUBSCRIBE/UNSUBSCRIBE is bounded
408
+ (`PUBSUB_COMMAND_TIMEOUT_MS`, 1 s), and a resubscribe refused while the connection stays up is
409
+ retried on a backoff (250 ms doubling to 10 s, full jitter) until it lands — after `CLIENT KILL` no
410
+ second `onconnect` comes. `schedule` and `resubscribeRetryMs` are injectable, so a test fires both
411
+ by hand. Every connect also sends `CLIENT SETNAME connectionName` before subscribing —
412
+ `redisPubSubAt` passes `cacheBusConnectionName()` (`x-cache-bus:<pid>`), so `CLIENT LIST TYPE
413
+ pubsub` says which replica a subscription is. The channel is the hop's one subject,
408
414
  unprefixed: old and new builds of one app must hear each other mid-rollout.
409
415
 
410
416
  **`flushProcessTiers(source)` is the repair for a process that cannot know what it missed** — its
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cache",
3
- "version": "31.19.0",
3
+ "version": "31.21.0",
4
4
  "description": "Tagged caching: request memo, LRU, Redis, CDN — one invalidation graph",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -43,6 +43,6 @@
43
43
  "test": "bun test"
44
44
  },
45
45
  "dependencies": {
46
- "@ultimat3/core": "31.19.0"
46
+ "@ultimat3/core": "31.21.0"
47
47
  }
48
48
  }
package/src/index.ts CHANGED
@@ -76,7 +76,7 @@ export type {
76
76
  RedisPubSubOptions,
77
77
  RedisSubscriberLike,
78
78
  } from './redis-pubsub';
79
- export { redisPubSub, redisPubSubAt } from './redis-pubsub';
79
+ export { cacheBusConnectionName, redisPubSub, redisPubSubAt } from './redis-pubsub';
80
80
  export type {
81
81
  Embedding,
82
82
  SemanticCache,
@@ -2,9 +2,10 @@
2
2
  // pub/sub — what a fleet with `REDIS_URL` and no NATS publishes its busts on. The CLI boot picks
3
3
  // it (`packages/cli/src/runtime-cache-bus.ts`); this file only speaks the protocol.
4
4
 
5
- import { logger, renderThrowable } from '@ultimat3/core';
5
+ import { backoffDelay, logger, renderThrowable, type Scheduler } from '@ultimat3/core';
6
6
  import { REDIS_CLIENT_OPTIONS } from '@ultimat3/core/redis';
7
7
  import type { RedisClient } from 'bun';
8
+ import { CacheDriverUnavailableError } from './errors';
8
9
 
9
10
  export type PubSubListener = (message: string, channel: string) => void;
10
11
 
@@ -12,6 +13,8 @@ export type PubSubListener = (message: string, channel: string) => void;
12
13
  export interface RedisSubscriberLike {
13
14
  subscribe(channel: string, listener: PubSubListener): Promise<number>;
14
15
  unsubscribe(channel: string): Promise<void>;
16
+ /** How `connectionName` is sent (`CLIENT SETNAME`). Absent, the connection stays anonymous. */
17
+ send?(command: string, args: string[]): Promise<unknown>;
15
18
  /** Fired on EVERY connect, the first included. The only reconnect signal Bun gives. */
16
19
  onconnect: ((this: RedisClient) => void) | null;
17
20
  close(): void;
@@ -40,6 +43,22 @@ export interface RedisPublisherLike {
40
43
  */
41
44
  export const PUBLISHER_CONNECT_WAIT_MS = 1_000;
42
45
 
46
+ /**
47
+ * How long one SUBSCRIBE or UNSUBSCRIBE may hold the lane. A command sent on a socket that died
48
+ * under it never answers, and unbounded it stalled every resubscribe queued behind it: a replica
49
+ * that never dropped what it held. A healthy server answers in single milliseconds.
50
+ */
51
+ export const PUBSUB_COMMAND_TIMEOUT_MS = 1_000;
52
+
53
+ /** 250 ms doubling to 10 s, full jitter: a refused resubscribe is asked again, never in lockstep. */
54
+ const defaultResubscribeRetryMs = (attempt: number): number =>
55
+ backoffDelay({ attempt, base: 250, max: 10_000, jitter: 'full' });
56
+
57
+ const timeoutSchedule: Scheduler = (fn, ms) => {
58
+ const handle = setTimeout(fn, ms);
59
+ return () => clearTimeout(handle);
60
+ };
61
+
43
62
  export interface InvalidationSubscription {
44
63
  unsubscribe(): void;
45
64
  }
@@ -63,8 +82,26 @@ export interface RedisPubSubOptions {
63
82
  * the shared client would refuse every cache read in the process.
64
83
  */
65
84
  readonly subscriber: RedisSubscriberLike;
85
+ /**
86
+ * Arms each command's deadline, each resubscribe retry and the publisher's connect wait. Injected
87
+ * so none of them waits in a test.
88
+ */
89
+ readonly schedule?: Scheduler;
90
+ /** The wait before resubscribe `attempt` (1-based) after a refusal with the connection up. */
91
+ readonly resubscribeRetryMs?: (attempt: number) => number;
92
+ /**
93
+ * `CLIENT SETNAME` for the subscriber, sent on EVERY connect: a reconnect is a new server-side
94
+ * connection with no name. `redisPubSubAt` passes `cacheBusConnectionName()`.
95
+ */
96
+ readonly connectionName?: string;
66
97
  }
67
98
 
99
+ /**
100
+ * The subscriber's name in `CLIENT LIST`: which process a pub/sub connection is, so an operator —
101
+ * and the live suite — can ask the server whether THIS replica is subscribed, not whether anyone is.
102
+ */
103
+ export const cacheBusConnectionName = (): string => `x-cache-bus:${String(process.pid)}`;
104
+
68
105
  /**
69
106
  * Pub/sub over two connections. What Bun 1.4.4 does on a dropped connection, measured on Redis 7
70
107
  * (`CLIENT KILL TYPE pubsub`): it reconnects and fires `onconnect`, the SERVER has forgotten the
@@ -78,10 +115,14 @@ export interface RedisPubSubOptions {
78
115
  *
79
116
  * Every SUBSCRIBE/UNSUBSCRIBE runs in one lane: two resubscribes that overlapped (a flapping
80
117
  * connection), or a `subscribe` beside one, registered `dispatch` twice and delivered every bust
81
- * twice.
118
+ * twice. Each command in it is bounded (`PUBSUB_COMMAND_TIMEOUT_MS`), and a resubscribe refused
119
+ * while the connection stays UP is retried on a backoff: measured after `CLIENT KILL`, no second
120
+ * `onconnect` came, and the one logged refusal left the replica deaf to every peer bust.
82
121
  */
83
122
  export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
84
123
  const { publisher, subscriber } = options;
124
+ const schedule = options.schedule ?? timeoutSchedule;
125
+ const retryMs = options.resubscribeRetryMs ?? defaultResubscribeRetryMs;
85
126
  const handlers = new Map<string, Set<(payload: string) => void>>();
86
127
  const listeners = new Set<() => void>();
87
128
  let closed = false;
@@ -94,6 +135,35 @@ export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
94
135
  lane = run.catch(() => undefined);
95
136
  return run;
96
137
  };
138
+ /** `command` answered, or refused once its deadline passes; a late answer changes nothing. */
139
+ const bounded = <T>(command: string, run: () => Promise<T>): Promise<T> =>
140
+ new Promise<T>((resolve, reject) => {
141
+ const cancel = schedule(() => {
142
+ reject(
143
+ new CacheDriverUnavailableError({
144
+ driver: 'redis',
145
+ cause: `${command} on the pub/sub connection did not answer within ${String(PUBSUB_COMMAND_TIMEOUT_MS)} ms; the next subscriber command was sent`,
146
+ fix: 'redis-cli -u "$REDIS_URL" CLIENT LIST TYPE pubsub — a resubscribe is retried on its own once the server answers',
147
+ }),
148
+ );
149
+ }, PUBSUB_COMMAND_TIMEOUT_MS);
150
+ let sent: Promise<T>;
151
+ try {
152
+ sent = run();
153
+ } catch (error) {
154
+ sent = Promise.reject(error);
155
+ }
156
+ sent.then(
157
+ (answer) => {
158
+ cancel();
159
+ resolve(answer);
160
+ },
161
+ (error: unknown) => {
162
+ cancel();
163
+ reject(error);
164
+ },
165
+ );
166
+ });
97
167
  const announce = (): void => {
98
168
  for (const listener of listeners) listener();
99
169
  };
@@ -109,7 +179,7 @@ export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
109
179
  */
110
180
  const unsubscribeQuietly = async (channel: string): Promise<void> => {
111
181
  try {
112
- await subscriber.unsubscribe(channel);
182
+ await bounded('UNSUBSCRIBE', () => subscriber.unsubscribe(channel));
113
183
  } catch {
114
184
  // Not subscribed, or the connection is away: either way no listener is left to double.
115
185
  }
@@ -122,23 +192,42 @@ export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
122
192
  */
123
193
  const subscribeOnce = async (channel: string): Promise<void> => {
124
194
  await unsubscribeQuietly(channel);
125
- await subscriber.subscribe(channel, dispatch);
195
+ await bounded('SUBSCRIBE', () => subscriber.subscribe(channel, dispatch));
126
196
  };
127
197
 
128
- const resubscribe = async (): Promise<void> => {
198
+ /** The pending retry's canceller; a reconnect or `close` drops it. */
199
+ let cancelRetry: (() => void) | undefined;
200
+ const resubscribe = async (attempt: number): Promise<void> => {
129
201
  try {
202
+ const { connectionName } = options;
203
+ const send = subscriber.send?.bind(subscriber);
204
+ if (connectionName !== undefined && send !== undefined) {
205
+ await bounded('CLIENT SETNAME', () => send('CLIENT', ['SETNAME', connectionName]));
206
+ }
130
207
  for (const channel of [...handlers.keys()]) await subscribeOnce(channel);
131
208
  } 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) });
209
+ // The connection may well stay up (measured after `CLIENT KILL`): no `onconnect` would come,
210
+ // so asking again is this hop's job. A real drop's `onconnect` supersedes the retry.
211
+ logger.warn('cache.broadcast.resubscribe-failed', { error: renderThrowable(error), attempt });
212
+ if (!closed) {
213
+ cancelRetry = schedule(() => {
214
+ cancelRetry = undefined;
215
+ if (!closed) void inLane(() => resubscribe(attempt + 1));
216
+ }, retryMs(attempt));
217
+ }
134
218
  return;
135
219
  }
220
+ // A retry an older refusal armed has nothing left to restore.
221
+ cancelRetry?.();
222
+ cancelRetry = undefined;
136
223
  announce();
137
224
  };
138
225
 
139
226
  // The first connect too: whatever the hop could not publish or subscribe before it is owed now.
140
227
  subscriber.onconnect = () => {
141
- if (!closed) void inLane(resubscribe);
228
+ cancelRetry?.();
229
+ cancelRetry = undefined;
230
+ if (!closed) void inLane(() => resubscribe(1));
142
231
  };
143
232
  publisher.onconnect = () => {
144
233
  waiting = undefined;
@@ -149,10 +238,15 @@ export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
149
238
  name: 'redis',
150
239
  async publish(subject, payload) {
151
240
  if (!publisher.connected) {
152
- waiting ??= Promise.race([
153
- publisher.connect().catch(() => undefined),
154
- Bun.sleep(PUBLISHER_CONNECT_WAIT_MS),
155
- ]);
241
+ // The connect or the bound, whichever is first; the other changes nothing.
242
+ waiting ??= new Promise<undefined>((resolve) => {
243
+ const cancel = schedule(() => resolve(undefined), PUBLISHER_CONNECT_WAIT_MS);
244
+ const connected = (): void => {
245
+ cancel();
246
+ resolve(undefined);
247
+ };
248
+ publisher.connect().then(connected, connected);
249
+ });
156
250
  await waiting;
157
251
  }
158
252
  await publisher.publish(subject, payload);
@@ -186,6 +280,8 @@ export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
186
280
  },
187
281
  async close() {
188
282
  closed = true;
283
+ cancelRetry?.();
284
+ cancelRetry = undefined;
189
285
  listeners.clear();
190
286
  handlers.clear();
191
287
  subscriber.onconnect = null;
@@ -200,12 +296,20 @@ export function redisPubSub(options: RedisPubSubOptions): InvalidationBus {
200
296
  * The bus for `url`: two connections of its own, each built with core's options
201
297
  * (`REDIS_CLIENT_OPTIONS` — no offline queue, never give up reconnecting). Two sockets per process
202
298
  * 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.
299
+ * publisher whose return the hop can hear. `close()` closes both. `connectionName` defaults to
300
+ * `cacheBusConnectionName()`; a suite running two buses in one process names each its own.
204
301
  */
205
- export function redisPubSubAt(url: string): InvalidationBus {
302
+ export function redisPubSubAt(
303
+ url: string,
304
+ options: { readonly connectionName?: string } = {},
305
+ ): InvalidationBus {
206
306
  const subscriber = new Bun.RedisClient(url, { ...REDIS_CLIENT_OPTIONS });
207
307
  const publisher = new Bun.RedisClient(url, { ...REDIS_CLIENT_OPTIONS });
208
- const bus = redisPubSub({ publisher, subscriber });
308
+ const bus = redisPubSub({
309
+ publisher,
310
+ subscriber,
311
+ connectionName: options.connectionName ?? cacheBusConnectionName(),
312
+ });
209
313
  // why: refused while the server is away like every command; the subscribe retry and the deferred
210
314
  // publish are where the caller learns of it. Unhandled, it would kill a process booting before
211
315
  // its Redis.