tricache 1.0.1 → 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 (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.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-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  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 +1370 -624
  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 +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  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-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  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 +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  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-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -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 +106 -27
  61. package/src/cache-service.ts +802 -502
  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 +145 -97
  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 +62 -17
  74. package/src/http/fastify.ts +35 -21
  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 +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,232 @@
1
+ import { C as CacheService } from '../cache-service-CWI4jkS7.cjs';
2
+ import { C as CacheOptions, i as ILogger } from '../types-BA4pz1A0.cjs';
3
+ import 'crypto';
4
+
5
+ /**
6
+ * Next.js 16 modern CacheHandler value shape for `"use cache"` components.
7
+ */
8
+ interface CacheHandlerValue {
9
+ /**
10
+ * Cached value — either a ReadableStream (for RSC payloads), or a serializable JS object / string.
11
+ */
12
+ value: unknown;
13
+ /**
14
+ * Tags associated with this cache entry at write time.
15
+ */
16
+ tags?: string[];
17
+ /**
18
+ * Stored timestamp (ms).
19
+ */
20
+ timestamp?: number;
21
+ /**
22
+ * Remaining / configured TTL (seconds).
23
+ */
24
+ ttl?: number;
25
+ /** Native Next.js CacheEntry timing fields, in seconds. */
26
+ stale?: number;
27
+ revalidate?: number;
28
+ expire?: number;
29
+ }
30
+ /** Complete native Next.js CacheEntry output, structurally checked against Next in tests. */
31
+ interface NextCacheEntry {
32
+ value: ReadableStream<Uint8Array>;
33
+ tags: string[];
34
+ timestamp: number;
35
+ stale: number;
36
+ revalidate: number;
37
+ expire: number;
38
+ }
39
+ /**
40
+ * Stored representation in TriCache for Next.js CacheHandler entries.
41
+ */
42
+ interface StoredNextCacheEntry {
43
+ /** Serialized payload or binary buffer (for streams) */
44
+ data: unknown;
45
+ /** Indicates whether the original value was a ReadableStream */
46
+ isStream: boolean;
47
+ /** Associated tags */
48
+ tags: string[];
49
+ /** Creation timestamp */
50
+ timestamp: number;
51
+ /** Configured TTL (seconds) */
52
+ ttl: number;
53
+ /** Captured soft tag versions at write time */
54
+ softTagVersions?: Record<string, number>;
55
+ generations?: Record<string, number>;
56
+ stale?: number;
57
+ revalidate?: number;
58
+ expire?: number;
59
+ streamEncoding?: 'base64';
60
+ }
61
+ type CacheLifePreset = 'default' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'max';
62
+ interface CacheLifeProfile {
63
+ stale?: number;
64
+ revalidate?: number;
65
+ expire?: number;
66
+ }
67
+ /**
68
+ * Context passed to CacheHandler methods by Next.js runtime.
69
+ */
70
+ interface CacheHandlerContext {
71
+ tags?: string[];
72
+ softTags?: string[];
73
+ revalidate?: number | false;
74
+ cacheLife?: CacheLifePreset | CacheLifeProfile | string;
75
+ }
76
+ /**
77
+ * Options for configuring TriCache Next.js integration.
78
+ */
79
+ interface NextCacheHandlerOptions extends CacheOptions {
80
+ /**
81
+ * Custom namespace for Next.js cache entries. Default: `'next'`
82
+ */
83
+ namespace?: string;
84
+ /**
85
+ * Explicitly force in-memory build phase mode (skips Redis socket connections).
86
+ * Automatically inferred when `process.env.NEXT_PHASE === 'phase-production-build'`
87
+ * or `process.env.NEXT_PHASE === 'phase-export'`.
88
+ */
89
+ isBuildPhase?: boolean;
90
+ /** Maximum buffered RSC stream size. Default: 16 MiB. */
91
+ maxStreamBytes?: number;
92
+ }
93
+ /**
94
+ * Legacy Next.js IncrementalCache value shape.
95
+ */
96
+ type IncrementalCacheValue = {
97
+ kind: 'PAGE';
98
+ html: string;
99
+ pageData: unknown;
100
+ headers?: Record<string, string | string[]>;
101
+ status?: number;
102
+ } | {
103
+ kind: 'FETCH';
104
+ data: {
105
+ headers: Record<string, string>;
106
+ body: string;
107
+ status?: number;
108
+ url?: string;
109
+ };
110
+ } | {
111
+ kind: 'REDIRECT';
112
+ props: Record<string, unknown>;
113
+ } | {
114
+ kind: 'IMAGE';
115
+ etag: string;
116
+ buffer: Buffer;
117
+ extension: string;
118
+ isAppImage?: boolean;
119
+ } | {
120
+ kind: 'ROUTE';
121
+ body: Buffer;
122
+ status: number;
123
+ headers: Record<string, string | string[]>;
124
+ };
125
+ /**
126
+ * Legacy Next.js IncrementalCache entry shape.
127
+ */
128
+ interface IncrementalCacheEntry {
129
+ curRevalidate?: number | false;
130
+ revalidateAfter?: number | false;
131
+ isStale?: boolean;
132
+ value: IncrementalCacheValue | null;
133
+ }
134
+
135
+ /**
136
+ * Built-in Next.js 16 cacheLife preset profile timings (in seconds).
137
+ */
138
+ declare const PRESET_CACHE_LIFE_PROFILES: Record<CacheLifePreset, {
139
+ stale: number;
140
+ revalidate: number;
141
+ expire: number;
142
+ }>;
143
+ /**
144
+ * Resolve a Next.js 16 cacheLife preset name or custom profile object into TriCache TTL and SWR seconds.
145
+ */
146
+ declare function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifeProfile | string): {
147
+ ttl: number;
148
+ swr: number;
149
+ } | null;
150
+ /**
151
+ * Modern Next.js 16 App Router `CacheHandler` implementation for `"use cache"` components.
152
+ *
153
+ * Implements the 5-method contract: `get`, `set`, `refreshTags`, `getExpiration`, `updateTags`.
154
+ */
155
+ declare class TriCacheHandler {
156
+ protected readonly cache: CacheService;
157
+ protected readonly logger: ILogger;
158
+ private readonly maxStreamBytes;
159
+ private readonly pendingSets;
160
+ private readonly observedTags;
161
+ constructor(options?: NextCacheHandlerOptions);
162
+ /**
163
+ * Get an entry from cache. Checks softTags against generational tag versions
164
+ * and returns a fresh unlocked ReadableStream if the stored value was a stream.
165
+ */
166
+ get(cacheKey: string, softTags: string[]): Promise<NextCacheEntry | undefined>;
167
+ get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined>;
168
+ /**
169
+ * Write an entry into cache. Drains incoming ReadableStream into a contiguous buffer
170
+ * before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
171
+ */
172
+ set(cacheKey: string, pendingEntry: Promise<CacheHandlerValue | null>, ctx?: CacheHandlerContext): Promise<void>;
173
+ private observeTag;
174
+ /**
175
+ * Delegate soft-tag checking to get() using Next's Infinity sentinel.
176
+ */
177
+ getExpiration(tags: string[]): Promise<number>;
178
+ /**
179
+ * Force subsequent tag reads to re-sync without forgetting monotonic versions.
180
+ */
181
+ refreshTags(): Promise<void>;
182
+ /**
183
+ * Update or invalidate tags cluster-wide.
184
+ */
185
+ updateTags(tags: string[], durations?: {
186
+ expire?: number;
187
+ }): Promise<void>;
188
+ }
189
+
190
+ /**
191
+ * Legacy Next.js 15/16 ISR `cacheHandler` implementation for Route Handlers and ISR pages.
192
+ *
193
+ * Implements the 4-method contract: `get`, `set`, `revalidateTag`, `resetRequestCache`.
194
+ */
195
+ declare class TriCacheISRHandler {
196
+ protected readonly cache: CacheService;
197
+ protected readonly requestCache: Map<string, IncrementalCacheEntry | null>;
198
+ constructor(options?: NextCacheHandlerOptions);
199
+ /**
200
+ * Read an entry from the cache. Checks the in-memory requestCache first before querying TriCache.
201
+ */
202
+ get(key: string): Promise<IncrementalCacheEntry | null>;
203
+ /**
204
+ * Set an entry in the cache.
205
+ */
206
+ set(key: string, data: IncrementalCacheValue | null, ctx?: {
207
+ tags?: string[];
208
+ revalidate?: number | false;
209
+ }): Promise<void>;
210
+ /**
211
+ * Revalidate all entries associated with a tag.
212
+ * Supports Next.js 16's cacheLife parameter ('max', 'hours', 'days').
213
+ */
214
+ revalidateTag(tag: string, _cacheLife?: string): Promise<void>;
215
+ /**
216
+ * Reset request-scoped in-memory cache at the beginning/end of each request.
217
+ */
218
+ resetRequestCache(): void;
219
+ }
220
+
221
+ /**
222
+ * Factory helper for creating custom configured Next.js cache handler instances.
223
+ *
224
+ * @example
225
+ * // next.config.mjs
226
+ * export default {
227
+ * cacheHandler: require.resolve('tricache/next'),
228
+ * };
229
+ */
230
+ declare function createNextCacheHandler(options?: NextCacheHandlerOptions): typeof TriCacheHandler;
231
+
232
+ export { type CacheHandlerContext, type CacheHandlerValue, type CacheLifePreset, type CacheLifeProfile, type IncrementalCacheEntry, type IncrementalCacheValue, type NextCacheEntry, type NextCacheHandlerOptions, PRESET_CACHE_LIFE_PROFILES, type StoredNextCacheEntry, TriCacheHandler, TriCacheISRHandler, createNextCacheHandler, TriCacheHandler as default, resolveCacheLife };
@@ -1,5 +1,5 @@
1
- import { C as CacheService } from '../cache-service-CREOp7MM.js';
2
- import { C as CacheOptions, i as ILogger } from '../types-Dyip5wAl.js';
1
+ import { C as CacheService } from '../cache-service-B108FzER.js';
2
+ import { C as CacheOptions, i as ILogger } from '../types-BA4pz1A0.js';
3
3
  import 'crypto';
