@websolutespa/bom-next 4.0.0-next.11 → 4.0.0-next.12

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @websolutespa/bom-next
2
2
 
3
+ ## 4.0.0-next.12
4
+
5
+ ### Patch Changes
6
+
7
+ - Shared Redis cache across instances and cold starts.
8
+
9
+ - **Lifetime of shared entries.** `cache-handlers/isr` stores the route lifetime (`cacheControl`) with every entry and returns it from `get`. Next.js 16.4 knows the lifetime only of the paths an instance rendered or prerendered, and treated an entry written by another instance as revalidate 1 s: every instance served it stale once and re-rendered it. Entries written before this release fall back to their stored `revalidate`.
10
+ - **One client per process.** The Redis client lives on `globalThis`, so the handler (loaded by Next.js from node_modules) and the bundled server code share one connection, and concurrent first calls no longer create two clients.
11
+ - **Cold start.** `registerIntrumentation()` connects the client before the first request (at most the 2 s connect timeout while Redis is down; skipped during `next build`), so the first page of a new instance reads Redis instead of rendering. The cache panel inspector waits for the connection the same way instead of reporting `none`. New export `connectRedisClient(timeout)` from `@websolutespa/bom-next/cache-handlers/isr`.
12
+
3
13
  ## 4.0.0-next.11
4
14
 
5
15
  ### Minor Changes
@@ -4,8 +4,12 @@
4
4
  * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:
5
5
  * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.
6
6
  *
7
- * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, value }` (in this
8
- * order: the cache panel reads the head of the value without parsing the page).
7
+ * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in
8
+ * this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored
9
+ * `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or
10
+ * prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).
11
+ * - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from
12
+ * node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).
9
13
  * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.
10
14
  * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),
11
15
  * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).
@@ -45,15 +49,27 @@ type CacheValue = {
45
49
  revalidate?: number | false;
46
50
  headers?: Record<string, string | string[] | undefined>;
47
51
  };
52
+ /** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */
53
+ type StoredCacheControl = {
54
+ revalidate: number | false;
55
+ expire: number | undefined;
56
+ };
48
57
  /** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */
49
58
  /** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */
50
59
  declare function getRedisClient(): Promise<RedisLike | undefined>;
60
+ /**
61
+ * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that
62
+ * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance
63
+ * already reads Redis.
64
+ */
65
+ declare function connectRedisClient(timeout?: number): Promise<RedisLike | undefined>;
51
66
  /** Builds the handler class around a client getter, so tests can inject one. */
