tricache 1.0.0 → 1.0.2

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.
Files changed (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
@@ -1,8 +1,9 @@
1
1
  import { CacheService } from '../cache-service';
2
- import { consoleLogger } from '../types';
2
+ import { CachePriority, consoleLogger } from '../types';
3
3
  import type { ILogger } from '../types';
4
4
  import type {
5
5
  CacheHandlerValue,
6
+ NextCacheEntry,
6
7
  StoredNextCacheEntry,
7
8
  CacheHandlerContext,
8
9
  NextCacheHandlerOptions,
@@ -55,22 +56,34 @@ export function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifeProf
55
56
  /**
56
57
  * Drain incoming web ReadableStream into a contiguous Node Buffer.
57
58
  */
58
- async function drainStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {
59
+ async function drainStream(stream: ReadableStream<Uint8Array>, maxBytes: number): Promise<Buffer> {
59
60
  const reader = stream.getReader();
60
61
  const chunks: Uint8Array[] = [];
61
- while (true) {
62
- const { done, value } = await reader.read();
63
- if (done) break;
64
- if (value) chunks.push(value);
62
+ let size = 0;
63
+ try {
64
+ while (true) {
65
+ const { done, value } = await reader.read();
66
+ if (done) break;
67
+ if (value) {
68
+ size += value.byteLength;
69
+ if (size > maxBytes) throw new Error('RSC stream exceeds maxStreamBytes');
70
+ chunks.push(Uint8Array.from(value));
71
+ }
72
+ }
73
+ return Buffer.concat(chunks);
74
+ } catch (error) {
75
+ void reader.cancel(error).catch(() => {});
76
+ throw error;
77
+ } finally {
78
+ reader.releaseLock();
65
79
  }
66
- return Buffer.concat(chunks);
67
80
  }
68
81
 
69
82
  /**
70
83
  * Construct a fresh, unlocked ReadableStream from a buffer.
71
84
  */
72
85
  function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8Array> {
73
- const uint8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
86
+ const uint8 = Uint8Array.from(buffer);
74
87
  return new ReadableStream<Uint8Array>({
75
88
  start(controller) {
76
89
  controller.enqueue(uint8);
@@ -87,9 +100,15 @@ function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8
87
100
  export class TriCacheHandler {
88
101
  protected readonly cache: CacheService;
89
102
  protected readonly logger: ILogger;
103
+ private readonly maxStreamBytes: number;
104
+ private readonly pendingSets = new Map<string, { token: symbol; completion: Promise<void> }>();
105
+ private readonly observedTags = new Map<string, { version: number; observedAt: number }>();
90
106
 
91
107
  constructor(options: NextCacheHandlerOptions = {}) {
92
108
  this.logger = options.logger ?? consoleLogger;
109
+ this.maxStreamBytes = options.maxStreamBytes ?? 16 * 1024 * 1024;
110
+ if (!Number.isFinite(this.maxStreamBytes) || this.maxStreamBytes <= 0) throw new Error('maxStreamBytes must be finite and positive');
111
+ if (options.tagStrategy && options.tagStrategy !== 'generational') throw new Error('Next.js cache handlers require tagStrategy: generational');
93
112
 
94
113
  const isBuildPhase =
95
114
  options.isBuildPhase ??
@@ -110,31 +129,59 @@ export class TriCacheHandler {
110
129
  * Get an entry from cache. Checks softTags against generational tag versions
111
130
  * and returns a fresh unlocked ReadableStream if the stored value was a stream.
112
131
  */
113
- async get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined> {
114
- const stored = await this.cache.get<StoredNextCacheEntry | null>(
115
- cacheKey,
116
- async () => null,
117
- );
132
+ async get(cacheKey: string, softTags: string[]): Promise<NextCacheEntry | undefined>;
133
+ async get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined>;
134
+ async get(cacheKey: string, context?: CacheHandlerContext | string[]): Promise<CacheHandlerValue | undefined> {
135
+ let pending = this.pendingSets.get(cacheKey);
136
+ while (pending) {
137
+ await pending.completion;
138
+ pending = this.pendingSets.get(cacheKey);
139
+ }
140
+ const native = Array.isArray(context);
141
+ const ctx = native ? { softTags: context } : context;
142
+ const stored = await this.cache.peek<StoredNextCacheEntry>(cacheKey);
118
143
 
119
144
  if (!stored || stored.data == null) {
120
145
  return undefined;
121
146
  }
122
147
 
123
- // Check softTags at read time (e.g. Next.js 16 layout / page boundaries)
124
- if (ctx?.softTags && ctx.softTags.length > 0) {
125
- const softTags = ctx.softTags;
126
- const currentVers = await Promise.all(softTags.map(st => this.cache.getTagVersion(st)));
127
- for (let i = 0; i < softTags.length; i++) {
128
- const storedSoftVer = stored.softTagVersions?.[softTags[i]] ?? 0;
129
- if (currentVers[i] > storedSoftVer) {
130
- return undefined;
148
+ const expire = stored.expire ?? stored.ttl;
149
+ if (!Number.isFinite(stored.timestamp) || !Number.isFinite(expire) || Date.now() >= stored.timestamp + expire * 1000) return undefined;
150
+ const tags = [...new Set([...stored.tags, ...ctx?.softTags ?? []])];
151
+ const versions = await Promise.all(tags.map(tag => this.cache.getTagVersion(tag)));
152
+ const states = await this.cache.mget<{ revalidatedAt: number; expiredAt?: number }>(tags.map(tag => `_next_tag_state_:${tag}`));
153
+ let revalidate = stored.revalidate ?? stored.ttl;
154
+ for (let index = 0; index < tags.length; index++) {
155
+ const tag = tags[index];
156
+ const state = states[index];
157
+ const snapshot = stored.generations?.[tag] ?? stored.softTagVersions?.[tag];
158
+ if (state && (state.revalidatedAt > stored.timestamp || state.revalidatedAt === stored.timestamp && snapshot !== versions[index])) {
159
+ if (state.expiredAt !== undefined && state.expiredAt <= Date.now()) return undefined;
160
+ revalidate = -1; // Next.js serves stale and computes a replacement in the background.
161
+ } else if (!state && versions[index] > 0) {
162
+ if (snapshot !== undefined && versions[index] > snapshot) return undefined;
163
+ if (snapshot === undefined) {
164
+ const observed = this.observeTag(tag, versions[index]);
165
+ if (stored.timestamp <= observed) return undefined;
131
166
  }
132
167
  }
133
168
  }
134
169
 
135
170
  let val = stored.data;
136
- if (stored.isStream && (Buffer.isBuffer(val) || val instanceof Uint8Array)) {
137
- val = createReadableStream(val);
171
+ if (stored.isStream) {
172
+ let bytes: Uint8Array;
173
+ if (stored.streamEncoding === 'base64' && typeof val === 'string') {
174
+ if (val.length > Math.ceil(this.maxStreamBytes / 3) * 4) return undefined;
175
+ bytes = Buffer.from(val, 'base64');
176
+ }
177
+ else if (Buffer.isBuffer(val) || val instanceof Uint8Array) bytes = val;
178
+ else if (val && typeof val === 'object' && (val as { type?: unknown }).type === 'Buffer' && Array.isArray((val as { data?: unknown }).data)) {
179
+ bytes = Buffer.from((val as { data: number[] }).data);
180
+ } else return undefined;
181
+ if (bytes.length > this.maxStreamBytes) return undefined;
182
+ val = createReadableStream(bytes);
183
+ } else if (native) {
184
+ return undefined; // Legacy plain-object entries are not native RSC CacheEntry streams.
138
185
  }
139
186
 
140
187
  return {
@@ -142,6 +189,9 @@ export class TriCacheHandler {
142
189
  tags: stored.tags,
143
190
  timestamp: stored.timestamp,
144
191
  ttl: stored.ttl,
192
+ stale: stored.stale ?? 300,
193
+ revalidate,
194
+ expire,
145
195
  };
146
196
  }
147
197
 
@@ -154,8 +204,17 @@ export class TriCacheHandler {
154
204
  pendingEntry: Promise<CacheHandlerValue | null>,
155
205
  ctx?: CacheHandlerContext,
156
206
  ): Promise<void> {
207
+ const token = Symbol(cacheKey);
208
+ let finish!: () => void;
209
+ const completion = new Promise<void>(resolve => { finish = resolve; });
210
+ this.pendingSets.set(cacheKey, { token, completion });
211
+ try {
212
+ const canCommit = this.cache.captureMutationFence(cacheKey);
157
213
  const entry = await pendingEntry;
158
214
  if (!entry || entry.value == null) return;
215
+ const tags = Array.from(new Set([...(entry.tags ?? []), ...(ctx?.tags ?? [])]));
216
+ const allTags = [...new Set([...tags, ...ctx?.softTags ?? []])];
217
+ const initialVersions = Object.fromEntries(await Promise.all(allTags.map(async tag => [tag, await this.cache.getTagVersion(tag)])));
159
218
 
160
219
  let dataToStore = entry.value;
161
220
  const isStream = Boolean(
@@ -165,7 +224,7 @@ export class TriCacheHandler {
165
224
 
166
225
  if (isStream) {
167
226
  try {
168
- dataToStore = await drainStream(dataToStore as ReadableStream<Uint8Array>);
227
+ dataToStore = (await drainStream(dataToStore as ReadableStream<Uint8Array>, this.maxStreamBytes)).toString('base64');
169
228
  } catch (streamErr) {
170
229
  this.logger.debug('Next.js cacheHandler: stream drain failed mid-flight, skipping cache', {
171
230
  cacheKey,
@@ -179,6 +238,8 @@ export class TriCacheHandler {
179
238
  const resolvedLife = resolveCacheLife(ctx?.cacheLife);
180
239
  if (resolvedLife) {
181
240
  ttl = resolvedLife.ttl;
241
+ } else if (typeof entry.revalidate === 'number') {
242
+ ttl = entry.revalidate;
182
243
  } else if (typeof entry.ttl === 'number') {
183
244
  ttl = entry.ttl;
184
245
  } else if (typeof ctx?.revalidate === 'number') {
@@ -190,7 +251,15 @@ export class TriCacheHandler {
190
251
  ttl = 300; // fallback default
191
252
  }
192
253
 
193
- const tags = Array.from(new Set([...(entry.tags ?? []), ...(ctx?.tags ?? [])]));
254
+ const expire = entry.expire ?? (resolvedLife ? resolvedLife.ttl + resolvedLife.swr : ttl);
255
+ const timestamp = entry.timestamp ?? Date.now();
256
+ if (!Number.isFinite(expire) || expire <= 0 || !Number.isFinite(timestamp) || timestamp > Date.now() + (this.cache.options.clockSkewToleranceMs ?? 250)) return;
257
+ const remaining = timestamp + expire * 1000 - Date.now();
258
+ if (remaining <= 0 || !canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
259
+ const finalVersions = await Promise.all(allTags.map(tag => this.cache.getTagVersion(tag)));
260
+ if (allTags.some((tag, index) => finalVersions[index] !== initialVersions[tag])) return;
261
+ const tagStates = await this.cache.mget<{ revalidatedAt: number }>(allTags.map(tag => `_next_tag_state_:${tag}`));
262
+ if (tagStates.some(state => state && state.revalidatedAt > timestamp)) return;
194
263
 
195
264
  let softTagVersions: Record<string, number> | undefined;
196
265
  if (ctx?.softTags && ctx.softTags.length > 0) {
@@ -206,52 +275,52 @@ export class TriCacheHandler {
206
275
  data: dataToStore,
207
276
  isStream,
208
277
  tags,
209
- timestamp: entry.timestamp ?? Date.now(),
278
+ timestamp,
210
279
  ttl,
211
280
  softTagVersions,
281
+ generations: initialVersions,
282
+ stale: entry.stale ?? (typeof ctx?.cacheLife === 'string' ? PRESET_CACHE_LIFE_PROFILES[ctx.cacheLife as CacheLifePreset]?.stale : typeof ctx?.cacheLife === 'object' ? ctx.cacheLife.stale : undefined) ?? 300,
283
+ revalidate: ttl,
284
+ expire,
285
+ streamEncoding: isStream ? 'base64' : undefined,
212
286
  };
213
287
 
214
- await this.cache.set(cacheKey, stored, ttl, undefined, tags.length > 0 ? { tags } : undefined);
288
+ if (!canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
289
+ // Next owns delayed tag expiry. Eager engine tags would delete SWR entries
290
+ // before Next could return revalidate:-1 and schedule their replacement.
291
+ await this.cache.set(cacheKey, stored, remaining / 1000, undefined, { tags: [] });
292
+ } finally {
293
+ finish();
294
+ if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
295
+ }
296
+ }
297
+
298
+ private observeTag(tag: string, version: number): number {
299
+ const known = this.observedTags.get(tag);
300
+ if (known?.version === version) return known.observedAt;
301
+ if (this.observedTags.size >= 10000) {
302
+ const oldest = this.observedTags.keys().next().value;
303
+ if (oldest !== undefined) this.observedTags.delete(oldest);
304
+ }
305
+ const observedAt = Date.now();
306
+ this.observedTags.set(tag, { version, observedAt });
307
+ return observedAt;
215
308
  }
216
309
 
217
310
  /**
218
- * Returns the expiration timestamp (ms since epoch) of the most relevant
219
- * cached entry for the given tags, or 0 when nothing is tracked. Next.js
220
- * uses this to decide whether a revalidation is due — a hardcoded 0 means
221
- * "always expired", so this reads the real stored entries instead.
311
+ * Delegate soft-tag checking to get() using Next's Infinity sentinel.
222
312
  */
223
313
  async getExpiration(tags: string[]): Promise<number> {
224
- try {
225
- let maxExpiration = 0;
226
- const tagSet = new Set(tags);
227
- const l1 = (this.cache as unknown as { l1: { scan(fn: (key: string, entry: { expiresAt?: number; tagVersions?: Record<string, number> }) => void, prefixLen: number): void } }).l1;
228
- l1.scan((key, entry) => {
229
- if (!entry.tagVersions) return;
230
- for (const tag of Object.keys(entry.tagVersions)) {
231
- if (!tagSet.has(tag)) continue;
232
- const exp = entry.expiresAt ?? 0;
233
- if (exp > maxExpiration) maxExpiration = exp;
234
- return;
235
- }
236
- }, 0);
237
- return maxExpiration;
238
- } catch (err) {
239
- this.logger.debug('Next.js cacheHandler getExpiration fail-soft', { error: (err as Error).message });
240
- return 0;
241
- }
314
+ // This is the native contract's explicit delegation sentinel, not an entry expiry.
315
+ return tags.length ? Infinity : 0;
242
316
  }
243
317
 
244
318
  /**
245
- * Reconcile local generational tag knowledge against shared state: drops the
246
- * in-memory tag-version cache so every subsequent read re-syncs versions
247
- * from Redis. The previous implementation was an empty try/catch.
319
+ * Force subsequent tag reads to re-sync without forgetting monotonic versions.
248
320
  */
249
321
  async refreshTags(): Promise<void> {
250
322
  try {
251
- const cache = this.cache as unknown as {
252
- tagVersions?: Map<string, unknown>;
253
- };
254
- cache.tagVersions?.clear();
323
+ this.cache.refreshTagVersions();
255
324
  } catch (err) {
256
325
  this.logger.debug('Next.js cacheHandler refreshTags fail-soft catch', {
257
326
  error: (err as Error).message,
@@ -262,8 +331,14 @@ export class TriCacheHandler {
262
331
  /**
263
332
  * Update or invalidate tags cluster-wide.
264
333
  */
265
- async updateTags(tags: string[]): Promise<void> {
334
+ async updateTags(tags: string[], durations?: { expire?: number }): Promise<void> {
266
335
  if (!tags || tags.length === 0) return;
336
+ const now = Date.now();
337
+ const delay = durations && durations.expire === undefined ? undefined : Math.max(0, durations?.expire ?? 0) * 1000;
338
+ if (delay !== undefined && !Number.isFinite(delay)) throw new Error('Tag expiry duration must be finite');
339
+ await Promise.all(tags.map(tag => this.cache.set(`_next_tag_state_:${tag}`, {
340
+ revalidatedAt: now, expiredAt: delay === undefined ? undefined : now + delay,
341
+ }, 0, CachePriority.HIGH)));
267
342
  await this.cache.invalidateTags(tags);
268
343
  }
269
344
  }
package/src/next/index.ts CHANGED
@@ -7,6 +7,7 @@ export {
7
7
  export { TriCacheISRHandler } from './isr-handler';
8
8
  export type {
9
9
  CacheHandlerValue,
10
+ NextCacheEntry,
10
11
  StoredNextCacheEntry,
11
12
  CacheHandlerContext,
12
13
  NextCacheHandlerOptions,
@@ -38,10 +38,7 @@ export class TriCacheISRHandler {
38
38
  return this.requestCache.get(key) ?? null;
39
39
  }
40
40
 
41
- const stored = await this.cache.get<IncrementalCacheEntry | null>(
42
- key,
43
- async () => null,
44
- );
41
+ const stored = await this.cache.peek<IncrementalCacheEntry>(key);
45
42
 
46
43
  if (stored) {
47
44
  this.requestCache.set(key, stored);
package/src/next/types.ts CHANGED
@@ -20,6 +20,20 @@ export interface CacheHandlerValue {
20
20
  * Remaining / configured TTL (seconds).
21
21
  */
22
22
  ttl?: number;
23
+ /** Native Next.js CacheEntry timing fields, in seconds. */
24
+ stale?: number;
25
+ revalidate?: number;
26
+ expire?: number;
27
+ }
28
+
29
+ /** Complete native Next.js CacheEntry output, structurally checked against Next in tests. */
30
+ export interface NextCacheEntry {
31
+ value: ReadableStream<Uint8Array>;
32
+ tags: string[];
33
+ timestamp: number;
34
+ stale: number;
35
+ revalidate: number;
36
+ expire: number;
23
37
  }
24
38
 
25
39
  /**
@@ -38,6 +52,11 @@ export interface StoredNextCacheEntry {
38
52
  ttl: number;
39
53
  /** Captured soft tag versions at write time */
40
54
  softTagVersions?: Record<string, number>;
55
+ generations?: Record<string, number>;
56
+ stale?: number;
57
+ revalidate?: number;
58
+ expire?: number;
59
+ streamEncoding?: 'base64';
41
60
  }
42
61
 
43
62
  export type CacheLifePreset =
@@ -79,6 +98,8 @@ export interface NextCacheHandlerOptions extends CacheOptions {
79
98
  * or `process.env.NEXT_PHASE === 'phase-export'`.
80
99
  */
81
100
  isBuildPhase?: boolean;
101
+ /** Maximum buffered RSC stream size. Default: 16 MiB. */
102
+ maxStreamBytes?: number;
82
103
  }
83
104
 
84
105
  /**
@@ -67,8 +67,14 @@ const MUTATION_OPERATIONS = new Set([
67
67
 
68
68
  /** Recursively sorts object keys for deterministic serialization of nested query filters */
69
69
  function deterministicStringify(val: unknown): string {
70
+ if (val instanceof Date) return `date:${JSON.stringify(val.toISOString())}`;
71
+ if (typeof val === 'bigint') return `bigint:${val}`;
72
+ if (val instanceof Uint8Array) return `binary:${Buffer.from(val.buffer, val.byteOffset, val.byteLength).toString('base64')}`;
73
+ if (val && typeof val === 'object' && typeof (val as { toJSON?: unknown }).toJSON === 'function') {
74
+ return deterministicStringify((val as { toJSON(): unknown }).toJSON());
75
+ }
70
76
  if (val === null || typeof val !== 'object') {
71
- return JSON.stringify(val);
77
+ return JSON.stringify(val) ?? 'undefined';
72
78
  }
73
79
  if (Array.isArray(val)) {
74
80
  return `[${val.map(deterministicStringify).join(',')}]`;
@@ -118,6 +124,11 @@ export function withTriCache(options: PrismaTriCacheOptions) {
118
124
  const queryArgs = args ?? {};
119
125
  const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
120
126
 
127
+ if (cacheConfig === false) {
128
+ const { cache: _c, ...cleanArgs } = queryArgs;
129
+ return query(cleanArgs);
130
+ }
131
+
121
132
  if (cacheConfig !== undefined || autoCache) {
122
133
  const opts: PrismaCacheQueryOptions = typeof cacheConfig === 'object' && cacheConfig !== null
123
134
  ? cacheConfig
@@ -119,8 +119,9 @@ type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
119
119
  function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
120
120
  // Compute optimal bit-count for p = 1 % and the requested entry ceiling.
121
121
  const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
122
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
123
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
122
+ const capacity = Math.max(1, maxEntries);
123
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
124
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
124
125
 
125
126
  try {
126
127
  const wasm = new WasmBloomFilter();
@@ -310,7 +311,10 @@ export class SmartMemoryCache {
310
311
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
311
312
  this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
312
313
  if (opts.admissionPolicy === 'wtinylfu') {
313
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
314
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.80, key => {
315
+ const entry = this.cache.get(key);
316
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
317
+ });
314
318
  }
315
319
 
316
320
  if (existing) {
@@ -403,6 +407,7 @@ export class SmartMemoryCache {
403
407
  const MAX_EVICT_PASSES = 64;
404
408
  let passes = 0;
405
409
  do {
410
+ const before = this.cache.size;
406
411
  this.smartEvict(category, catOvf);
407
412
  const lim2 = this.getCategoryLimit(category);
408
413
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -410,6 +415,7 @@ export class SmartMemoryCache {
410
415
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
411
416
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
412
417
  passes++;
418
+ if (this.cache.size === before) break; // Only protected entries remain.
413
419
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
414
420
  }
415
421
 
@@ -564,6 +570,8 @@ export class SmartMemoryCache {
564
570
  fetchedAt: now,
565
571
  tagVersions: entry.tagVersions,
566
572
  setAt: entry.setAt,
573
+ tags: entry.tags,
574
+ dependsOn: entry.dependsOn,
567
575
  };
568
576
  return hit;
569
577
  }
@@ -576,10 +584,21 @@ export class SmartMemoryCache {
576
584
  staleAt?: number,
577
585
  delta?: number,
578
586
  tagVersions?: Record<string, number>,
579
- ): void {
587
+ setAt?: number,
588
+ tags?: string[],
589
+ dependsOn?: string[],
590
+ ): boolean {
580
591
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
581
592
  // "size probe" that was discarded for large payloads (the double-pass).
582
593
  const packed = this.codec.encode(data);
594
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
595
+ }
596
+
597
+ private storePacked(
598
+ key: string, packed: Buffer, data: unknown, ttlMs: number, priority: CachePriority,
599
+ staleAt?: number, delta?: number, tagVersions?: Record<string, number>, setAt?: number,
600
+ tags?: string[], dependsOn?: string[],
601
+ ): boolean {
583
602
  const size = packed.byteLength;
584
603
  this.compressions++;
585
604
  this.sketch.increment(key);
@@ -587,9 +606,11 @@ export class SmartMemoryCache {
587
606
  const cat = this.getCategory(key);
588
607
  const lim = this.getCategoryLimit(cat);
589
608
 
590
- if (size > lim.maxSizeBytes * 0.5) {
609
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 ||
610
+ size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
611
+ this.delete(key); // An oversized replacement must not leave the old value readable.
591
612
  this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
592
- return;
613
+ return false;
593
614
  }
594
615
 
595
616
  // Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
@@ -621,11 +642,13 @@ export class SmartMemoryCache {
621
642
  priority,
622
643
  ttlMs,
623
644
  delta,
624
- setAt: now,
645
+ setAt: setAt ?? now,
625
646
  tagVersions,
647
+ tags,
648
+ dependsOn,
626
649
  });
627
650
  }
628
- return;
651
+ return false;
629
652
  } else if (decision.candidateKey) {
630
653
  // An older window candidate was rejected to make room for key
631
654
  const candEntry = this.cache.get(decision.candidateKey);
@@ -643,21 +666,28 @@ export class SmartMemoryCache {
643
666
  this._delete(decision.evictKey, 'capacity');
644
667
  }
645
668
 
646
- // Check category byte limit or total byte limit
669
+ // Count and byte limits apply to TinyLFU too, including category quotas.
647
670
  const catSz = this.categorySize.get(cat) ?? 0;
648
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
671
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries ||
672
+ catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
649
673
  this.ensureCapacity(cat, size);
650
674
  }
651
675
  } else {
652
676
  this.ensureCapacity(cat, size);
653
677
  }
654
678
 
679
+ if (this.cache.size >= this.opts.maxEntries || (this.categoryCount.get(cat) ?? 0) >= lim.maxEntries ||
680
+ this.totalSize + size > this.opts.maxBytes || (this.categorySize.get(cat) ?? 0) + size > lim.maxSizeBytes) {
681
+ this.wtinyPolicy?.onDelete(key);
682
+ return false;
683
+ }
684
+
655
685
  const now = Date.now();
656
686
  // Only cache the live object for small entries — large entries would store the packed
657
687
  // buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
658
688
  // For large entries, get() falls back to the unpack() path transparently.
659
689
  const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
660
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
690
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions, tags, dependsOn });
661
691
  // Only add new keys to the bloom — overwrites already have their bits set.
662
692
  // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
663
693
  if (!existingEntry) this.bloom.add(key);
@@ -668,6 +698,7 @@ export class SmartMemoryCache {
668
698
  let ks = this.categoryKeys.get(cat);
669
699
  if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
670
700
  ks.add(key);
701
+ return true;
671
702
  }
672
703
 
673
704
  delete(key: string): boolean {
@@ -900,7 +931,8 @@ export class SmartMemoryCache {
900
931
  if (entry.expiresAt <= now) continue;
901
932
  if (entry.priority === 4 /* CRITICAL */) continue;
902
933
  if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
903
- out.push({ key, entry: { ...entry } });
934
+ const { value: _value, ...stored } = entry;
935
+ out.push({ key, entry: { ...stored } });
904
936
  }
905
937
  return out;
906
938
  }
@@ -908,24 +940,30 @@ export class SmartMemoryCache {
908
940
  importEntries(entries: Array<{ key: string; entry: SmartCacheEntry }>, forbiddenPrefixes: readonly string[]): number {
909
941
  const now = Date.now();
910
942
  let loaded = 0;
911
- for (const { key, entry } of entries) {
912
- if (entry.expiresAt <= now) continue;
943
+ for (const item of entries) {
944
+ if (!item || typeof item.key !== 'string' || !item.entry) continue;
945
+ const { key, entry } = item;
946
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
913
947
  if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
914
948
  if (this.cache.has(key)) continue;
915
- const rawData = entry.data;
916
- // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
917
- const data: Buffer = !entry.isCompressed
918
- ? this.codec.encode(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
919
- : rawData instanceof Uint8Array
920
- ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
921
- : rawData as Buffer; // already a Buffer
922
- // Cache the live object for small entries only — large entries skip double-heap storage.
923
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
924
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
925
- this.bloom.add(key);
926
- loaded++;
949
+ try {
950
+ const rawData = entry.data;
951
+ const data = !entry.isCompressed
952
+ ? this.codec.encode(JSON.parse(rawData as unknown as string))
953
+ : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
954
+ if (!data) continue;
955
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
956
+ if (this.storePacked(key, data, value, entry.expiresAt - now, entry.priority, entry.staleAt,
957
+ entry.delta, entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn)) {
958
+ const restored = this.cache.get(key)!;
959
+ restored.expiresAt = entry.expiresAt;
960
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
961
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
962
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
963
+ loaded++;
964
+ }
965
+ } catch { /* One corrupt snapshot entry must not discard the healthy entries. */ }
927
966
  }
928
- this.recalculateStats();
929
967
  return loaded;
930
968
  }
931
969