4
4
 
5
5
  /**
@@ -22,6 +22,19 @@ interface CacheHandlerValue {
22
22
  * Remaining / configured TTL (seconds).
23
23
  */
24
24
  ttl?: number;
25
+ /** Native Next.js CacheEntry timing fields, in seconds. */
26
+ stale?: number;
27
+ revalidate?: number;
28
+ expire?: number;
29
+ }
30
+ /** Complete native Next.js CacheEntry output, structurally checked against Next in tests. */
31
+ interface NextCacheEntry {
32
+ value: ReadableStream<Uint8Array>;
33
+ tags: string[];
34
+ timestamp: number;
35
+ stale: number;
36
+ revalidate: number;
37
+ expire: number;
25
38
  }
26
39
  /**
27
40
  * Stored representation in TriCache for Next.js CacheHandler entries.
@@ -39,6 +52,11 @@ interface StoredNextCacheEntry {
39
52
  ttl: number;
40
53
  /** Captured soft tag versions at write time */
41
54
  softTagVersions?: Record<string, number>;
55
+ generations?: Record<string, number>;
56
+ stale?: number;
57
+ revalidate?: number;
58
+ expire?: number;
59
+ streamEncoding?: 'base64';
42
60
  }
43
61
  type CacheLifePreset = 'default' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'max';
