tricache 0.7.0 → 0.7.1

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 (40) hide show
  1. package/README.md +1428 -1428
  2. package/bin/tricache.js +8 -8
  3. package/dist/cache-service-5GATUYAK.js +7 -0
  4. package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
  5. package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
  6. package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
  7. package/dist/cli.cjs +113 -56
  8. package/dist/cli.js +3 -3
  9. package/dist/drizzle/index.cjs +114 -57
  10. package/dist/drizzle/index.d.ts +1 -1
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/http/index.cjs +149 -64
  13. package/dist/http/index.d.ts +1 -1
  14. package/dist/http/index.js +38 -10
  15. package/dist/index.cjs +112 -55
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/nestjs/index.cjs +112 -55
  19. package/dist/nestjs/index.d.ts +1 -1
  20. package/dist/nestjs/index.js +2 -2
  21. package/dist/next/index.cjs +143 -63
  22. package/dist/next/index.d.ts +10 -6
  23. package/dist/next/index.js +33 -10
  24. package/dist/prisma/index.cjs +2 -1
  25. package/dist/prisma/index.d.ts +1 -1
  26. package/dist/prisma/index.js +2 -1
  27. package/dist/serialize-worker.cjs +26 -15
  28. package/dist/serialize-worker.js +1 -1
  29. package/package.json +4 -2
  30. package/src/cache-service.ts +3294 -3226
  31. package/src/cli.ts +143 -143
  32. package/src/compression.ts +56 -63
  33. package/src/disk-tier.ts +821 -821
  34. package/src/encryption.ts +513 -493
  35. package/src/http/index.ts +265 -223
  36. package/src/next/cache-handler.ts +268 -244
  37. package/src/prisma/index.ts +154 -151
  38. package/src/smart-memory-cache.ts +1026 -1024
  39. package/src/types.ts +911 -902
  40. package/dist/cache-service-AJASH5FX.js +0 -7
@@ -1,244 +1,268 @@
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 | 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
+ * Returns the expiration timestamp (ms since epoch) of the most relevant
216
+ * cached entry for the given tags, or 0 when nothing is tracked. Next.js
217
+ * uses this to decide whether a revalidation is due — a hardcoded 0 means
218
+ * "always expired", so this reads the real stored entries instead.
219
+ */
220
+ async getExpiration(tags: string[]): Promise<number> {
221
+ try {
222
+ let maxExpiration = 0;
223
+ const tagSet = new Set(tags);
224
+ const l1 = (this.cache as unknown as { l1: { scan(fn: (key: string, entry: { expiresAt?: number; tagVersions?: Record<string, number> }) => void, prefixLen: number): void } }).l1;
225
+ l1.scan((key, entry) => {
226
+ if (!entry.tagVersions) return;
227
+ for (const tag of Object.keys(entry.tagVersions)) {
228
+ if (!tagSet.has(tag)) continue;
229
+ const exp = entry.expiresAt ?? 0;
230
+ if (exp > maxExpiration) maxExpiration = exp;
231
+ return;
232
+ }
233
+ }, 0);
234
+ return maxExpiration;
235
+ } catch (err) {
236
+ this.logger.debug('Next.js cacheHandler getExpiration fail-soft', { error: (err as Error).message });
237
+ return 0;
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Reconcile local generational tag knowledge against shared state: drops the
243
+ * in-memory tag-version cache so every subsequent read re-syncs versions
244
+ * from Redis. The previous implementation was an empty try/catch.
245
+ */
246
+ async refreshTags(): Promise<void> {
247
+ try {
248
+ const cache = this.cache as unknown as {
249
+ tagVersions?: Map<string, unknown>;
250
+ };
251
+ cache.tagVersions?.clear();
252
+ } catch (err) {
253
+ this.logger.debug('Next.js cacheHandler refreshTags fail-soft catch', {
254
+ error: (err as Error).message,
255
+ });
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Update or invalidate tags cluster-wide.
261
+ */
262
+ async updateTags(tags: string[]): Promise<void> {
263
+ if (!tags || tags.length === 0) return;
264
+ await this.cache.invalidateTags(tags);
265
+ }
266
+ }
267
+
268
+ export default TriCacheHandler;