52
67
  declare function createRedisCacheHandler(getClient?: () => Promise<RedisLike | undefined>, prefix?: string): {
53
68
  new (_ctx?: unknown): {
54
69
  get(key: string, ctx?: CacheHandlerContext): Promise<{
55
70
  lastModified: number;
56
71
  value: CacheValue;
72
+ cacheControl: StoredCacheControl | undefined;
57
73
  } | null>;
58
74
  set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext): Promise<void>;
59
75
  revalidateTag(tags: string | string[], durations?: {
@@ -67,6 +83,7 @@ declare const _default: {
67
83
  get(key: string, ctx?: CacheHandlerContext): Promise<{
68
84
  lastModified: number;
69
85
  value: CacheValue;
86
+ cacheControl: StoredCacheControl | undefined;
70
87
  } | null>;
71
88
  set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext): Promise<void>;
72
89
  revalidateTag(tags: string | string[], durations?: {
@@ -76,5 +93,5 @@ declare const _default: {
76
93
  };
77
94
  };
78
95
  //#endregion
79
- export { RedisLike, _default, createRedisCacheHandler, decode, encode, getRedisClient };
96
+ export { RedisLike, _default, connectRedisClient, createRedisCacheHandler, decode, encode, getRedisClient };
80
97
  //# sourceMappingURL=redis.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"redis.d.ts","names":[],"sources":["../../src/cache-handler/redis.ts"],"mappings":";;AAiBA;;;;;;;;;;;;;;;KAAY,SAAA;EACV,OAAA;EACA,GAAA,CAAI,GAAA,WAAc,OAAA;EAClB,IAAA,CAAK,IAAA,aAAiB,OAAA;EACtB,GAAA,CAAI,GAAA,UAAa,KAAA,UAAe,OAAA;IAAY,EAAA;EAAA,IAAgB,OAAA;EAC5D,IAAA,CAAK,OAAA,uBAA8B,OAAA;EACnC,GAAA,CAAI,GAAA,sBAAyB,OAAA;AAAA;AAAA,KAGnB,mBAAA;EACV,IAAA;EACA,QAAA;EACA,UAAA;EACA,YAAA;IAAiB,UAAA;IAA6B,MAAA;EAAA;AAAA;;iBA0ChC,MAAA,CAAO,KAAA;;iBAKP,MAAA,aAAA,CAAoB,GAAA,WAAc,CAAA;;KAK7C,UAAA;EACH,IAAA;EACA,MAAA;EACA,UAAA;EACA,OAAA,GAAU,MAAA;AAAA;;;iBA0CU,cAAA,CAAA,GAAkB,OAAA,CAAQ,SAAA;AAjD/C;AAAA,iBAmFe,uBAAA,CACd,SAAA,SAAiB,OAAA,CAAQ,SAAA,eACzB,MAAA;EAAA;qBAMuB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;;;;qBA2C3B,IAAA,EAAQ,UAAA,SAAiB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;2CAuC9B,SAAA;MAAgB,MAAA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,IAAiB,OAAA;;;;cA2B/E,QAAA;EAAA;qBAlHwB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;;;;;qBA6C3B,IAAA,EAAQ,UAAA,SAAiB,GAAA,GAAQ,mBAAA,GAAmB,OAAA;2CA0C9B,SAAA;MAAgB,MAAA;IAAA,IAAiB,OAAA"}
@@ -33,6 +33,14 @@ function encode(entry) {
33
33
  function decode(raw) {
34
34
  return JSON.parse(raw, reviver);
35
35
  }
36
+ /** The lifetime returned with an entry, so every instance applies the one it was written with. */
37
+ function cacheControlOf(entry) {
38
+ if (entry.cacheControl) return entry.cacheControl;
39
+ return typeof entry.revalidate === "number" || entry.revalidate === false ? {
40
+ revalidate: entry.revalidate,
41
+ expire: void 0
42
+ } : void 0;
43
+ }
36
44
  /** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */
37
45
  function entryTags(value, ctx) {
38
46
  const tags = new Set(ctx?.tags ?? []);
@@ -44,12 +52,17 @@ function revalidateOf(value, ctx) {
44
52
  const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;
45
53
  return typeof revalidate === "number" || revalidate === false ? revalidate : null;
46
54
  }
47
- let sharedClient;
55
+ /**
56
+ * The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the
57
+ * instrumentation are bundled into the app, and module state would give each its own connection.
58
+ */
59
+ const shared = globalThis;
48
60
  /** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */
49
61
  async function getRedisClient() {
50
62
  if (!process.env.REDIS_URL) return;
51
- if (!sharedClient) {
63
+ if (!shared.__bomRedisClient) {
52
64
  const { createClient } = await import("redis");
65
+ if (shared.__bomRedisClient) return getRedisClient();
53
66
  const client = createClient({
54
67
  url: process.env.REDIS_URL,
55
68
  disableOfflineQueue: true,
@@ -58,7 +71,7 @@ async function getRedisClient() {
58
71
  reconnectStrategy: (retries) => Math.min(retries * 200, 5e3)
59
72
  }
60
73
  });
61
- sharedClient = client;
74
+ shared.__bomRedisClient = client;
62
75
  let logged = false;
63
76
  client.on("error", (error) => {
64
77
  if (!logged) {
@@ -71,8 +84,32 @@ async function getRedisClient() {
71
84
  });
72
85
  client.connect().catch(() => {});
73
86
  }
87
+ const sharedClient = shared.__bomRedisClient;
74
88
  return sharedClient.isReady ? sharedClient : void 0;
75
89
  }
90
+ /**
91
+ * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that
92
+ * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance
93
+ * already reads Redis.
94
+ */
95
+ async function connectRedisClient(timeout = 2e3) {
96
+ const ready = await getRedisClient();
97
+ const client = shared.__bomRedisClient;
98
+ if (ready || !client) return ready;
99
+ await new Promise((resolve) => {
100
+ const done = { timer: void 0 };
101
+ const onReady = () => {
102
+ clearTimeout(done.timer);
103
+ resolve();
104
+ };
105
+ done.timer = setTimeout(() => {
106
+ client.off("ready", onReady);
107
+ resolve();
108
+ }, timeout);
109
+ client.once("ready", onReady);
110
+ });
111
+ return client.isReady ? client : void 0;
112
+ }
76
113
  /** Builds the handler class around a client getter, so tests can inject one. */
77
114
  function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefix()) {
78
115
  const k = keys(prefix);
@@ -90,9 +127,11 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
90
127
  ...ctx?.tags ?? [],
91
128
  ...ctx?.softTags ?? []
92
129
  ])];
130
+ const cacheControl = cacheControlOf(entry);
93
131
  if (!tags.length) return {
94
132
  lastModified: entry.lastModified,
95
- value: entry.value
133
+ value: entry.value,
134
+ cacheControl
96
135
  };
97
136
  const [expired, stale] = await Promise.all([client.mGet(tags.map((tag) => k.expired + tag)), client.mGet(tags.map((tag) => k.stale + tag))]);
98
137
  const now = Date.now();
@@ -101,12 +140,14 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
101
140
  if (typeof entry.revalidate !== "number") return null;
102
141
  return {
103
142
  lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1e3 - 1),
104
- value: entry.value
143
+ value: entry.value,
144
+ cacheControl
105
145
  };
106
146
  }
107
147
  return {
108
148
  lastModified: entry.lastModified,
109
- value: entry.value
149
+ value: entry.value,
150
+ cacheControl
110
151
  };
111
152
  } catch {
112
153
  return null;
@@ -120,10 +161,15 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
120
161
  await client.del([k.entry + key, k.meta + key]);
121
162
  return;
122
163
  }
164
+ const revalidate = revalidateOf(data, ctx);
123
165
  const entry = {
124
166
  lastModified: Date.now(),
125
167
  tags: entryTags(data, ctx),
126
- revalidate: revalidateOf(data, ctx),
168
+ revalidate,
169
+ cacheControl: revalidate === null ? void 0 : {
170
+ revalidate,
171
+ expire: ctx?.cacheControl?.expire
172
+ },
127
173
  value: data
128
174
  };
129
175
  const raw = encode(entry);
@@ -159,6 +205,6 @@ function createRedisCacheHandler(getClient = getRedisClient, prefix = redisPrefi
159
205
  }
160
206
  var redis_default = createRedisCacheHandler();
161
207
  //#endregion
162
- export { createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient, keys, redisPrefix };
208
+ export { connectRedisClient, createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient, keys, redisPrefix };
163
209
 
164
210
  //# sourceMappingURL=redis.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"redis.js","names":[],"sources":["../../src/cache-handler/redis.ts"],"sourcesContent":["/**\n * Next.js incremental cache handler (ISR pages, route handlers, `fetch` and `unstable_cache` entries) backed by\n * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:\n * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.\n *\n * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, value }` (in this\n * order: the cache panel reads the head of the value without parsing the page).\n * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.\n * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),\n * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).\n * `revalidateTag(tag, 'max')` sets the stale time; `revalidateTag(tag, { expire: 0 })`, `updateTag` and\n * `revalidatePath` set the expiry. Next.js only applies stale tags of its own file-system cache, so this handler\n * reports a stale entry by moving its `lastModified` back past its revalidate time.\n * - Redis down: reads miss and writes are dropped, so pages still render (uncached) instead of failing.\n */\n\n/** The subset of a `redis` client this handler uses (injectable for tests). */\nexport type RedisLike = {\n isReady: boolean;\n get(key: string): Promise<string | null>;\n mGet(keys: string[]): Promise<(string | null)[]>;\n set(key: string, value: string, options?: { EX?: number }): Promise<unknown>;\n mSet(entries: [string, string][]): Promise<unknown>;\n del(key: string | string[]): Promise<unknown>;\n};\n\nexport type CacheHandlerContext = {\n tags?: string[];\n softTags?: string[];\n revalidate?: number | false;\n cacheControl?: { revalidate?: number | false; expire?: number };\n};\n\nexport const tagsHeader = 'x-next-cache-tags';\n\nexport function redisPrefix(env: NodeJS.ProcessEnv = process.env): string {\n return env.REDIS_PREFIX ? `${env.REDIS_PREFIX}:` : '';\n}\n\nexport const keys = (prefix: string) => ({\n entry: `${prefix}next:`,\n meta: `${prefix}next-meta:`,\n expired: `${prefix}next-tag:`,\n stale: `${prefix}next-tag-stale:`,\n});\n\nfunction replacer(_key: string, value: unknown) {\n if (value instanceof Map) {\n return { __t: 'map', d: Array.from(value.entries()) };\n }\n if (\n value &&\n typeof value === 'object' &&\n (value as { type?: string }).type === 'Buffer' &&\n Array.isArray((value as { data?: unknown }).data)\n ) {\n return { __t: 'buf', d: Buffer.from((value as { data: number[] }).data).toString('base64') };\n }\n return value;\n}\n\nfunction reviver(_key: string, value: unknown) {\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'map') {\n return new Map((value as { d: [unknown, unknown][] }).d);\n }\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'buf') {\n return Buffer.from((value as { d: string }).d, 'base64');\n }\n return value;\n}\n\n/** Serializes a cache entry, keeping Buffers and Maps (RSC payloads, segment data). */\nexport function encode(entry: unknown): string {\n return JSON.stringify(entry, replacer);\n}\n\n/** Restores a cache entry written by {@link encode}. */\nexport function decode<T = unknown>(raw: string): T {\n return JSON.parse(raw, reviver) as T;\n}\n\n/** The fields of a Next.js cache value this handler reads; the rest is stored as it is. */\ntype CacheValue = {\n kind?: string;\n status?: number;\n revalidate?: number | false;\n headers?: Record<string, string | string[] | undefined>;\n};\n\ntype StoredEntry = {\n lastModified: number;\n tags: string[];\n revalidate: number | false | null;\n value: CacheValue;\n};\n\n/** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */\nexport function entryTags(\n value: CacheValue | null | undefined,\n ctx: CacheHandlerContext | undefined\n): string[] {\n const tags = new Set(ctx?.tags ?? []);\n const header = value?.headers?.[tagsHeader];\n if (typeof header === 'string') {\n header\n .split(',')\n .filter(Boolean)\n .forEach((tag) => tags.add(tag));\n }\n return Array.from(tags);\n}\n\nfunction revalidateOf(\n value: CacheValue,\n ctx: CacheHandlerContext | undefined\n): number | false | null {\n const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;\n return typeof revalidate === 'number' || revalidate === false ? revalidate : null;\n}\n\ntype ConnectingClient = RedisLike & {\n on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;\n connect(): Promise<unknown>;\n};\n\nlet sharedClient: ConnectingClient | undefined;\n\n/** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */\nexport async function getRedisClient(): Promise<RedisLike | undefined> {\n if (!process.env.REDIS_URL) {\n return undefined;\n }\n if (!sharedClient) {\n const { createClient } = await import('redis');\n const client = createClient({\n url: process.env.REDIS_URL,\n // fail fast while disconnected instead of queueing commands behind a dead socket\n disableOfflineQueue: true,\n socket: {\n connectTimeout: 2000,\n reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),\n },\n }) as unknown as ConnectingClient;\n sharedClient = client;\n let logged = false;\n client.on('error', (error: Error) => {\n if (!logged) {\n console.warn('[cache-handler] redis unavailable, serving uncached:', error.message);\n logged = true;\n }\n });\n client.on('ready', () => {\n logged = false;\n });\n client.connect().catch(() => {\n /* reported by the error listener, retried by reconnectStrategy */\n });\n }\n return sharedClient.isReady ? sharedClient : undefined;\n}\n\n/** Builds the handler class around a client getter, so tests can inject one. */\nexport function createRedisCacheHandler(\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\n prefix = redisPrefix()\n) {\n const k = keys(prefix);\n return class RedisCacheHandler {\n constructor(_ctx?: unknown) {}\n\n async get(key: string, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return null;\n }\n try {\n const raw = await client.get(k.entry + key);\n if (!raw) {\n return null;\n }\n const entry = decode<StoredEntry>(raw);\n const tags = [\n ...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),\n ];\n if (!tags.length) {\n return { lastModified: entry.lastModified, value: entry.value };\n }\n const [expired, stale] = await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ]);\n const now = Date.now();\n // an expiry set after this entry was written, and already reached, is a miss: blocking regeneration\n if (expired.some((at) => at && Number(at) > entry.lastModified && Number(at) <= now)) {\n return null;\n }\n if (stale.some((at) => at && Number(at) > entry.lastModified)) {\n if (typeof entry.revalidate !== 'number') {\n // never revalidated by time: a stale entry can only be regenerated by a miss\n return null;\n }\n // serve once more and regenerate in the background: Next.js sees an entry past its revalidate time\n return {\n lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),\n value: entry.value,\n };\n }\n return { lastModified: entry.lastModified, value: entry.value };\n } catch {\n return null;\n }\n }\n\n async set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return;\n }\n try {\n if (data == null) {\n await client.del([k.entry + key, k.meta + key]);\n return;\n }\n const entry: StoredEntry = {\n lastModified: Date.now(),\n tags: entryTags(data, ctx),\n revalidate: revalidateOf(data, ctx),\n value: data,\n };\n const raw = encode(entry);\n const expire = ctx?.cacheControl?.expire;\n const ttl =\n typeof expire === 'number' && Number.isFinite(expire) && expire > 0\n ? { EX: Math.ceil(expire) }\n : undefined;\n const meta = {\n lastModified: entry.lastModified,\n tags: entry.tags,\n revalidate: entry.revalidate,\n kind: data.kind ?? null,\n status: typeof data.status === 'number' ? data.status : null,\n size: Buffer.byteLength(raw),\n };\n await Promise.all([\n client.set(k.entry + key, raw, ttl),\n client.set(k.meta + key, JSON.stringify(meta), ttl),\n ]);\n } catch {\n // a failed write only costs a regeneration on the next request\n }\n }\n\n async revalidateTag(tags: string | string[], durations?: { expire?: number }) {\n const list = (Array.isArray(tags) ? tags : [tags]).filter(Boolean);\n const client = await getClient();\n if (!client?.isReady || !list.length) {\n return;\n }\n const now = Date.now();\n const writes: [string, string][] = [];\n for (const tag of list) {\n if (durations) {\n writes.push([k.stale + tag, String(now)]);\n if (durations.expire !== undefined) {\n writes.push([k.expired + tag, String(now + durations.expire * 1000)]);\n }\n } else {\n writes.push([k.expired + tag, String(now)]);\n }\n }\n try {\n await client.mSet(writes);\n } catch {\n // the entries expire on their own\n }\n }\n\n resetRequestCache() {}\n };\n}\n\nexport default createRedisCacheHandler();\n"],"mappings":";AAiCA,MAAa,aAAa;AAE1B,SAAgB,YAAY,MAAyB,QAAQ,KAAa;AACxE,QAAO,IAAI,eAAe,GAAG,IAAI,aAAa,KAAK;;AAGrD,MAAa,QAAQ,YAAoB;CACvC,OAAO,GAAG,OAAO;CACjB,MAAM,GAAG,OAAO;CAChB,SAAS,GAAG,OAAO;CACnB,OAAO,GAAG,OAAO;CAClB;AAED,SAAS,SAAS,MAAc,OAAgB;AAC9C,KAAI,iBAAiB,IACnB,QAAO;EAAE,KAAK;EAAO,GAAG,MAAM,KAAK,MAAM,SAAS,CAAC;EAAE;AAEvD,KACE,SACA,OAAO,UAAU,Y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W,CAAC,KAAK,OAC5B;GAEF,MAAM,MAAM,KAAK,KAAK;GACtB,MAAM,SAA6B,EAAE;AACrC,QAAK,MAAM,OAAO,KAChB,KAAI,WAAW;AACb,WAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AACzC,QAAI,UAAU,WAAW,KAAA,EACvB,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,MAAM,UAAU,SAAS,IAAK,CAAC,CAAC;SAGvE,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,IAAI,CAAC,CAAC;AAG/C,OAAI;AACF,UAAM,OAAO,KAAK,OAAO;WACnB;;EAKV,oBAAoB;;;AAIxB,IAAA,gBAAe,yBAAyB"}
1
+ {"version":3,"file":"redis.js","names":[],"sources":["../../src/cache-handler/redis.ts"],"sourcesContent":["/**\n * Next.js incremental cache handler (ISR pages, route handlers, `fetch` and `unstable_cache` entries) backed by\n * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:\n * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.\n *\n * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in\n * this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored\n * `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or\n * prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).\n * - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from\n * node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).\n * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.\n * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),\n * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).\n * `revalidateTag(tag, 'max')` sets the stale time; `revalidateTag(tag, { expire: 0 })`, `updateTag` and\n * `revalidatePath` set the expiry. Next.js only applies stale tags of its own file-system cache, so this handler\n * reports a stale entry by moving its `lastModified` back past its revalidate time.\n * - Redis down: reads miss and writes are dropped, so pages still render (uncached) instead of failing.\n */\n\n/** The subset of a `redis` client this handler uses (injectable for tests). */\nexport type RedisLike = {\n isReady: boolean;\n get(key: string): Promise<string | null>;\n mGet(keys: string[]): Promise<(string | null)[]>;\n set(key: string, value: string, options?: { EX?: number }): Promise<unknown>;\n mSet(entries: [string, string][]): Promise<unknown>;\n del(key: string | string[]): Promise<unknown>;\n};\n\nexport type CacheHandlerContext = {\n tags?: string[];\n softTags?: string[];\n revalidate?: number | false;\n cacheControl?: { revalidate?: number | false; expire?: number };\n};\n\nexport const tagsHeader = 'x-next-cache-tags';\n\nexport function redisPrefix(env: NodeJS.ProcessEnv = process.env): string {\n return env.REDIS_PREFIX ? `${env.REDIS_PREFIX}:` : '';\n}\n\nexport const keys = (prefix: string) => ({\n entry: `${prefix}next:`,\n meta: `${prefix}next-meta:`,\n expired: `${prefix}next-tag:`,\n stale: `${prefix}next-tag-stale:`,\n});\n\nfunction replacer(_key: string, value: unknown) {\n if (value instanceof Map) {\n return { __t: 'map', d: Array.from(value.entries()) };\n }\n if (\n value &&\n typeof value === 'object' &&\n (value as { type?: string }).type === 'Buffer' &&\n Array.isArray((value as { data?: unknown }).data)\n ) {\n return { __t: 'buf', d: Buffer.from((value as { data: number[] }).data).toString('base64') };\n }\n return value;\n}\n\nfunction reviver(_key: string, value: unknown) {\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'map') {\n return new Map((value as { d: [unknown, unknown][] }).d);\n }\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'buf') {\n return Buffer.from((value as { d: string }).d, 'base64');\n }\n return value;\n}\n\n/** Serializes a cache entry, keeping Buffers and Maps (RSC payloads, segment data). */\nexport function encode(entry: unknown): string {\n return JSON.stringify(entry, replacer);\n}\n\n/** Restores a cache entry written by {@link encode}. */\nexport function decode<T = unknown>(raw: string): T {\n return JSON.parse(raw, reviver) as T;\n}\n\n/** The fields of a Next.js cache value this handler reads; the rest is stored as it is. */\ntype CacheValue = {\n kind?: string;\n status?: number;\n revalidate?: number | false;\n headers?: Record<string, string | string[] | undefined>;\n};\n\n/** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */\ntype StoredCacheControl = { revalidate: number | false; expire: number | undefined };\n\ntype StoredEntry = {\n lastModified: number;\n tags: string[];\n revalidate: number | false | null;\n /** Absent on entries written before 4.0.0-next.12. */\n cacheControl?: StoredCacheControl;\n value: CacheValue;\n};\n\n/** The lifetime returned with an entry, so every instance applies the one it was written with. */\nfunction cacheControlOf(entry: StoredEntry): StoredCacheControl | undefined {\n if (entry.cacheControl) {\n return entry.cacheControl;\n }\n return typeof entry.revalidate === 'number' || entry.revalidate === false\n ? { revalidate: entry.revalidate, expire: undefined }\n : undefined;\n}\n\n/** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */\nexport function entryTags(\n value: CacheValue | null | undefined,\n ctx: CacheHandlerContext | undefined\n): string[] {\n const tags = new Set(ctx?.tags ?? []);\n const header = value?.headers?.[tagsHeader];\n if (typeof header === 'string') {\n header\n .split(',')\n .filter(Boolean)\n .forEach((tag) => tags.add(tag));\n }\n return Array.from(tags);\n}\n\nfunction revalidateOf(\n value: CacheValue,\n ctx: CacheHandlerContext | undefined\n): number | false | null {\n const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;\n return typeof revalidate === 'number' || revalidate === false ? revalidate : null;\n}\n\ntype ConnectingClient = RedisLike & {\n on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;\n once(event: 'ready', listener: () => void): unknown;\n off(event: 'ready', listener: () => void): unknown;\n connect(): Promise<unknown>;\n};\n\n/**\n * The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the\n * instrumentation are bundled into the app, and module state would give each its own connection.\n */\nconst shared = globalThis as typeof globalThis & { __bomRedisClient?: ConnectingClient };\n\n/** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */\nexport async function getRedisClient(): Promise<RedisLike | undefined> {\n if (!process.env.REDIS_URL) {\n return undefined;\n }\n if (!shared.__bomRedisClient) {\n const { createClient } = await import('redis');\n // another caller may have created it while the module loaded\n if (shared.__bomRedisClient) {\n return getRedisClient();\n }\n const client = createClient({\n url: process.env.REDIS_URL,\n // fail fast while disconnected instead of queueing commands behind a dead socket\n disableOfflineQueue: true,\n socket: {\n connectTimeout: 2000,\n reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),\n },\n }) as unknown as ConnectingClient;\n shared.__bomRedisClient = client;\n let logged = false;\n client.on('error', (error: Error) => {\n if (!logged) {\n console.warn('[cache-handler] redis unavailable, serving uncached:', error.message);\n logged = true;\n }\n });\n client.on('ready', () => {\n logged = false;\n });\n client.connect().catch(() => {\n /* reported by the error listener, retried by reconnectStrategy */\n });\n }\n const sharedClient = shared.__bomRedisClient;\n return sharedClient.isReady ? sharedClient : undefined;\n}\n\n/**\n * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that\n * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance\n * already reads Redis.\n */\nexport async function connectRedisClient(timeout = 2000): Promise<RedisLike | undefined> {\n const ready = await getRedisClient();\n const client = shared.__bomRedisClient;\n if (ready || !client) {\n return ready;\n }\n await new Promise<void>((resolve) => {\n const done = { timer: undefined as ReturnType<typeof setTimeout> | undefined };\n const onReady = () => {\n clearTimeout(done.timer);\n resolve();\n };\n // no listener left behind while Redis stays down and the panel keeps asking\n done.timer = setTimeout(() => {\n client.off('ready', onReady);\n resolve();\n }, timeout);\n client.once('ready', onReady);\n });\n return client.isReady ? client : undefined;\n}\n\n/** Builds the handler class around a client getter, so tests can inject one. */\nexport function createRedisCacheHandler(\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\n prefix = redisPrefix()\n) {\n const k = keys(prefix);\n return class RedisCacheHandler {\n constructor(_ctx?: unknown) {}\n\n async get(key: string, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return null;\n }\n try {\n const raw = await client.get(k.entry + key);\n if (!raw) {\n return null;\n }\n const entry = decode<StoredEntry>(raw);\n const tags = [\n ...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),\n ];\n const cacheControl = cacheControlOf(entry);\n if (!tags.length) {\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\n }\n const [expired, stale] = await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ]);\n const now = Date.now();\n // an expiry set after this entry was written, and already reached, is a miss: blocking regeneration\n if (expired.some((at) => at && Number(at) > entry.lastModified && Number(at) <= now)) {\n return null;\n }\n if (stale.some((at) => at && Number(at) > entry.lastModified)) {\n if (typeof entry.revalidate !== 'number') {\n // never revalidated by time: a stale entry can only be regenerated by a miss\n return null;\n }\n // serve once more and regenerate in the background: Next.js sees an entry past its revalidate time\n return {\n lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),\n value: entry.value,\n cacheControl,\n };\n }\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\n } catch {\n return null;\n }\n }\n\n async set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return;\n }\n try {\n if (data == null) {\n await client.del([k.entry + key, k.meta + key]);\n return;\n }\n const revalidate = revalidateOf(data, ctx);\n const entry: StoredEntry = {\n lastModified: Date.now(),\n tags: entryTags(data, ctx),\n revalidate,\n cacheControl:\n revalidate === null ? undefined : { revalidate, expire: ctx?.cacheControl?.expire },\n value: data,\n };\n const raw = encode(entry);\n const expire = ctx?.cacheControl?.expire;\n const ttl =\n typeof expire === 'number' && Number.isFinite(expire) && expire > 0\n ? { EX: Math.ceil(expire) }\n : undefined;\n const meta = {\n lastModified: entry.lastModified,\n tags: entry.tags,\n revalidate: entry.revalidate,\n kind: data.kind ?? null,\n status: typeof data.status === 'number' ? data.status : null,\n size: Buffer.byteLength(raw),\n };\n await Promise.all([\n client.set(k.entry + key, raw, ttl),\n client.set(k.meta + key, JSON.stringify(meta), ttl),\n ]);\n } catch {\n // a failed write only costs a regeneration on the next request\n }\n }\n\n async revalidateTag(tags: string | string[], durations?: { expire?: number }) {\n const list = (Array.isArray(tags) ? tags : [tags]).filter(Boolean);\n const client = await getClient();\n if (!client?.isReady || !list.length) {\n return;\n }\n const now = Date.now();\n const writes: [string, string][] = [];\n for (const tag of list) {\n if (durations) {\n writes.push([k.stale + tag, String(now)]);\n if (durations.expire !== undefined) {\n writes.push([k.expired + tag, String(now + durations.expire * 1000)]);\n }\n } else {\n writes.push([k.expired + tag, String(now)]);\n }\n }\n try {\n await client.mSet(writes);\n } catch {\n // the entries expire on their own\n }\n }\n\n resetRequestCache() {}\n };\n}\n\nexport default createRedisCacheHandler();\n"],"mappings":";AAqCA,MAAa,aAAa;AAE1B,SAAgB,YAAY,MAAyB,QAAQ,KAAa;AACxE,QAAO,IAAI,eAAe,GAAG,IAAI,aAAa,KAAK;;AAGrD,MAAa,QAAQ,YAAoB;CACvC,OAAO,GAAG,OAAO;CACjB,MAAM,GAAG,OAAO;CAChB,SAAS,GAAG,OAAO;CACnB,OAAO,GAAG,OAAO;CAClB;AAED,SAAS,SAAS,MAAc,OAAgB;AAC9C,KAAI,iBAAiB,IACnB,QAAO;EAAE,KAAK;EAAO,GAAG,MAAM,KAAK,MAAM,SAAS,CAAC;EAAE;AAEvD,KACE,SACA,OAAO,UAAU,YAChB,MAA4B,SAAS,YACtC,MAAM,QAAS,MAA6B,KAAK,CAEjD,QAAO;EAAE,KAAK;EAAO,GAAG,OAAO,KAAM,MAA6B,KAAK,CAAC,SAAS,SAAS;EAAE;AAE9F,QAAO;;AAGT,SAAS,QAAQ,MAAc,OAAgB;AAC7C,KAAI,SAAS,OAAO,UAAU,YAAa,MAA2B,QA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AAO,SAAS,OAAO,IAAI,SAAS,IAC9D,EAAE,IAAI,KAAK,KAAK,OAAO,EAAE,GACzB,KAAA;IACN,MAAM,OAAO;KACX,cAAc,MAAM;KACpB,MAAM,MAAM;KACZ,YAAY,MAAM;KAClB,MAAM,KAAK,QAAQ;KACnB,QAAQ,OAAO,KAAK,WAAW,WAAW,KAAK,SAAS;KACxD,MAAM,OAAO,WAAW,IAAI;KAC7B;AACD,UAAM,QAAQ,IAAI,CAChB,OAAO,IAAI,EAAE,QAAQ,KAAK,KAAK,IAAI,EACnC,OAAO,IAAI,EAAE,OAAO,KAAK,KAAK,UAAU,KAAK,EAAE,IAAI,CACpD,CAAC;WACI;;EAKV,MAAM,cAAc,MAAyB,WAAiC;GAC5E,MAAM,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,KAAK,EAAE,OAAO,QAAQ;GAClE,MAAM,SAAS,MAAM,WAAW;AAChC,OAAI,CAAC,QAAQ,WAAW,CAAC,KAAK,OAC5B;GAEF,MAAM,MAAM,KAAK,KAAK;GACtB,MAAM,SAA6B,EAAE;AACrC,QAAK,MAAM,OAAO,KAChB,KAAI,WAAW;AACb,WAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AACzC,QAAI,UAAU,WAAW,KAAA,EACvB,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,MAAM,UAAU,SAAS,IAAK,CAAC,CAAC;SAGvE,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,IAAI,CAAC,CAAC;AAG/C,OAAI;AACF,UAAM,OAAO,KAAK,OAAO;WACnB;;EAKV,oBAAoB;;;AAIxB,IAAA,gBAAe,yBAAyB"}
@@ -1,2 +1,2 @@
1
- import { _default, createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
- export { createRedisCacheHandler, decode, _default as default, encode, getRedisClient };
1
+ import { _default, connectRedisClient, createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
+ export { connectRedisClient, createRedisCacheHandler, decode, _default as default, encode, getRedisClient };
@@ -1,2 +1,2 @@
1
- import redis_default, { createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
- export { createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient };
1
+ import redis_default, { connectRedisClient, createRedisCacheHandler, decode, encode, getRedisClient } from "../cache-handler/redis.js";
2
+ export { connectRedisClient, createRedisCacheHandler, decode, redis_default as default, encode, getRedisClient };
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","names":[],"sources":["../../src/instrumentation/server.ts"],"mappings":";;;iBAGsB,sBAAA,CAAA,GAAsB,OAAA;;AAA5C;;iBAmBgB,mBAAA,CACd,KAAA,WACA,OAAA,EAAS,WAAA,EACT,YAAA,EAAc,YAAA"}
1
+ {"version":3,"file":"server.d.ts","names":[],"sources":["../../src/instrumentation/server.ts"],"mappings":";;;iBAGsB,sBAAA,CAAA,GAAsB,OAAA;;AAA5C;;iBAyBgB,mBAAA,CACd,KAAA,WACA,OAAA,EAAS,WAAA,EACT,YAAA,EAAc,YAAA"}
@@ -4,6 +4,10 @@ async function registerIntrumentation() {
4
4
  if (process.env.NEXT_RUNTIME === "nodejs") {
5
5
  const { registerLocalCacheExecutor } = await import("../server/cache/local-executor.js");
6
6
  registerLocalCacheExecutor();
7
+ if (process.env.REDIS_URL && process.env.NEXT_PHASE !== "phase-production-build") {
8
+ const { connectRedisClient } = await import("../cache-handler/redis.js");
9
+ await connectRedisClient();
10
+ }
7
11
  }
8
12
  if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
9
13
  if (process.env.NEXT_RUNTIME === "nodejs") await import("./sentry/config.server.js");
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["sentryCaptureRequestError"],"sources":["../../src/instrumentation/server.ts"],"sourcesContent":["import { captureRequestError as sentryCaptureRequestError } from './sentry/capture.requestError';\nimport { ErrorContext, RequestInfo } from './types';\n\nexport async function registerIntrumentation() {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n // the cache panel (Bowl admin) reaches this site runtime in process instead of over HTTP\n const { registerLocalCacheExecutor } = await import('../server/cache/local-executor');\n registerLocalCacheExecutor();\n }\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n await import('./sentry/config.server');\n }\n if (process.env.NEXT_RUNTIME === 'edge') {\n await import('./sentry/config.edge');\n }\n }\n}\n\n/**\n * Reports errors passed to the the Next.js `onRequestError` instrumentation hook.\n */\nexport function captureRequestError(\n error: unknown,\n request: RequestInfo,\n errorContext: ErrorContext\n): void {\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n return sentryCaptureRequestError(error, request, errorContext);\n } else {\n console.log('Instrumentation.captureRequestError', error, errorContext);\n }\n}\n"],"mappings":";;AAGA,eAAsB,yBAAyB;AAC7C,KAAI,QAAQ,IAAI,iBAAiB,UAAU;EAEzC,MAAM,EAAE,+BAA+B,MAAM,OAAO;AACpD,8BAA4B;;AAE9B,KAAI,QAAQ,IAAI,wBAAwB;AACtC,MAAI,QAAQ,IAAI,iBAAiB,SAC/B,OAAM,OAAO;AAEf,MAAI,QAAQ,IAAI,iBAAiB,OAC/B,OAAM,OAAO;;;;;;AAQnB,SAAgB,oBACd,OACA,SACA,cACM;AACN,KAAI,QAAQ,IAAI,uBACd,QAAOA,sBAA0B,OAAO,SAAS,aAAa;KAE9D,SAAQ,IAAI,uCAAuC,OAAO,aAAa"}
1
+ {"version":3,"file":"server.js","names":["sentryCaptureRequestError"],"sources":["../../src/instrumentation/server.ts"],"sourcesContent":["import { captureRequestError as sentryCaptureRequestError } from './sentry/capture.requestError';\nimport { ErrorContext, RequestInfo } from './types';\n\nexport async function registerIntrumentation() {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n // the cache panel (Bowl admin) reaches this site runtime in process instead of over HTTP\n const { registerLocalCacheExecutor } = await import('../server/cache/local-executor');\n registerLocalCacheExecutor();\n if (process.env.REDIS_URL && process.env.NEXT_PHASE !== 'phase-production-build') {\n // connect the shared cache client before the first request, so a cold instance already reads Redis (at most\n // the 2 s connect timeout while Redis is down; pages then render uncached)\n const { connectRedisClient } = await import('../cache-handler/redis');\n await connectRedisClient();\n }\n }\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n await import('./sentry/config.server');\n }\n if (process.env.NEXT_RUNTIME === 'edge') {\n await import('./sentry/config.edge');\n }\n }\n}\n\n/**\n * Reports errors passed to the the Next.js `onRequestError` instrumentation hook.\n */\nexport function captureRequestError(\n error: unknown,\n request: RequestInfo,\n errorContext: ErrorContext\n): void {\n if (process.env.NEXT_PUBLIC_SENTRY_DSN) {\n return sentryCaptureRequestError(error, request, errorContext);\n } else {\n console.log('Instrumentation.captureRequestError', error, errorContext);\n }\n}\n"],"mappings":";;AAGA,eAAsB,yBAAyB;AAC7C,KAAI,QAAQ,IAAI,iBAAiB,UAAU;EAEzC,MAAM,EAAE,+BAA+B,MAAM,OAAO;AACpD,8BAA4B;AAC5B,MAAI,QAAQ,IAAI,aAAa,QAAQ,IAAI,eAAe,0BAA0B;GAGhF,MAAM,EAAE,uBAAuB,MAAM,OAAO;AAC5C,SAAM,oBAAoB;;;AAG9B,KAAI,QAAQ,IAAI,wBAAwB;AACtC,MAAI,QAAQ,IAAI,iBAAiB,SAC/B,OAAM,OAAO;AAEf,MAAI,QAAQ,IAAI,iBAAiB,OAC/B,OAAM,OAAO;;;;;;AAQnB,SAAgB,oBACd,OACA,SACA,cACM;AACN,KAAI,QAAQ,IAAI,uBACd,QAAOA,sBAA0B,OAAO,SAAS,aAAa;KAE9D,SAAQ,IAAI,uCAAuC,OAAO,aAAa"}
@@ -1,4 +1,4 @@
1
- import { getRedisClient, keys, redisPrefix } from "../../../cache-handler/redis.js";
1
+ import { connectRedisClient, keys, redisPrefix } from "../../../cache-handler/redis.js";
2
2
  import { tagState } from "../../../cache-handlers/default.js";
3
3
  import { parseRouteCacheKey } from "./route-cache-key.js";
4
4
  import { functionName } from "./types.js";
@@ -10,7 +10,7 @@ const maxEntries = 2e4;
10
10
  * are never loaded. The state is exact: the tag timestamps the handler writes are compared with each entry.
11
11
  * Entries written by an older handler without meta keys are not listed.
12
12
  */
13
- function createRedisInspector({ getClient = getRedisClient, prefix = redisPrefix() } = {}) {
13
+ function createRedisInspector({ getClient = connectRedisClient, prefix = redisPrefix() } = {}) {
14
14
  const k = keys(prefix);
15
15
  async function scan() {
16
16
  const client = await getClient();
@@ -1 +1 @@
1
- {"version":3,"file":"redis.js","names":[],"sources":["../../../../src/server/cache/inspector/redis.ts"],"sourcesContent":["import { getRedisClient, keys, redisPrefix, type RedisLike } from '../../../cache-handler/redis';\nimport { tagState, type UseCacheMeta } from '../../../cache-handlers/default';\nimport { explicitTags } from './filesystem';\nimport { parseRouteCacheKey } from './route-cache-key';\nimport { type CachedFunction, type CachedPage, type CacheInspector, functionName } from './types';\n\n/** The redis client subset the inspector needs on top of the handler's. */\nexport type RedisScanner = Pick<RedisLike, 'isReady' | 'mGet'> & {\n scanIterator(options: { MATCH: string; COUNT?: number }): AsyncIterable<string | string[]>;\n};\n\ntype Meta = {\n lastModified: number;\n tags: string[];\n revalidate: number | false | null;\n kind: string | null;\n status: number | null;\n size: number;\n};\n\nconst maxEntries = 20_000;\n\n/**\n * Reads the shared Redis cache of `@websolutespa/bom-next/cache-handlers/isr` through its meta keys, so page bodies\n * are never loaded. The state is exact: the tag timestamps the handler writes are compared with each entry.\n * Entries written by an older handler without meta keys are not listed.\n */\nexport function createRedisInspector({\n getClient = getRedisClient as () => Promise<RedisScanner | undefined>,\n prefix = redisPrefix(),\n}: { getClient?: () => Promise<RedisScanner | undefined>; prefix?: string } = {}): CacheInspector {\n const k = keys(prefix);\n\n async function scan(): Promise<{ key: string; meta: Meta; expired: boolean; stale: boolean }[]> {\n const client = await getClient();\n if (!client?.isReady) {\n throw new Error('Redis is not reachable.');\n }\n const metaKeys: string[] = [];\n for await (const batch of client.scanIterator({ MATCH: `${k.meta}*`, COUNT: 500 })) {\n metaKeys.push(...(Array.isArray(batch) ? batch : [batch]));\n if (metaKeys.length >= maxEntries) break;\n }\n if (!metaKeys.length) {\n return [];\n }\n const raw = await client.mGet(metaKeys);\n const entries = metaKeys\n .map((metaKey, index) => {\n try {\n return { key: metaKey.slice(k.meta.length), meta: JSON.parse(raw[index] ?? '') as Meta };\n } catch {\n return undefined;\n }\n })\n .filter((entry): entry is { key: string; meta: Meta } => Boolean(entry));\n const tags = [...new Set(entries.flatMap((entry) => entry.meta.tags))];\n const [expired, stale] = tags.length\n ? await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ])\n : [[], []];\n const expiredAt = new Map(tags.map((tag, index) => [tag, Number(expired[index] ?? 0)]));\n const staleAt = new Map(tags.map((tag, index) => [tag, Number(stale[index] ?? 0)]));\n const now = Date.now();\n return entries.map(({ key, meta }) => ({\n key,\n meta,\n expired: meta.tags.some((tag) => {\n const at = expiredAt.get(tag) ?? 0;\n return at > meta.lastModified && at <= now;\n }),\n stale: meta.tags.some((tag) => (staleAt.get(tag) ?? 0) > meta.lastModified),\n }));\n }\n\n let pending: ReturnType<typeof scan> | undefined;\n // pages() and functions() are read together: one scan serves both\n function scanOnce() {\n pending ??= scan().finally(() => {\n setTimeout(() => {\n pending = undefined;\n }, 0);\n });\n return pending;\n }\n\n return {\n backend: 'redis',\n async pages() {\n const pages: CachedPage[] = [];\n for (const { key, meta, expired, stale } of await scanOnce()) {\n if (meta.kind !== 'APP_PAGE' && meta.kind !== 'APP_ROUTE') continue;\n const parsed = parseRouteCacheKey(key);\n if (!parsed || parsed.internalPath.startsWith('/_') || parsed.internalPath === '/index')\n continue;\n pages.push({\n internalPath: parsed.internalPath,\n tags: explicitTags(meta.tags.join(',')),\n generatedAt: meta.lastModified,\n sizeBytes: meta.size,\n revalidateSeconds: typeof meta.revalidate === 'number' ? meta.revalidate : null,\n status: meta.status,\n expired,\n stale: !expired && stale,\n sourceHash: parsed.sourceHash,\n });\n }\n return pages;\n },\n async functions() {\n const functions: CachedFunction[] = [];\n for (const { key, meta, expired, stale } of await scanOnce()) {\n const name = meta.kind === 'FETCH' ? functionName(meta.tags) : undefined;\n if (!name) continue;\n functions.push({\n key,\n name,\n tags: meta.tags,\n generatedAt: meta.lastModified,\n sizeBytes: meta.size,\n revalidateSeconds: typeof meta.revalidate === 'number' ? meta.revalidate : null,\n expired,\n stale: !expired && stale,\n });\n }\n // `'use cache'` results (Cache Components, Redis handler): same tag keys, their own meta prefix\n const client = await getClient();\n if (client?.isReady) {\n const useCacheMeta = `${prefix}use-cache-meta:`;\n const metaKeys: string[] = [];\n for await (const batch of client.scanIterator({ MATCH: `${useCacheMeta}*`, COUNT: 500 })) {\n metaKeys.push(...(Array.isArray(batch) ? batch : [batch]));\n if (metaKeys.length >= maxEntries) break;\n }\n const raw = metaKeys.length ? await client.mGet(metaKeys) : [];\n const metas = raw\n .map((value) => {\n try {\n return JSON.parse(value ?? '') as UseCacheMeta;\n } catch {\n return undefined;\n }\n })\n .filter((meta): meta is UseCacheMeta => Boolean(meta && functionName(meta.tags)));\n const tags = [...new Set(metas.flatMap((meta) => meta.tags))];\n const [expired, stale] = tags.length\n ? await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ])\n : [[], []];\n const states = new Map(\n tags.map((tag, index) => [\n tag,\n { expired: Number(expired[index] ?? 0), stale: Number(stale[index] ?? 0) },\n ])\n );\n for (const meta of metas) {\n const state = tagState(meta, (tag) => states.get(tag) ?? {});\n functions.push({\n key: meta.key,\n name: functionName(meta.tags)!,\n tags: meta.tags,\n generatedAt: meta.timestamp,\n sizeBytes: meta.size,\n revalidateSeconds: Number.isFinite(meta.revalidate) ? meta.revalidate : null,\n expired: state === 'expired',\n stale: state === 'stale',\n });\n }\n }\n return functions;\n },\n };\n}\n"],"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,QAAQ,OAAO;KACxB,MAAM,QAAQ,SAAS,OAAO,QAAQ,OAAO,IAAI,IAAI,IAAI,EAAE,CAAC;AAC5D,eAAU,KAAK;MACb,KAAK,KAAK;MACV,MAAM,aAAa,KAAK,KAAK;MAC7B,MAAM,KAAK;MACX,aAAa,KAAK;MAClB,WAAW,KAAK;MAChB,mBAAmB,OAAO,SAAS,KAAK,WAAW,GAAG,KAAK,aAAa;MACxE,SAAS,UAAU;MACnB,OAAO,UAAU;MAClB,CAAC;;;AAGN,UAAO;;EAEV"}
1
+ {"version":3,"file":"redis.js","names":[],"sources":["../../../../src/server/cache/inspector/redis.ts"],"sourcesContent":["import {\n connectRedisClient,\n keys,\n redisPrefix,\n type RedisLike,\n} from '../../../cache-handler/redis';\nimport { tagState, type UseCacheMeta } from '../../../cache-handlers/default';\nimport { explicitTags } from './filesystem';\nimport { parseRouteCacheKey } from './route-cache-key';\nimport { type CachedFunction, type CachedPage, type CacheInspector, functionName } from './types';\n\n/** The redis client subset the inspector needs on top of the handler's. */\nexport type RedisScanner = Pick<RedisLike, 'isReady' | 'mGet'> & {\n scanIterator(options: { MATCH: string; COUNT?: number }): AsyncIterable<string | string[]>;\n};\n\ntype Meta = {\n lastModified: number;\n tags: string[];\n revalidate: number | false | null;\n kind: string | null;\n status: number | null;\n size: number;\n};\n\nconst maxEntries = 20_000;\n\n/**\n * Reads the shared Redis cache of `@websolutespa/bom-next/cache-handlers/isr` through its meta keys, so page bodies\n * are never loaded. The state is exact: the tag timestamps the handler writes are compared with each entry.\n * Entries written by an older handler without meta keys are not listed.\n */\nexport function createRedisInspector({\n // the panel may wait for the connection: on a cold instance the client is not ready yet\n getClient = connectRedisClient as () => Promise<RedisScanner | undefined>,\n prefix = redisPrefix(),\n}: { getClient?: () => Promise<RedisScanner | undefined>; prefix?: string } = {}): CacheInspector {\n const k = keys(prefix);\n\n async function scan(): Promise<{ key: string; meta: Meta; expired: boolean; stale: boolean }[]> {\n const client = await getClient();\n if (!client?.isReady) {\n throw new Error('Redis is not reachable.');\n }\n const metaKeys: string[] = [];\n for await (const batch of client.scanIterator({ MATCH: `${k.meta}*`, COUNT: 500 })) {\n metaKeys.push(...(Array.isArray(batch) ? batch : [batch]));\n if (metaKeys.length >= maxEntries) break;\n }\n if (!metaKeys.length) {\n return [];\n }\n const raw = await client.mGet(metaKeys);\n const entries = metaKeys\n .map((metaKey, index) => {\n try {\n return { key: metaKey.slice(k.meta.length), meta: JSON.parse(raw[index] ?? '') as Meta };\n } catch {\n return undefined;\n }\n })\n .filter((entry): entry is { key: string; meta: Meta } => Boolean(entry));\n const tags = [...new Set(entries.flatMap((entry) => entry.meta.tags))];\n const [expired, stale] = tags.length\n ? await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ])\n : [[], []];\n const expiredAt = new Map(tags.map((tag, index) => [tag, Number(expired[index] ?? 0)]));\n const staleAt = new Map(tags.map((tag, index) => [tag, Number(stale[index] ?? 0)]));\n const now = Date.now();\n return entries.map(({ key, meta }) => ({\n key,\n meta,\n expired: meta.tags.some((tag) => {\n const at = expiredAt.get(tag) ?? 0;\n return at > meta.lastModified && at <= now;\n }),\n stale: meta.tags.some((tag) => (staleAt.get(tag) ?? 0) > meta.lastModified),\n }));\n }\n\n let pending: ReturnType<typeof scan> | undefined;\n // pages() and functions() are read together: one scan serves both\n function scanOnce() {\n pending ??= scan().finally(() => {\n setTimeout(() => {\n pending = undefined;\n }, 0);\n });\n return pending;\n }\n\n return {\n backend: 'redis',\n async pages() {\n const pages: CachedPage[] = [];\n for (const { key, meta, expired, stale } of await scanOnce()) {\n if (meta.kind !== 'APP_PAGE' && meta.kind !== 'APP_ROUTE') continue;\n const parsed = parseRouteCacheKey(key);\n if (!parsed || parsed.internalPath.startsWith('/_') || parsed.internalPath === '/index')\n continue;\n pages.push({\n internalPath: parsed.internalPath,\n tags: explicitTags(meta.tags.join(',')),\n generatedAt: meta.lastModified,\n sizeBytes: meta.size,\n revalidateSeconds: typeof meta.revalidate === 'number' ? meta.revalidate : null,\n status: meta.status,\n expired,\n stale: !expired && stale,\n sourceHash: parsed.sourceHash,\n });\n }\n return pages;\n },\n async functions() {\n const functions: CachedFunction[] = [];\n for (const { key, meta, expired, stale } of await scanOnce()) {\n const name = meta.kind === 'FETCH' ? functionName(meta.tags) : undefined;\n if (!name) continue;\n functions.push({\n key,\n name,\n tags: meta.tags,\n generatedAt: meta.lastModified,\n sizeBytes: meta.size,\n revalidateSeconds: typeof meta.revalidate === 'number' ? meta.revalidate : null,\n expired,\n stale: !expired && stale,\n });\n }\n // `'use cache'` results (Cache Components, Redis handler): same tag keys, their own meta prefix\n const client = await getClient();\n if (client?.isReady) {\n const useCacheMeta = `${prefix}use-cache-meta:`;\n const metaKeys: string[] = [];\n for await (const batch of client.scanIterator({ MATCH: `${useCacheMeta}*`, COUNT: 500 })) {\n metaKeys.push(...(Array.isArray(batch) ? batch : [batch]));\n if (metaKeys.length >= maxEntries) break;\n }\n const raw = metaKeys.length ? await client.mGet(metaKeys) : [];\n const metas = raw\n .map((value) => {\n try {\n return JSON.parse(value ?? '') as UseCacheMeta;\n } catch {\n return undefined;\n }\n })\n .filter((meta): meta is UseCacheMeta => Boolean(meta && functionName(meta.tags)));\n const tags = [...new Set(metas.flatMap((meta) => meta.tags))];\n const [expired, stale] = tags.length\n ? await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ])\n : [[], []];\n const states = new Map(\n tags.map((tag, index) => [\n tag,\n { expired: Number(expired[index] ?? 0), stale: Number(stale[index] ?? 0) },\n ])\n );\n for (const meta of metas) {\n const state = tagState(meta, (tag) => states.get(tag) ?? {});\n functions.push({\n key: meta.key,\n name: functionName(meta.tags)!,\n tags: meta.tags,\n generatedAt: meta.timestamp,\n sizeBytes: meta.size,\n revalidateSeconds: Number.isFinite(meta.revalidate) ? meta.revalidate : null,\n expired: state === 'expired',\n stale: state === 'stale',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E,CAC3E,CAAC,CACH;AACD,SAAK,MAAM,QAAQ,OAAO;KACxB,MAAM,QAAQ,SAAS,OAAO,QAAQ,OAAO,IAAI,IAAI,IAAI,EAAE,CAAC;AAC5D,eAAU,KAAK;MACb,KAAK,KAAK;MACV,MAAM,aAAa,KAAK,KAAK;MAC7B,MAAM,KAAK;MACX,aAAa,KAAK;MAClB,WAAW,KAAK;MAChB,mBAAmB,OAAO,SAAS,KAAK,WAAW,GAAG,KAAK,aAAa;MACxE,SAAS,UAAU;MACnB,OAAO,UAAU;MAClB,CAAC;;;AAGN,UAAO;;EAEV"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@websolutespa/bom-next",
3
- "version": "4.0.0-next.11",
3
+ "version": "4.0.0-next.12",
4
4
  "description": "Next module of the BOM Repository",
5
5
  "keywords": [
6
6
  "bom",
@@ -1,6 +1,13 @@
1
1
  // @vitest-environment node
2
2
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
- import { createRedisCacheHandler, decode, encode, type RedisLike } from './redis';
3
+ import {
4
+ connectRedisClient,
5
+ createRedisCacheHandler,
6
+ decode,
7
+ encode,
8
+ getRedisClient,
9
+ type RedisLike,
10
+ } from './redis';
4
11
 
5
12
  /** An in-memory stand-in for the redis client subset the handler uses. */
6
13
  function fakeRedis(): RedisLike & {
@@ -138,6 +145,31 @@ describe('redis cache handler', () => {
138
145
  expect(await handler.get('/p', {})).toBeNull();
139
146
  });
140
147
 
148
+ it('returns the stored lifetime, so another instance applies it instead of revalidating after 1 s', async () => {
149
+ const handler = new Handler();
150
+ await handler.set('/p', page('bom:all'), pageCtx);
151
+ expect(await handler.get('/p', {})).toMatchObject({
152
+ cacheControl: { revalidate: 3600, expire: 31536000 },
153
+ });
154
+ // the stale path keeps the lifetime: Next.js computes the stale time from it
155
+ vi.advanceTimersByTime(1000);
156
+ await handler.revalidateTag('bom:all', { expire: 31536000 });
157
+ const stale = await handler.get('/p', {});
158
+ expect(stale!.cacheControl).toEqual({ revalidate: 3600, expire: 31536000 });
159
+ expect(stale!.lastModified + 3600 * 1000).toBeLessThan(Date.now());
160
+ });
161
+
162
+ it('derives the lifetime of an entry written before cacheControl was stored', async () => {
163
+ const legacy = { lastModified: Date.now(), tags: [], revalidate: 900, value: page('') };
164
+ redis.store.set('bom:next:/old', encode(legacy));
165
+ expect((await new Handler().get('/old', {}))!.cacheControl).toEqual({
166
+ revalidate: 900,
167
+ expire: undefined,
168
+ });
169
+ redis.store.set('bom:next:/none', encode({ ...legacy, revalidate: null }));
170
+ expect((await new Handler().get('/none', {}))!.cacheControl).toBeUndefined();
171
+ });
172
+
141
173
  it('deletes on null and never throws while Redis is not ready', async () => {
142
174
  const handler = new Handler();
143
175
  await handler.set('/p', page('bom:all'), pageCtx);
@@ -151,3 +183,48 @@ describe('redis cache handler', () => {
151
183
  await expect(offline.revalidateTag('x')).resolves.toBeUndefined();
152
184
  });
153
185
  });
186
+
187
+ describe('shared redis client', () => {
188
+ afterEach(() => {
189
+ delete process.env.REDIS_URL;
190
+ delete (globalThis as { __bomRedisClient?: unknown }).__bomRedisClient;
191
+ });
192
+
193
+ it('is undefined without REDIS_URL', async () => {
194
+ expect(await getRedisClient()).toBeUndefined();
195
+ expect(await connectRedisClient(10)).toBeUndefined();
196
+ });
197
+
198
+ it('is one client per process, shared through globalThis, and waits for it to be ready', async () => {
199
+ const listeners = new Map<string, () => void>();
200
+ const client = {
201
+ isReady: false,
202
+ on: () => client,
203
+ once: (event: string, listener: () => void) => listeners.set(event, listener),
204
+ off: (event: string) => listeners.delete(event),
205
+ };
206
+ (globalThis as { __bomRedisClient?: unknown }).__bomRedisClient = client;
207
+ process.env.REDIS_URL = 'redis://localhost:6379';
208
+ expect(await getRedisClient()).toBeUndefined();
209
+ const connecting = connectRedisClient(2000);
210
+ await vi.advanceTimersByTimeAsync(10);
211
+ client.isReady = true;
212
+ listeners.get('ready')!();
213
+ expect(await connecting).toBe(client);
214
+ });
215
+
216
+ it('gives up after the timeout and leaves no listener behind', async () => {
217
+ const listeners = new Map<string, () => void>();
218
+ const client = {
219
+ isReady: false,
220
+ once: (event: string, listener: () => void) => listeners.set(event, listener),
221
+ off: (event: string) => listeners.delete(event),
222
+ };
223
+ (globalThis as { __bomRedisClient?: unknown }).__bomRedisClient = client;
224
+ process.env.REDIS_URL = 'redis://localhost:6379';
225
+ const connecting = connectRedisClient(2000);
226
+ await vi.advanceTimersByTimeAsync(2001);
227
+ expect(await connecting).toBeUndefined();
228
+ expect(listeners.size).toBe(0);
229
+ });
230
+ });
@@ -3,8 +3,12 @@
3
3
  * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:
4
4
  * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.
5
5
  *
6
- * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, value }` (in this
7
- * order: the cache panel reads the head of the value without parsing the page).
6
+ * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in
7
+ * this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored
8
+ * `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or
9
+ * prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).
10
+ * - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from
11
+ * node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).
8
12
  * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.
9
13
  * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),
10
14
  * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).
@@ -87,13 +91,28 @@ type CacheValue = {
87
91
  headers?: Record<string, string | string[] | undefined>;
88
92
  };
89
93
 
94
+ /** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */
95
+ type StoredCacheControl = { revalidate: number | false; expire: number | undefined };
96
+
90
97
  type StoredEntry = {
91
98
  lastModified: number;
92
99
  tags: string[];
93
100
  revalidate: number | false | null;
101
+ /** Absent on entries written before 4.0.0-next.12. */
102
+ cacheControl?: StoredCacheControl;
94
103
  value: CacheValue;
95
104
  };
96
105
 
106
+ /** The lifetime returned with an entry, so every instance applies the one it was written with. */
107
+ function cacheControlOf(entry: StoredEntry): StoredCacheControl | undefined {
108
+ if (entry.cacheControl) {
109
+ return entry.cacheControl;
110
+ }
111
+ return typeof entry.revalidate === 'number' || entry.revalidate === false
112
+ ? { revalidate: entry.revalidate, expire: undefined }
113
+ : undefined;
114
+ }
115
+
97
116
  /** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */
98
117
  export function entryTags(
99
118
  value: CacheValue | null | undefined,
@@ -120,18 +139,28 @@ function revalidateOf(
120
139
 
121
140
  type ConnectingClient = RedisLike & {
122
141
  on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;
142
+ once(event: 'ready', listener: () => void): unknown;
143
+ off(event: 'ready', listener: () => void): unknown;
123
144
  connect(): Promise<unknown>;
124
145
  };
125
146
 
126
- let sharedClient: ConnectingClient | undefined;
147
+ /**
148
+ * The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the
149
+ * instrumentation are bundled into the app, and module state would give each its own connection.
150
+ */
151
+ const shared = globalThis as typeof globalThis & { __bomRedisClient?: ConnectingClient };
127
152
 
128
153
  /** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */
129
154
  export async function getRedisClient(): Promise<RedisLike | undefined> {
130
155
  if (!process.env.REDIS_URL) {
131
156
  return undefined;
132
157
  }
133
- if (!sharedClient) {
158
+ if (!shared.__bomRedisClient) {
134
159
  const { createClient } = await import('redis');
160
+ // another caller may have created it while the module loaded
161
+ if (shared.__bomRedisClient) {
162
+ return getRedisClient();
163
+ }
135
164
  const client = createClient({
136
165
  url: process.env.REDIS_URL,
137
166
  // fail fast while disconnected instead of queueing commands behind a dead socket
@@ -141,7 +170,7 @@ export async function getRedisClient(): Promise<RedisLike | undefined> {
141
170
  reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),
142
171
  },
143
172
  }) as unknown as ConnectingClient;
144
- sharedClient = client;
173
+ shared.__bomRedisClient = client;
145
174
  let logged = false;
146
175
  client.on('error', (error: Error) => {
147
176
  if (!logged) {
@@ -156,9 +185,37 @@ export async function getRedisClient(): Promise<RedisLike | undefined> {
156
185
  /* reported by the error listener, retried by reconnectStrategy */
157
186
  });
158
187
  }
188
+ const sharedClient = shared.__bomRedisClient;
159
189
  return sharedClient.isReady ? sharedClient : undefined;
160
190
  }
161
191
 
192
+ /**
193
+ * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that
194
+ * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance
195
+ * already reads Redis.
196
+ */
197
+ export async function connectRedisClient(timeout = 2000): Promise<RedisLike | undefined> {
198
+ const ready = await getRedisClient();
199
+ const client = shared.__bomRedisClient;
200
+ if (ready || !client) {
201
+ return ready;
202
+ }
203
+ await new Promise<void>((resolve) => {
204
+ const done = { timer: undefined as ReturnType<typeof setTimeout> | undefined };
205
+ const onReady = () => {
206
+ clearTimeout(done.timer);
207
+ resolve();
208
+ };
209
+ // no listener left behind while Redis stays down and the panel keeps asking
210
+ done.timer = setTimeout(() => {
211
+ client.off('ready', onReady);
212
+ resolve();
213
+ }, timeout);
214
+ client.once('ready', onReady);
215
+ });
216
+ return client.isReady ? client : undefined;
217
+ }
218
+
162
219
  /** Builds the handler class around a client getter, so tests can inject one. */
163
220
  export function createRedisCacheHandler(
164
221
  getClient: () => Promise<RedisLike | undefined> = getRedisClient,
@@ -182,8 +239,9 @@ export function createRedisCacheHandler(
182
239
  const tags = [
183
240
  ...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),
184
241
  ];
242
+ const cacheControl = cacheControlOf(entry);
185
243
  if (!tags.length) {
186
- return { lastModified: entry.lastModified, value: entry.value };
244
+ return { lastModified: entry.lastModified, value: entry.value, cacheControl };
187
245
  }
188
246
  const [expired, stale] = await Promise.all([
189
247
  client.mGet(tags.map((tag) => k.expired + tag)),
@@ -203,9 +261,10 @@ export function createRedisCacheHandler(
203
261
  return {
204
262
  lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),
205
263
  value: entry.value,
264
+ cacheControl,
206
265
  };
207
266
  }
208
- return { lastModified: entry.lastModified, value: entry.value };
267
+ return { lastModified: entry.lastModified, value: entry.value, cacheControl };
209
268
  } catch {
210
269
  return null;
211
270
  }
@@ -221,10 +280,13 @@ export function createRedisCacheHandler(
221
280
  await client.del([k.entry + key, k.meta + key]);
222
281
  return;
223
282
  }
283
+ const revalidate = revalidateOf(data, ctx);
224
284
  const entry: StoredEntry = {
225
285
  lastModified: Date.now(),
226
286
  tags: entryTags(data, ctx),
227
- revalidate: revalidateOf(data, ctx),
287
+ revalidate,
288
+ cacheControl:
289
+ revalidate === null ? undefined : { revalidate, expire: ctx?.cacheControl?.expire },
228
290
  value: data,
229
291
  };
230
292
  const raw = encode(entry);
@@ -1,3 +1,9 @@
1
1
  // `next.config` `cacheHandler`: the shared Redis incremental cache (ISR, route handlers, data cache).
2
- export { createRedisCacheHandler, decode, encode, getRedisClient } from '../cache-handler/redis';
2
+ export {
3
+ connectRedisClient,
4
+ createRedisCacheHandler,
5
+ decode,
6
+ encode,
7
+ getRedisClient,
8
+ } from '../cache-handler/redis';
3
9
  export { default } from '../cache-handler/redis';
@@ -6,6 +6,12 @@ export async function registerIntrumentation() {
6
6
  // the cache panel (Bowl admin) reaches this site runtime in process instead of over HTTP
7
7
  const { registerLocalCacheExecutor } = await import('../server/cache/local-executor');
8
8
  registerLocalCacheExecutor();
9
+ if (process.env.REDIS_URL && process.env.NEXT_PHASE !== 'phase-production-build') {
10
+ // connect the shared cache client before the first request, so a cold instance already reads Redis (at most
11
+ // the 2 s connect timeout while Redis is down; pages then render uncached)
12
+ const { connectRedisClient } = await import('../cache-handler/redis');
13
+ await connectRedisClient();
14
+ }
9
15
  }
10
16
  if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
11
17
  if (process.env.NEXT_RUNTIME === 'nodejs') {
@@ -1,4 +1,9 @@
1
- import { getRedisClient, keys, redisPrefix, type RedisLike } from '../../../cache-handler/redis';
1
+ import {
2
+ connectRedisClient,
3
+ keys,
4
+ redisPrefix,
5
+ type RedisLike,
6
+ } from '../../../cache-handler/redis';
2
7
  import { tagState, type UseCacheMeta } from '../../../cache-handlers/default';
3
8
  import { explicitTags } from './filesystem';
4
9
  import { parseRouteCacheKey } from './route-cache-key';
@@ -26,7 +31,8 @@ const maxEntries = 20_000;
26
31
  * Entries written by an older handler without meta keys are not listed.
27
32
  */
28
33
  export function createRedisInspector({
29
- getClient = getRedisClient as () => Promise<RedisScanner | undefined>,
34
+ // the panel may wait for the connection: on a cold instance the client is not ready yet
35
+ getClient = connectRedisClient as () => Promise<RedisScanner | undefined>,
30
36
  prefix = redisPrefix(),
31
37
  }: { getClient?: () => Promise<RedisScanner | undefined>; prefix?: string } = {}): CacheInspector {
32
38
  const k = keys(prefix);