44
62
  interface CacheLifeProfile {
@@ -69,6 +87,8 @@ interface NextCacheHandlerOptions extends CacheOptions {
69
87
  * or `process.env.NEXT_PHASE === 'phase-export'`.
70
88
  */
71
89
  isBuildPhase?: boolean;
90
+ /** Maximum buffered RSC stream size. Default: 16 MiB. */
91
+ maxStreamBytes?: number;
72
92
  }
73
93
  /**
74
94
  * Legacy Next.js IncrementalCache value shape.
@@ -135,34 +155,36 @@ declare function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifePro
135
155
  declare class TriCacheHandler {
136
156
  protected readonly cache: CacheService;
137
157
  protected readonly logger: ILogger;
158
+ private readonly maxStreamBytes;
159
+ private readonly pendingSets;
160
+ private readonly observedTags;
138
161
  constructor(options?: NextCacheHandlerOptions);
139
162
  /**
140
163
  * Get an entry from cache. Checks softTags against generational tag versions
141
164
  * and returns a fresh unlocked ReadableStream if the stored value was a stream.
142
165
  */
166
+ get(cacheKey: string, softTags: string[]): Promise<NextCacheEntry | undefined>;
143
167
  get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | undefined>;
144
168
  /**
145
169
  * Write an entry into cache. Drains incoming ReadableStream into a contiguous buffer
146
170
  * before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
147
171
  */
148
172
  set(cacheKey: string, pendingEntry: Promise<CacheHandlerValue | null>, ctx?: CacheHandlerContext): Promise<void>;
173
+ private observeTag;
149
174
  /**
150
- * Returns the expiration timestamp (ms since epoch) of the most relevant
151
- * cached entry for the given tags, or 0 when nothing is tracked. Next.js
152
- * uses this to decide whether a revalidation is due — a hardcoded 0 means
153
- * "always expired", so this reads the real stored entries instead.
175
+ * Delegate soft-tag checking to get() using Next's Infinity sentinel.
154
176
  */
155
177
  getExpiration(tags: string[]): Promise<number>;
156
178
  /**
157
- * Reconcile local generational tag knowledge against shared state: drops the
158
- * in-memory tag-version cache so every subsequent read re-syncs versions
159
- * from Redis. The previous implementation was an empty try/catch.
179
+ * Force subsequent tag reads to re-sync without forgetting monotonic versions.
160
180
  */
161
181
  refreshTags(): Promise<void>;
162
182
  /**
163
183
  * Update or invalidate tags cluster-wide.
164
184
  */
165
- updateTags(tags: string[]): Promise<void>;
185
+ updateTags(tags: string[], durations?: {
186
+ expire?: number;
187
+ }): Promise<void>;
166
188
  }
