tricache 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -1,244 +1,271 @@
1
- import { CacheService } from '../cache-service';
2
- import { consoleLogger } from '../types';
3
- import type { ILogger } from '../types';
4
- import type {
5
- CacheHandlerValue,
6
- StoredNextCacheEntry,
7
- CacheHandlerContext,
8
- NextCacheHandlerOptions,
9
- CacheLifePreset,
10
- CacheLifeProfile,
11
- } from './types';
12
-
13
- /**
14
- * Built-in Next.js 16 cacheLife preset profile timings (in seconds).
15
- */
16
- export const PRESET_CACHE_LIFE_PROFILES: Record<CacheLifePreset, { stale: number; revalidate: number; expire: number }> = {
17
- default: { stale: 300, revalidate: 900, expire: 2_592_000 },
18
- seconds: { stale: 0, revalidate: 1, expire: 60 },
19
- minutes: { stale: 300, revalidate: 60, expire: 3600 },
20
- hours: { stale: 300, revalidate: 3600, expire: 86400 },
21
- days: { stale: 300, revalidate: 86400, expire: 604800 },
22
- weeks: { stale: 300, revalidate: 604800, expire: 2_592_000 },
23
- max: { stale: 300, revalidate: 2_592_000, expire: 31_536_000 },
24
- };
25
-
26
- /**
27
- * Resolve a Next.js 16 cacheLife preset name or custom profile object into TriCache TTL and SWR seconds.
28
- */
29
- export function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifeProfile | string): { ttl: number; swr: number } | null {
30
- if (!profileOrName) return null;
31
-
32
- if (typeof profileOrName === 'string') {
33
- const preset = PRESET_CACHE_LIFE_PROFILES[profileOrName as CacheLifePreset];
34
- if (preset) {
35
- return {
36
- ttl: preset.revalidate,
37
- swr: Math.max(0, preset.expire - preset.revalidate),
38
- };
39
- }
40
- return null;
41
- }
42
-
43
- if (typeof profileOrName === 'object') {
44
- const revalidate = typeof profileOrName.revalidate === 'number' ? profileOrName.revalidate : 900;
45
- const expire = typeof profileOrName.expire === 'number' ? profileOrName.expire : 2_592_000;
46
- return {
47
- ttl: revalidate,
48
- swr: Math.max(0, expire - revalidate),
49
- };
50
- }
51
-
52
- return null;
53
- }
54
-
55
- /**
56
- * Drain incoming web ReadableStream into a contiguous Node Buffer.
57
- */
58
- async function drainStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {
59
- const reader = stream.getReader();
60
- const chunks: Uint8Array[] = [];
61
- while (true) {
62
- const { done, value } = await reader.read();
63
- if (done) break;
64
- if (value) chunks.push(value);
65
- }
66
- return Buffer.concat(chunks);
67
- }
68
-
69
- /**
70
- * Construct a fresh, unlocked ReadableStream from a buffer.
71
- */
72
- function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8Array> {
73
- const uint8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
74
- return new ReadableStream<Uint8Array>({
75
- start(controller) {
76
- controller.enqueue(uint8);
77
- controller.close();
78
- },
79
- });
80
- }
81
-
82
- /**
83
- * Modern Next.js 16 App Router `CacheHandler` implementation for `"use cache"` components.
84
- *
85
- * Implements the 5-method contract: `get`, `set`, `refreshTags`, `getExpiration`, `updateTags`.
86
- */
87
- export class TriCacheHandler {
88
- protected readonly cache: CacheService;
89
- protected readonly logger: ILogger;
90
-
91
- constructor(options: NextCacheHandlerOptions = {}) {
92
- this.logger = options.logger ?? consoleLogger;
93
-
94
- const isBuildPhase =
95
- options.isBuildPhase ??
96
- (typeof process !== 'undefined' &&
97
- (process.env.NEXT_PHASE === 'phase-production-build' ||
98
- process.env.NEXT_PHASE === 'phase-export'));
99
-
100
- this.cache = CacheService.create({
101
- ...options,
102
- namespace: options.namespace ?? 'next',
103
- tagStrategy: options.tagStrategy ?? 'generational',
104
- cloneStrategy: options.cloneStrategy ?? 'none',
105
- disableRedis: isBuildPhase ? true : options.disableRedis,
106
- });
107
- }
108
-
109
- /**
110
- * Get an entry from cache. Checks softTags against generational tag versions
111
- * and returns a fresh unlocked ReadableStream if the stored value was a stream.
112
- */
113
- async get(cacheKey: string, ctx?: CacheHandlerContext): Promise<CacheHandlerValue | null> {
114
- const stored = await this.cache.get<StoredNextCacheEntry | null>(
115
- cacheKey,
116
- async () => null,
117
- );
118
-
119
- if (!stored || stored.data == null) {
120
- return null;
121
- }
122
-
123
- // Check softTags at read time (e.g. Next.js 16 layout / page boundaries)
124
- if (ctx?.softTags && ctx.softTags.length > 0) {
125
- for (const softTag of ctx.softTags) {
126
- const currentVer = await this.cache.getTagVersion(softTag);
127
- const storedSoftVer = stored.softTagVersions?.[softTag] ?? 0;
128
- if (currentVer > storedSoftVer) {
129
- return null;
130
- }
131
- }
132
- }
133
-
134
- let val = stored.data;
135
- if (stored.isStream && (Buffer.isBuffer(val) || val instanceof Uint8Array)) {
136
- val = createReadableStream(val);
137
- }
138
-
139
- return {
140
- value: val,
141
- tags: stored.tags,
142
- timestamp: stored.timestamp,
143
- ttl: stored.ttl,
144
- };
145
- }
146
-
147
- /**
148
- * Write an entry into cache. Drains incoming ReadableStream into a contiguous buffer
149
- * before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
150
- */
151
- async set(
152
- cacheKey: string,
153
- pendingEntry: Promise<CacheHandlerValue | null>,
154
- ctx?: CacheHandlerContext,
155
- ): Promise<void> {
156
- const entry = await pendingEntry;
157
- if (!entry || entry.value == null) return;
158
-
159
- let dataToStore = entry.value;
160
- const isStream = Boolean(
161
- dataToStore &&
162
- typeof (dataToStore as { getReader?: unknown }).getReader === 'function',
163
- );
164
-
165
- if (isStream) {
166
- try {
167
- dataToStore = await drainStream(dataToStore as ReadableStream<Uint8Array>);
168
- } catch (streamErr) {
169
- this.logger.debug('Next.js cacheHandler: stream drain failed mid-flight, skipping cache', {
170
- cacheKey,
171
- error: (streamErr as Error).message,
172
- });
173
- return;
174
- }
175
- }
176
-
177
- let ttl: number;
178
- const resolvedLife = resolveCacheLife(ctx?.cacheLife);
179
- if (resolvedLife) {
180
- ttl = resolvedLife.ttl;
181
- } else if (typeof entry.ttl === 'number') {
182
- ttl = entry.ttl;
183
- } else if (typeof ctx?.revalidate === 'number') {
184
- if (ctx.revalidate <= 0) return; // Do not cache dynamic 0s responses
185
- ttl = ctx.revalidate;
186
- } else if (ctx?.revalidate === false) {
187
- ttl = 31_536_000; // 1 year for static indefinite assets
188
- } else {
189
- ttl = 300; // fallback default
190
- }
191
-
192
- const tags = Array.from(new Set([...(entry.tags ?? []), ...(ctx?.tags ?? [])]));
193
-
194
- let softTagVersions: Record<string, number> | undefined;
195
- if (ctx?.softTags && ctx.softTags.length > 0) {
196
- softTagVersions = {};
197
- for (const st of ctx.softTags) {
198
- softTagVersions[st] = await this.cache.getTagVersion(st);
199
- }
200
- }
201
-
202
- const stored: StoredNextCacheEntry = {
203
- data: dataToStore,
204
- isStream,
205
- tags,
206
- timestamp: entry.timestamp ?? Date.now(),
207
- ttl,
208
- softTagVersions,
209
- };
210
-
211
- await this.cache.set(cacheKey, stored, ttl, undefined, tags.length > 0 ? { tags } : undefined);
212
- }
213
-
214
- /**
215
- * Refreshes tag timestamps from shared cache. Fail-soft error boundary ensures
216
- * network errors never crash incoming HTTP requests.
217
- */
218
- async refreshTags(): Promise<void> {
219
- try {
220
- // Re-sync local tag state when invoked by Next.js revalidation worker
221
- } catch (err) {
222
- this.logger.debug('Next.js cacheHandler refreshTags fail-soft catch', {
223
- error: (err as Error).message,
224
- });
225
- }
226
- }
227
-
228
- /**
229
- * Returns the maximum expiration timestamp across the given tags (or 0 if not tracking).
230
- */
231
- async getExpiration(_tags: string[]): Promise<number> {
232
- return 0;
233
- }
234
-
235
- /**
236
- * Update or invalidate tags cluster-wide.
237
- */
238
- async updateTags(tags: string[]): Promise<void> {
239
- if (!tags || tags.length === 0) return;
240
- await this.cache.invalidateTags(tags);
241
- }
242
- }
243
-
244
- export default TriCacheHandler;
1
+ import { CacheService } from '../cache-service';
2
+ import { consoleLogger } from '../types';
3
+ import type { ILogger } from '../types';
4
+ import type {
5
+ CacheHandlerValue,
6
+ StoredNextCacheEntry,
7
+ CacheHandlerContext,
8
+ NextCacheHandlerOptions,
9
+ CacheLifePreset,
10
+ CacheLifeProfile,
11
+ } from './types';
12
+
13
+ /**
14
+ * Built-in Next.js 16 cacheLife preset profile timings (in seconds).
15
+ */
16
+ export const PRESET_CACHE_LIFE_PROFILES: Record<CacheLifePreset, { stale: number; revalidate: number; expire: number }> = {
17
+ default: { stale: 300, revalidate: 900, expire: 2_592_000 },
18
+ seconds: { stale: 0, revalidate: 1, expire: 60 },
19
+ minutes: { stale: 300, revalidate: 60, expire: 3600 },
20
+ hours: { stale: 300, revalidate: 3600, expire: 86400 },
21
+ days: { stale: 300, revalidate: 86400, expire: 604800 },
22
+ weeks: { stale: 300, revalidate: 604800, expire: 2_592_000 },
23
+ max: { stale: 300, revalidate: 2_592_000, expire: 31_536_000 },
24
+ };
25
+
26
+ /**
27
+ * Resolve a Next.js 16 cacheLife preset name or custom profile object into TriCache TTL and SWR seconds.
28
+ */
29
+ export function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifeProfile | string): { ttl: number; swr: number } | null {
30
+ if (!profileOrName) return null;
31
+
32
+ if (typeof profileOrName === 'string') {
33
+ const preset = PRESET_CACHE_LIFE_PROFILES[profileOrName as CacheLifePreset];
34
+ if (preset) {
35
+ return {
36
+ ttl: preset.revalidate,
37
+ swr: Math.max(0, preset.expire - preset.revalidate),
38
+ };
39
+ }
40
+ return null;
41
+ }
42
+
43
+ if (typeof profileOrName === 'object') {
44
+ const revalidate = typeof profileOrName.revalidate === 'number' ? profileOrName.revalidate : 900;
45
+ const expire = typeof profileOrName.expire === 'number' ? profileOrName.expire : 2_592_000;
46
+ return {
47
+ ttl: revalidate,
48
+ swr: Math.max(0, expire - revalidate),
49
+ };
50
+ }
51
+
52
+ return null;
53
+ }
54
+
55
+ /**
56
+ * Drain incoming web ReadableStream into a contiguous Node Buffer.
57
+ */
58
+ async function drainStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {
59
+ const reader = stream.getReader();
60
+ const chunks: Uint8Array[] = [];
61
+ while (true) {
62
+ const { done, value } = await reader.read();
63
+ if (done) break;
64
+ if (value) chunks.push(value);
65
+ }
66
+ return Buffer.concat(chunks);
67
+ }
68
+
69
+ /**
70
+ * Construct a fresh, unlocked ReadableStream from a buffer.
71
+ */
72
+ function createReadableStream(buffer: Buffer | Uint8Array): ReadableStream<Uint8Array> {
73
+ const uint8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
74
+ return new ReadableStream<Uint8Array>({
75
+ start(controller) {
76
+ controller.enqueue(uint8);
77
+ controller.close();
78
+ },
79
+ });
80
+ }
81
+
82
+ /**
83
+ * Modern Next.js 16 App Router `CacheHandler` implementation for `"use cache"` components.
84
+ *
85
+ * Implements the 5-method contract: `get`, `set`, `refreshTags`, `getExpiration`, `updateTags`.
86
+ */
87
+ export class TriCacheHandler {
88
+ protected readonly cache: CacheService;
89
+ protected readonly logger: ILogger;
90
+
91
+ constructor(options: NextCacheHandlerOptions = {}) {
92
+ this.logger = options.logger ?? consoleLogger;
93
+
94
+ const isBuildPhase =
95
+ options.isBuildPhase ??
96
+ (typeof process !== 'undefined' &&
97
+ (process.env.NEXT_PHASE === 'phase-production-build' ||
98
+ process.env.NEXT_PHASE === 'phase-export'));
99
+
100
+ this.cache = CacheService.create({
101
+ ...options,
102
+ namespace: options.namespace ?? 'next',
103
+ tagStrategy: options.tagStrategy ?? 'generational',
104
+ cloneStrategy: options.cloneStrategy ?? 'none',
105
+ disableRedis: isBuildPhase ? true : options.disableRedis,
106
+ });
107
+ }
108
+
109
+ /**
110
+ * Get an entry from cache. Checks softTags against generational tag versions
111
+ * and returns a fresh unlocked ReadableStream if the stored value was a stream.
112
+ */
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
+ );
118
+
119
+ if (!stored || stored.data == null) {
120
+ return undefined;
121
+ }
122
+
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;
131
+ }
132
+ }
133
+ }
134
+
135
+ let val = stored.data;
136
+ if (stored.isStream && (Buffer.isBuffer(val) || val instanceof Uint8Array)) {
137
+ val = createReadableStream(val);
138
+ }
139
+
140
+ return {
141
+ value: val,
142
+ tags: stored.tags,
143
+ timestamp: stored.timestamp,
144
+ ttl: stored.ttl,
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Write an entry into cache. Drains incoming ReadableStream into a contiguous buffer
150
+ * before storing. Catches mid-flight stream aborts to avoid crashing Next.js.
151
+ */
152
+ async set(
153
+ cacheKey: string,
154
+ pendingEntry: Promise<CacheHandlerValue | null>,
155
+ ctx?: CacheHandlerContext,
156
+ ): Promise<void> {
157
+ const entry = await pendingEntry;
158
+ if (!entry || entry.value == null) return;
159
+
160
+ let dataToStore = entry.value;
161
+ const isStream = Boolean(
162
+ dataToStore &&
163
+ typeof (dataToStore as { getReader?: unknown }).getReader === 'function',
164
+ );
165
+
166
+ if (isStream) {
167
+ try {
168
+ dataToStore = await drainStream(dataToStore as ReadableStream<Uint8Array>);
169
+ } catch (streamErr) {
170
+ this.logger.debug('Next.js cacheHandler: stream drain failed mid-flight, skipping cache', {
171
+ cacheKey,
172
+ error: (streamErr as Error).message,
173
+ });
174
+ return;
175
+ }
176
+ }
177
+
178
+ let ttl: number;
179
+ const resolvedLife = resolveCacheLife(ctx?.cacheLife);
180
+ if (resolvedLife) {
181
+ ttl = resolvedLife.ttl;
182
+ } else if (typeof entry.ttl === 'number') {
183
+ ttl = entry.ttl;
184
+ } else if (typeof ctx?.revalidate === 'number') {
185
+ if (ctx.revalidate <= 0) return; // Do not cache dynamic 0s responses
186
+ ttl = ctx.revalidate;
187
+ } else if (ctx?.revalidate === false) {
188
+ ttl = 31_536_000; // 1 year for static indefinite assets
189
+ } else {
190
+ ttl = 300; // fallback default
191
+ }
192
+
193
+ const tags = Array.from(new Set([...(entry.tags ?? []), ...(ctx?.tags ?? [])]));
194
+
195
+ let softTagVersions: Record<string, number> | undefined;
196
+ if (ctx?.softTags && ctx.softTags.length > 0) {
197
+ const softTags = ctx.softTags;
198
+ const vers = await Promise.all(softTags.map(st => this.cache.getTagVersion(st)));
199
+ softTagVersions = {};
200
+ for (let i = 0; i < softTags.length; i++) {
201
+ softTagVersions[softTags[i]] = vers[i];
202
+ }
203
+ }
204
+
205
+ const stored: StoredNextCacheEntry = {
206
+ data: dataToStore,
207
+ isStream,
208
+ tags,
209
+ timestamp: entry.timestamp ?? Date.now(),
210
+ ttl,
211
+ softTagVersions,
212
+ };
213
+
214
+ await this.cache.set(cacheKey, stored, ttl, undefined, tags.length > 0 ? { tags } : undefined);
215
+ }
216
+
217
+ /**
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.
222
+ */
223
+ 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
+ }
242
+ }
243
+
244
+ /**
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.
248
+ */
249
+ async refreshTags(): Promise<void> {
250
+ try {
251
+ const cache = this.cache as unknown as {
252
+ tagVersions?: Map<string, unknown>;
253
+ };
254
+ cache.tagVersions?.clear();
255
+ } catch (err) {
256
+ this.logger.debug('Next.js cacheHandler refreshTags fail-soft catch', {
257
+ error: (err as Error).message,
258
+ });
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Update or invalidate tags cluster-wide.
264
+ */
265
+ async updateTags(tags: string[]): Promise<void> {
266
+ if (!tags || tags.length === 0) return;
267
+ await this.cache.invalidateTags(tags);
268
+ }
269
+ }
270
+
271
+ export default TriCacheHandler;
package/src/next/index.ts CHANGED
@@ -1,37 +1,37 @@
1
- export {
2
- TriCacheHandler,
3
- PRESET_CACHE_LIFE_PROFILES,
4
- resolveCacheLife,
5
- default,
6
- } from './cache-handler';
7
- export { TriCacheISRHandler } from './isr-handler';
8
- export type {
9
- CacheHandlerValue,
10
- StoredNextCacheEntry,
11
- CacheHandlerContext,
12
- NextCacheHandlerOptions,
13
- IncrementalCacheValue,
14
- IncrementalCacheEntry,
15
- CacheLifePreset,
16
- CacheLifeProfile,
17
- } from './types';
18
-
19
- import { TriCacheHandler } from './cache-handler';
20
- import type { NextCacheHandlerOptions } from './types';
21
-
22
- /**
23
- * Factory helper for creating custom configured Next.js cache handler instances.
24
- *
25
- * @example
26
- * // next.config.mjs
27
- * export default {
28
- * cacheHandler: require.resolve('tricache/next'),
29
- * };
30
- */
31
- export function createNextCacheHandler(options: NextCacheHandlerOptions = {}): typeof TriCacheHandler {
32
- return class ConfiguredTriCacheHandler extends TriCacheHandler {
33
- constructor() {
34
- super(options);
35
- }
36
- };
37
- }
1
+ export {
2
+ TriCacheHandler,
3
+ PRESET_CACHE_LIFE_PROFILES,
4
+ resolveCacheLife,
5
+ default,
6
+ } from './cache-handler';
7
+ export { TriCacheISRHandler } from './isr-handler';
8
+ export type {
9
+ CacheHandlerValue,
10
+ StoredNextCacheEntry,
11
+ CacheHandlerContext,
12
+ NextCacheHandlerOptions,
13
+ IncrementalCacheValue,
14
+ IncrementalCacheEntry,
15
+ CacheLifePreset,
16
+ CacheLifeProfile,
17
+ } from './types';
18
+
19
+ import { TriCacheHandler } from './cache-handler';
20
+ import type { NextCacheHandlerOptions } from './types';
21
+
22
+ /**
23
+ * Factory helper for creating custom configured Next.js cache handler instances.
24
+ *
25
+ * @example
26
+ * // next.config.mjs
27
+ * export default {
28
+ * cacheHandler: require.resolve('tricache/next'),
29
+ * };
30
+ */
31
+ export function createNextCacheHandler(options: NextCacheHandlerOptions = {}): typeof TriCacheHandler {
32
+ return class ConfiguredTriCacheHandler extends TriCacheHandler {
33
+ constructor() {
34
+ super(options);
35
+ }
36
+ };
37
+ }