167
189
 
168
190
  /**
@@ -207,4 +229,4 @@ declare class TriCacheISRHandler {
207
229
  */
208
230
  declare function createNextCacheHandler(options?: NextCacheHandlerOptions): typeof TriCacheHandler;
209
231
 
210
- export { type CacheHandlerContext, type CacheHandlerValue, type CacheLifePreset, type CacheLifeProfile, type IncrementalCacheEntry, type IncrementalCacheValue, type NextCacheHandlerOptions, PRESET_CACHE_LIFE_PROFILES, type StoredNextCacheEntry, TriCacheHandler, TriCacheISRHandler, createNextCacheHandler, TriCacheHandler as default, resolveCacheLife };
232
+ export { type CacheHandlerContext, type CacheHandlerValue, type CacheLifePreset, type CacheLifeProfile, type IncrementalCacheEntry, type IncrementalCacheValue, type NextCacheEntry, type NextCacheHandlerOptions, PRESET_CACHE_LIFE_PROFILES, type StoredNextCacheEntry, TriCacheHandler, TriCacheISRHandler, createNextCacheHandler, TriCacheHandler as default, resolveCacheLife };
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  CacheService
3
- } from "../chunk-JYQFQJNJ.js";
3
+ } from "../chunk-WYF7NOAT.js";
4
4
  import {
5
5
  consoleLogger
6
6
  } from "../chunk-UBWLPKTI.js";
7
- import "../chunk-2AJKEQMZ.js";
7
+ import "../chunk-H4GFLQ26.js";
8
8
 
9
9
  // src/next/cache-handler.ts
10
10
  var PRESET_CACHE_LIFE_PROFILES = {
@@ -38,18 +38,31 @@ function resolveCacheLife(profileOrName) {
38
38
  }
39
39
  return null;
40
40
  }
41
- async function drainStream(stream) {
41
+ async function drainStream(stream, maxBytes) {
42
42
  const reader = stream.getReader();
43
43
  const chunks = [];
44
- while (true) {
45
- const { done, value } = await reader.read();
46
- if (done) break;
47
- if (value) chunks.push(value);
44
+ let size = 0;
45
+ try {
46
+ while (true) {
47
+ const { done, value } = await reader.read();
48
+ if (done) break;
49
+ if (value) {
50
+ size += value.byteLength;
51
+ if (size > maxBytes) throw new Error("RSC stream exceeds maxStreamBytes");
52
+ chunks.push(Uint8Array.from(value));
53
+ }
54
+ }
55
+ return Buffer.concat(chunks);
56
+ } catch (error) {
57
+ void reader.cancel(error).catch(() => {
58
+ });
59
+ throw error;
60
+ } finally {
61
+ reader.releaseLock();
48
62
  }
49
- return Buffer.concat(chunks);
50
63
  }
51
64
  function createReadableStream(buffer) {
52
- const uint8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
65
+ const uint8 = Uint8Array.from(buffer);
53
66
  return new ReadableStream({
54
67
  start(controller) {
55
68
  controller.enqueue(uint8);
@@ -60,8 +73,14 @@ function createReadableStream(buffer) {
60
73
  var TriCacheHandler = class {
61
74
  cache;
62
75
  logger;
76
+ maxStreamBytes;
77
+ pendingSets = /* @__PURE__ */ new Map();
78
+ observedTags = /* @__PURE__ */ new Map();
63
79
  constructor(options = {}) {
64
80
  this.logger = options.logger ?? consoleLogger;
81
+ this.maxStreamBytes = options.maxStreamBytes ?? 16 * 1024 * 1024;
82
+ if (!Number.isFinite(this.maxStreamBytes) || this.maxStreamBytes <= 0) throw new Error("maxStreamBytes must be finite and positive");
83
+ if (options.tagStrategy && options.tagStrategy !== "generational") throw new Error("Next.js cache handlers require tagStrategy: generational");
65
84
  const isBuildPhase = options.isBuildPhase ?? (typeof process !== "undefined" && (process.env.NEXT_PHASE === "phase-production-build" || process.env.NEXT_PHASE === "phase-export"));
66
85
  this.cache = CacheService.create({
67
86
  ...options,
@@ -71,34 +90,62 @@ var TriCacheHandler = class {
71
90
  disableRedis: isBuildPhase ? true : options.disableRedis
72
91
  });
73
92
  }
74
- /**
75
- * Get an entry from cache. Checks softTags against generational tag versions
76
- * and returns a fresh unlocked ReadableStream if the stored value was a stream.
77
- */
78
- async get(cacheKey, ctx) {
93
+ async get(cacheKey, context) {
94
+ let pending = this.pendingSets.get(cacheKey);
95
+ while (pending) {
96
+ await pending.completion;
97
+ pending = this.pendingSets.get(cacheKey);
98
+ }
99
+ const native = Array.isArray(context);
100
+ const ctx = native ? { softTags: context } : context;
79
101
  const stored = await this.cache.peek(cacheKey);
80
102
  if (!stored || stored.data == null) {
81
103
  return void 0;
82
104
  }
83
- if (ctx?.softTags && ctx.softTags.length > 0) {
84
- const softTags = ctx.softTags;
85
- const currentVers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
86
- for (let i = 0; i < softTags.length; i++) {
87
- const storedSoftVer = stored.softTagVersions?.[softTags[i]] ?? 0;
88
- if (currentVers[i] > storedSoftVer) {
89
- return void 0;
105
+ const expire = stored.expire ?? stored.ttl;
106
+ if (!Number.isFinite(stored.timestamp) || !Number.isFinite(expire) || Date.now() >= stored.timestamp + expire * 1e3) return void 0;
107
+ const tags = [.../* @__PURE__ */ new Set([...stored.tags, ...ctx?.softTags ?? []])];
108
+ const versions = await Promise.all(tags.map((tag) => this.cache.getTagVersion(tag)));
109
+ const states = await this.cache.mget(tags.map((tag) => `_next_tag_state_:${tag}`));
110
+ let revalidate = stored.revalidate ?? stored.ttl;
111
+ for (let index = 0; index < tags.length; index++) {
112
+ const tag = tags[index];
113
+ const state = states[index];
114
+ const snapshot = stored.generations?.[tag] ?? stored.softTagVersions?.[tag];
115
+ if (state && (state.revalidatedAt > stored.timestamp || state.revalidatedAt === stored.timestamp && snapshot !== versions[index])) {
116
+ if (state.expiredAt !== void 0 && state.expiredAt <= Date.now()) return void 0;
117
+ revalidate = -1;
118
+ } else if (!state && versions[index] > 0) {
119
+ if (snapshot !== void 0 && versions[index] > snapshot) return void 0;
120
+ if (snapshot === void 0) {
121
+ const observed = this.observeTag(tag, versions[index]);
122
+ if (stored.timestamp <= observed) return void 0;
90
123
  }
91
124
  }
92
125
  }
93
126
  let val = stored.data;
94
- if (stored.isStream && (Buffer.isBuffer(val) || val instanceof Uint8Array)) {
95
- val = createReadableStream(val);
127
+ if (stored.isStream) {
128
+ let bytes;
129
+ if (stored.streamEncoding === "base64" && typeof val === "string") {
130
+ if (val.length > Math.ceil(this.maxStreamBytes / 3) * 4) return void 0;
131
+ bytes = Buffer.from(val, "base64");
132
+ } else if (Buffer.isBuffer(val) || val instanceof Uint8Array) bytes = val;
133
+ else if (val && typeof val === "object" && val.type === "Buffer" && Array.isArray(val.data)) {
134
+ bytes = Buffer.from(val.data);
135
+ } else return void 0;
136
+ if (bytes.length > this.maxStreamBytes) return void 0;
137
+ val = createReadableStream(bytes);
138
+ } else if (native) {
139
+ return void 0;
96
140
  }
97
141
  return {
98
142
  value: val,
99
143
  tags: stored.tags,
100
144
  timestamp: stored.timestamp,
101
- ttl: stored.ttl
145
+ ttl: stored.ttl,
146
+ stale: stored.stale ?? 300,
147
+ revalidate,
148
+ expire
102
149
  };
103
150
  }
104
151
  /**
@@ -106,92 +153,111 @@ var TriCacheHandler = class {
106
153
  * before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
107
154
  */
108
155
  async set(cacheKey, pendingEntry, ctx) {
109
- const entry = await pendingEntry;
110
- if (!entry || entry.value == null) return;
111
- let dataToStore = entry.value;
112
- const isStream = Boolean(
113
- dataToStore && typeof dataToStore.getReader === "function"
114
- );
115
- if (isStream) {
116
- try {
117
- dataToStore = await drainStream(dataToStore);
118
- } catch (streamErr) {
119
- this.logger.debug("Next.js cacheHandler: stream drain failed mid-flight, skipping cache", {
120
- cacheKey,
121
- error: streamErr.message
122
- });
123
- return;
156
+ const token = Symbol(cacheKey);
157
+ let finish;
158
+ const completion = new Promise((resolve) => {
159
+ finish = resolve;
160
+ });
161
+ this.pendingSets.set(cacheKey, { token, completion });
162
+ try {
163
+ const canCommit = this.cache.captureMutationFence(cacheKey);
164
+ const entry = await pendingEntry;
165
+ if (!entry || entry.value == null) return;
166
+ const tags = Array.from(/* @__PURE__ */ new Set([...entry.tags ?? [], ...ctx?.tags ?? []]));
167
+ const allTags = [.../* @__PURE__ */ new Set([...tags, ...ctx?.softTags ?? []])];
168
+ const initialVersions = Object.fromEntries(await Promise.all(allTags.map(async (tag) => [tag, await this.cache.getTagVersion(tag)])));
169
+ let dataToStore = entry.value;
170
+ const isStream = Boolean(
171
+ dataToStore && typeof dataToStore.getReader === "function"
172
+ );
173
+ if (isStream) {
174
+ try {
175
+ dataToStore = (await drainStream(dataToStore, this.maxStreamBytes)).toString("base64");
176
+ } catch (streamErr) {
177
+ this.logger.debug("Next.js cacheHandler: stream drain failed mid-flight, skipping cache", {
178
+ cacheKey,
179
+ error: streamErr.message
180
+ });
181
+ return;
182
+ }
124
183
  }
125
- }
126
- let ttl;
127
- const resolvedLife = resolveCacheLife(ctx?.cacheLife);
128
- if (resolvedLife) {
129
- ttl = resolvedLife.ttl;
130
- } else if (typeof entry.ttl === "number") {
131
- ttl = entry.ttl;
132
- } else if (typeof ctx?.revalidate === "number") {
133
- if (ctx.revalidate <= 0) return;
134
- ttl = ctx.revalidate;
135
- } else if (ctx?.revalidate === false) {
136
- ttl = 31536e3;
137
- } else {
138
- ttl = 300;
139
- }
140
- const tags = Array.from(/* @__PURE__ */ new Set([...entry.tags ?? [], ...ctx?.tags ?? []]));
141
- let softTagVersions;
142
- if (ctx?.softTags && ctx.softTags.length > 0) {
143
- const softTags = ctx.softTags;
144
- const vers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
145
- softTagVersions = {};
146
- for (let i = 0; i < softTags.length; i++) {
147
- softTagVersions[softTags[i]] = vers[i];
184
+ let ttl;
185
+ const resolvedLife = resolveCacheLife(ctx?.cacheLife);
186
+ if (resolvedLife) {
187
+ ttl = resolvedLife.ttl;
188
+ } else if (typeof entry.revalidate === "number") {
189
+ ttl = entry.revalidate;
190
+ } else if (typeof entry.ttl === "number") {
191
+ ttl = entry.ttl;
192
+ } else if (typeof ctx?.revalidate === "number") {
193
+ if (ctx.revalidate <= 0) return;
194
+ ttl = ctx.revalidate;
195
+ } else if (ctx?.revalidate === false) {
196
+ ttl = 31536e3;
197
+ } else {
198
+ ttl = 300;
148
199
  }
200
+ const expire = entry.expire ?? (resolvedLife ? resolvedLife.ttl + resolvedLife.swr : ttl);
201
+ const timestamp = entry.timestamp ?? Date.now();
202
+ if (!Number.isFinite(expire) || expire <= 0 || !Number.isFinite(timestamp) || timestamp > Date.now() + (this.cache.options.clockSkewToleranceMs ?? 250)) return;
203
+ const remaining = timestamp + expire * 1e3 - Date.now();
204
+ if (remaining <= 0 || !canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
205
+ const finalVersions = await Promise.all(allTags.map((tag) => this.cache.getTagVersion(tag)));
206
+ if (allTags.some((tag, index) => finalVersions[index] !== initialVersions[tag])) return;
207
+ const tagStates = await this.cache.mget(allTags.map((tag) => `_next_tag_state_:${tag}`));
208
+ if (tagStates.some((state) => state && state.revalidatedAt > timestamp)) return;
209
+ let softTagVersions;
210
+ if (ctx?.softTags && ctx.softTags.length > 0) {
211
+ const softTags = ctx.softTags;
212
+ const vers = await Promise.all(softTags.map((st) => this.cache.getTagVersion(st)));
213
+ softTagVersions = {};
214
+ for (let i = 0; i < softTags.length; i++) {
215
+ softTagVersions[softTags[i]] = vers[i];
216
+ }
217
+ }
218
+ const stored = {
219
+ data: dataToStore,
220
+ isStream,
221
+ tags,
222
+ timestamp,
223
+ ttl,
224
+ softTagVersions,
225
+ generations: initialVersions,
226
+ stale: entry.stale ?? (typeof ctx?.cacheLife === "string" ? PRESET_CACHE_LIFE_PROFILES[ctx.cacheLife]?.stale : typeof ctx?.cacheLife === "object" ? ctx.cacheLife.stale : void 0) ?? 300,
227
+ revalidate: ttl,
228
+ expire,
229
+ streamEncoding: isStream ? "base64" : void 0
230
+ };
231
+ if (!canCommit() || this.pendingSets.get(cacheKey)?.token !== token) return;
232
+ await this.cache.set(cacheKey, stored, remaining / 1e3, void 0, { tags: [] });
233
+ } finally {
234
+ finish();
235
+ if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
149
236
  }
150
- const stored = {
151
- data: dataToStore,
152
- isStream,
153
- tags,
154
- timestamp: entry.timestamp ?? Date.now(),
155
- ttl,
156
- softTagVersions
157
- };
158
- await this.cache.set(cacheKey, stored, ttl, void 0, tags.length > 0 ? { tags } : void 0);
237
+ }
238
+ observeTag(tag, version) {
239
+ const known = this.observedTags.get(tag);
240
+ if (known?.version === version) return known.observedAt;
241
+ if (this.observedTags.size >= 1e4) {
242
+ const oldest = this.observedTags.keys().next().value;
243
+ if (oldest !== void 0) this.observedTags.delete(oldest);
244
+ }
245
+ const observedAt = Date.now();
246
+ this.observedTags.set(tag, { version, observedAt });
247
+ return observedAt;
159
248
  }
160
249
  /**
161
- * Returns the expiration timestamp (ms since epoch) of the most relevant
162
- * cached entry for the given tags, or 0 when nothing is tracked. Next.js
163
- * uses this to decide whether a revalidation is due — a hardcoded 0 means
164
- * "always expired", so this reads the real stored entries instead.
250
+ * Delegate soft-tag checking to get() using Next's Infinity sentinel.
165
251
  */
166
252
  async getExpiration(tags) {
167
- try {
168
- let maxExpiration = 0;
169
- const tagSet = new Set(tags);
170
- const l1 = this.cache.l1;
171
- l1.scan((key, entry) => {
172
- if (!entry.tagVersions) return;
173
- for (const tag of Object.keys(entry.tagVersions)) {
174
- if (!tagSet.has(tag)) continue;
175
- const exp = entry.expiresAt ?? 0;
176
- if (exp > maxExpiration) maxExpiration = exp;
177
- return;
178
- }
179
- }, 0);
180
- return maxExpiration;
181
- } catch (err) {
182
- this.logger.debug("Next.js cacheHandler getExpiration fail-soft", { error: err.message });
183
- return 0;
184
- }
253
+ return tags.length ? Infinity : 0;
185
254
  }
186
255
  /**
187
- * Reconcile local generational tag knowledge against shared state: drops the
188
- * in-memory tag-version cache so every subsequent read re-syncs versions
189
- * from Redis. The previous implementation was an empty try/catch.
256
+ * Force subsequent tag reads to re-sync without forgetting monotonic versions.
190
257
  */
191
258
  async refreshTags() {
192
259
  try {
193
- const cache = this.cache;
194
- cache.tagVersions?.clear();
260
+ this.cache.refreshTagVersions();
195
261
  } catch (err) {
196
262
  this.logger.debug("Next.js cacheHandler refreshTags fail-soft catch", {
197
263
  error: err.message
@@ -201,8 +267,15 @@ var TriCacheHandler = class {
201
267
  /**
202
268
  * Update or invalidate tags cluster-wide.
203
269
  */
204
- async updateTags(tags) {
270
+ async updateTags(tags, durations) {
205
271
  if (!tags || tags.length === 0) return;
272
+ const now = Date.now();
273
+ const delay = durations && durations.expire === void 0 ? void 0 : Math.max(0, durations?.expire ?? 0) * 1e3;
274
+ if (delay !== void 0 && !Number.isFinite(delay)) throw new Error("Tag expiry duration must be finite");
275
+ await Promise.all(tags.map((tag) => this.cache.set(`_next_tag_state_:${tag}`, {
276
+ revalidatedAt: now,
277
+ expiredAt: delay === void 0 ? void 0 : now + delay
278
+ }, 0, 3 /* HIGH */)));
206
279
  await this.cache.invalidateTags(tags);
207
280
  }
208
281
  };