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
package/src/hono/index.ts CHANGED
@@ -20,6 +20,8 @@ import {
20
20
  buildDeterministicKey,
21
21
  generateETag,
22
22
  shouldSkipCache,
23
+ isShareableHttpResponse,
24
+ matchesETag,
23
25
  type KeyDerivationOptions,
24
26
  } from '../http/utils.js';
25
27
 
@@ -40,12 +42,12 @@ export interface HonoCacheContext {
40
42
  clone?: () => { text: () => Promise<string> };
41
43
  body?: unknown;
42
44
  };
43
- body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
45
+ body: (...args: any[]) => any;
44
46
  executionCtx?: unknown;
45
47
  }
46
48
 
47
49
  export type HonoNext = () => Promise<void>;
48
- export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
50
+ export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<Response | void>;
49
51
 
50
52
  export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
51
53
  /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
@@ -58,6 +60,8 @@ export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDer
58
60
  skipCache?: (c: HonoCacheContext) => boolean;
59
61
  /** Dynamic tags derivation from the Hono context. */
60
62
  tags?: string[] | ((c: HonoCacheContext) => string[]);
63
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
64
+ swr?: number;
61
65
  }
62
66
 
63
67
  export interface CachedHonoResponse {
@@ -71,7 +75,7 @@ export interface CachedHonoResponse {
71
75
  function readRequestHeader(c: HonoCacheContext, name: string): string | undefined {
72
76
  const headerFn = c.req.header;
73
77
  if (typeof headerFn === 'function') {
74
- const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
78
+ const viaFn = headerFn.call(c.req, name) ?? headerFn.call(c.req, name.toLowerCase());
75
79
  if (viaFn !== undefined && viaFn !== null && viaFn !== '') {
76
80
  return viaFn;
77
81
  }
@@ -95,6 +99,10 @@ function toRequestLike(c: HonoCacheContext, headerWhitelist?: string[]) {
95
99
  const headers: Record<string, string | undefined> = {};
96
100
  const cacheControl = readRequestHeader(c, 'cache-control');
97
101
  const ifNoneMatch = readRequestHeader(c, 'if-none-match');
102
+ for (const name of ['authorization', 'cookie', 'range', 'x-api-key', 'x-auth-token']) {
103
+ const value = readRequestHeader(c, name);
104
+ if (value) headers[name] = value;
105
+ }
98
106
 
99
107
  if (cacheControl) {
100
108
  headers['cache-control'] = cacheControl;
@@ -133,8 +141,8 @@ function applyHonoCachedResponse(
133
141
  c: HonoCacheContext,
134
142
  cached: CachedHonoResponse,
135
143
  ifNoneMatch: string | undefined,
136
- ): unknown {
137
- if (cached.etag && ifNoneMatch === cached.etag) {
144
+ ): Response | void {
145
+ if (cached.etag && matchesETag(ifNoneMatch, cached.etag)) {
138
146
  const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
139
147
  if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
140
148
  if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
@@ -159,6 +167,7 @@ function applyHonoCachedResponse(
159
167
  async function snapshotHonoResponse(
160
168
  c: HonoCacheContext,
161
169
  etag: boolean,
170
+ options: KeyDerivationOptions,
162
171
  ): Promise<CachedHonoResponse> {
163
172
  const res = c.res;
164
173
  if (!res) {
@@ -178,6 +187,7 @@ async function snapshotHonoResponse(
178
187
  }
179
188
 
180
189
  const status = res.status ?? 200;
190
+ if (!isShareableHttpResponse(status, name => res.headers?.get?.(name), options)) return { body: '', contentType, status: 0 };
181
191
  if (!isCacheableStatus(status)) {
182
192
  return { body: '', contentType, status };
183
193
  }
@@ -249,7 +259,6 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
249
259
  cache,
250
260
  etag = true,
251
261
  ttl = 300,
252
- swr,
253
262
  tags,
254
263
  skipCache,
255
264
  keyGenerator,
@@ -265,7 +274,7 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
265
274
  }
266
275
 
267
276
  const reqLike = toRequestLike(c, headerWhitelist);
268
- if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined)) {
277
+ if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined, { ...options, keyGenerator: keyGenerator ? () => keyGenerator(c) : undefined })) {
269
278
  return await next();
270
279
  }
271
280
 
@@ -289,14 +298,15 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
289
298
  async () => {
290
299
  ranNext = true;
291
300
  await next();
292
- const snapshot = await snapshotHonoResponse(c, etag);
301
+ const snapshot = await snapshotHonoResponse(c, etag, { headerWhitelist, keyGenerator: keyGenerator ? () => keyGenerator(c) : undefined });
293
302
  if (!isCacheableStatus(snapshot.status)) {
294
303
  throw new NonCacheableHonoResponseError(snapshot);
295
304
  }
296
305
  return snapshot;
297
306
  },
298
307
  ttl,
299
- { swr, tags: resolvedTags },
308
+ // Never invoke a completed Hono next() chain from background work.
309
+ { swr: 0, tags: resolvedTags },
300
310
  );
301
311
 
302
312
  return applyHonoCachedResponse(c, cached, ifNoneMatch);
@@ -4,6 +4,9 @@ import {
4
4
  buildDeterministicKey,
5
5
  generateETag,
6
6
  shouldSkipCache,
7
+ isCacheableHttpResponse,
8
+ isShareableHttpResponse,
9
+ matchesETag,
7
10
  type KeyDerivationOptions,
8
11
  } from './utils.js';
9
12
 
@@ -16,6 +19,8 @@ export interface ExpressCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDeriv
16
19
  skipCache?: (req: any) => boolean;
17
20
  /** Dynamic tags derivation from request. */
18
21
  tags?: string[] | ((req: any) => string[]);
22
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
23
+ swr?: number;
19
24
  }
20
25
 
21
26
  export interface CachedHttpResponse {
@@ -23,6 +28,14 @@ export interface CachedHttpResponse {
23
28
  contentType?: string;
24
29
  etag?: string;
25
30
  status: number;
31
+ binary?: boolean;
32
+ headers?: Record<string, string | string[]>;
33
+ }
34
+
35
+ class UncacheableHttpResponse extends Error {
36
+ constructor(readonly response: CachedHttpResponse, readonly shareable: boolean) {
37
+ super('Response is not cacheable');
38
+ }
26
39
  }
27
40
 
28
41
  /**
@@ -56,11 +69,11 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
56
69
  cache,
57
70
  etag = true,
58
71
  ttl = 300,
59
- swr,
60
72
  tags,
61
73
  skipCache,
62
74
  keyGenerator,
63
75
  headerWhitelist,
76
+ cacheAuthenticated,
64
77
  } = options;
65
78
 
66
79
  return async (req: any, res: any, next: any) => {
@@ -69,7 +82,7 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
69
82
  return next();
70
83
  }
71
84
 
72
- if (shouldSkipCache(req, skipCache)) {
85
+ if (shouldSkipCache(req, skipCache, options)) {
73
86
  return next();
74
87
  }
75
88
 
@@ -79,19 +92,70 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
79
92
  activeCache = CacheService.create();
80
93
  }
81
94
 
82
- const key = buildDeterministicKey(req, { keyGenerator, headerWhitelist });
95
+ const keyOptions = { keyGenerator, headerWhitelist, cacheAuthenticated };
96
+ const key = buildDeterministicKey(req, keyOptions);
83
97
  const ifNoneMatch = req.headers ? (req.headers['if-none-match'] || req.headers['If-None-Match']) : undefined;
84
98
 
85
99
  const resolvedTags = typeof tags === 'function' ? tags(req) : tags;
86
100
 
101
+ let respondedLocally = false;
102
+
87
103
  try {
88
104
  const cached = await activeCache.get<CachedHttpResponse>(
89
105
  key,
90
106
  async () => {
91
- return new Promise<CachedHttpResponse>((resolve) => {
92
- const origJson = res.json?.bind(res);
93
- const origSend = res.send?.bind(res);
94
- const origEnd = res.end?.bind(res);
107
+ return new Promise<CachedHttpResponse>((resolve, reject) => {
108
+ const rawJson = res.json;
109
+ const rawSend = res.send;
110
+ const rawEnd = res.end;
111
+ const rawWrite = res.write;
112
+ const origJson = rawJson?.bind(res);
113
+ const origSend = rawSend?.bind(res);
114
+ const origEnd = rawEnd?.bind(res);
115
+ let settled = false;
116
+ let streamed = false;
117
+
118
+ const cleanup = () => {
119
+ if (rawJson !== undefined) res.json = rawJson;
120
+ if (rawSend !== undefined) res.send = rawSend;
121
+ if (rawEnd !== undefined) res.end = rawEnd;
122
+ if (rawWrite !== undefined) res.write = rawWrite;
123
+ res.removeListener?.('close', onClose);
124
+ };
125
+
126
+ const settle = (response: CachedHttpResponse) => {
127
+ if (settled) return;
128
+ settled = true;
129
+ respondedLocally = true;
130
+ response.binary = Buffer.isBuffer(response.body);
131
+ if (typeof res.getHeaders === 'function') {
132
+ const headers: Record<string, string | string[]> = {};
133
+ for (const [name, value] of Object.entries(res.getHeaders())) {
134
+ if (!['content-length', 'transfer-encoding', 'connection', 'set-cookie', 'etag', 'content-type'].includes(name.toLowerCase()) && value != null) {
135
+ headers[name] = Array.isArray(value) ? value as string[] : String(value);
136
+ }
137
+ }
138
+ response.headers = headers;
139
+ }
140
+ const header = (name: string) => res.getHeader?.(name);
141
+ cleanup();
142
+ if (!streamed && isCacheableHttpResponse(response.status, header, keyOptions)) resolve(response);
143
+ else reject(new UncacheableHttpResponse(response, !streamed && isShareableHttpResponse(response.status, header, keyOptions)));
144
+ };
145
+
146
+ const onClose = () => {
147
+ if (settled) return;
148
+ settled = true;
149
+ respondedLocally = true;
150
+ cleanup();
151
+ reject(new Error('Express response closed before completion'));
152
+ };
153
+
154
+ res.once?.('close', onClose);
155
+ if (rawWrite) res.write = (...args: unknown[]) => {
156
+ streamed = true;
157
+ return rawWrite.apply(res, args);
158
+ };
95
159
 
96
160
  const getStatusCode = () => (res.statusCode ?? 200);
97
161
 
@@ -101,15 +165,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
101
165
  const bodyEtag = etag ? generateETag(body) : undefined;
102
166
  const contentType = res.getHeader?.('content-type') || 'application/json; charset=utf-8';
103
167
 
104
- resolve({ body, contentType, etag: bodyEtag, status });
168
+ settle({ body, contentType, etag: bodyEtag, status });
105
169
 
106
- if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
170
+ if (isCacheableHttpResponse(status, name => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
107
171
  res.status?.(304);
108
172
  origEnd?.();
109
173
  return;
110
174
  }
111
175
 
112
- if (bodyEtag && res.setHeader) {
176
+ if (status >= 200 && status < 300 && bodyEtag && res.setHeader) {
113
177
  res.setHeader('ETag', bodyEtag);
114
178
  }
115
179
  return origJson(body);
@@ -122,15 +186,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
122
186
  const bodyEtag = etag ? generateETag(body) : undefined;
123
187
  const contentType = res.getHeader?.('content-type') as string | undefined;
124
188
 
125
- resolve({ body, contentType, etag: bodyEtag, status });
189
+ settle({ body, contentType, etag: bodyEtag, status });
126
190
 
127
- if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
191
+ if (isCacheableHttpResponse(status, name => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
128
192
  res.status?.(304);
129
193
  origEnd?.();
130
194
  return;
131
195
  }
132
196
 
133
- if (bodyEtag && res.setHeader) {
197
+ if (status >= 200 && status < 300 && bodyEtag && res.setHeader) {
134
198
  res.setHeader('ETag', bodyEtag);
135
199
  }
136
200
  return origSend(body);
@@ -138,33 +202,37 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
138
202
  }
139
203
 
140
204
  if (origEnd) {
141
- res.end = (body?: unknown) => {
205
+ res.end = (body?: unknown, ...args: unknown[]) => {
142
206
  const status = getStatusCode();
143
207
  const bodyEtag = etag && body != null ? generateETag(body) : undefined;
144
208
  const contentType = res.getHeader?.('content-type') as string | undefined;
145
209
 
146
- resolve({ body, contentType, etag: bodyEtag, status });
147
- return origEnd(body as never);
210
+ settle({ body, contentType, etag: bodyEtag, status });
211
+ return origEnd(body, ...args);
148
212
  };
149
213
  }
150
214
 
151
- next();
215
+ try {
216
+ next();
217
+ } catch (err) {
218
+ if (!settled) {
219
+ settled = true;
220
+ cleanup();
221
+ reject(err);
222
+ }
223
+ }
152
224
  });
153
225
  },
154
226
  ttl,
155
- { swr, tags: resolvedTags }
227
+ // res/next belong to this request and cannot be reused for background SWR.
228
+ { swr: 0, tags: resolvedTags }
156
229
  );
157
230
 
158
- // Status gate: only cache 2xx successful responses
159
- if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
160
- await activeCache.delete(key).catch(() => {});
161
- return;
162
- }
163
-
164
- if (!res.headersSent) {
231
+ if (!respondedLocally && !res.headersSent) {
232
+ for (const [name, value] of Object.entries(cached.headers ?? {})) res.setHeader?.(name, value);
165
233
  if (cached.etag) {
166
234
  if (res.setHeader) res.setHeader('ETag', cached.etag);
167
- if (ifNoneMatch === cached.etag) {
235
+ if (matchesETag(ifNoneMatch, cached.etag)) {
168
236
  return res.status(304).end();
169
237
  }
170
238
  }
@@ -177,6 +245,11 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
177
245
  res.status(cached.status);
178
246
  }
179
247
 
248
+ if (req.method === 'HEAD') return res.end?.();
249
+ if (cached.binary) {
250
+ const body = Buffer.isBuffer(cached.body) ? cached.body : Buffer.from((cached.body as { data: number[] }).data);
251
+ return res.send ? res.send(body) : res.end?.(body);
252
+ }
180
253
  if (typeof cached.body === 'object' && cached.body !== null && res.json) {
181
254
  return res.json(cached.body);
182
255
  } else if (res.send) {
@@ -186,6 +259,17 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
186
259
  }
187
260
  }
188
261
  } catch (err) {
262
+ if (err instanceof UncacheableHttpResponse) {
263
+ if (respondedLocally || res.headersSent) return;
264
+ // Never share a private, varied, cookie-setting, or partial response with another request.
265
+ if (!err.shareable) return next();
266
+ const response = err.response;
267
+ if (response.contentType) res.setHeader?.('Content-Type', response.contentType);
268
+ res.status?.(response.status);
269
+ return typeof response.body === 'object' && response.body !== null && !response.binary && res.json
270
+ ? res.json(response.body)
271
+ : res.send ? res.send(response.body) : res.end?.(response.body);
272
+ }
189
273
  next(err);
190
274
  }
191
275
  };
@@ -4,6 +4,8 @@ import {
4
4
  buildDeterministicKey,
5
5
  generateETag,
6
6
  shouldSkipCache,
7
+ isCacheableHttpResponse,
8
+ matchesETag,
7
9
  type KeyDerivationOptions,
8
10
  } from './utils.js';
9
11
 
@@ -16,6 +18,8 @@ export interface FastifyCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDeriv
16
18
  skipCache?: (req: any) => boolean;
17
19
  /** Dynamic tags derivation from request. */
18
20
  tags?: string[] | ((req: any) => string[]);
21
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
22
+ swr?: number;
19
23
  }
20
24
 
21
25
  export interface CachedFastifyResponse {
@@ -23,6 +27,12 @@ export interface CachedFastifyResponse {
23
27
  contentType?: string;
24
28
  etag?: string;
25
29
  status: number;
30
+ binary?: boolean;
31
+ headers?: Record<string, string | string[]>;
32
+ }
33
+
34
+ function responseBody(entry: CachedFastifyResponse): unknown {
35
+ return entry.binary && !Buffer.isBuffer(entry.body) ? Buffer.from((entry.body as { data: number[] }).data) : entry.body;
26
36
  }
27
37
 
28
38
  /**
@@ -58,7 +68,7 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
58
68
  return;
59
69
  }
60
70
 
61
- if (shouldSkipCache(req, mergedOpts.skipCache)) {
71
+ if (shouldSkipCache(req, mergedOpts.skipCache, mergedOpts)) {
62
72
  return;
63
73
  }
64
74
 
@@ -71,17 +81,14 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
71
81
  ? (req.headers['if-none-match'] || req.headers['If-None-Match'])
72
82
  : undefined;
73
83
 
74
- // Fast probe in cache
75
- const cached = await activeCache!.get<CachedFastifyResponse | null>(
76
- key,
77
- async () => null,
78
- 0
79
- );
84
+ // Fast probe in cache without writing null entries on misses
85
+ const cached = await activeCache!.peek<CachedFastifyResponse>(key);
80
86
 
81
87
  if (cached && typeof cached === 'object' && cached.body !== null) {
88
+ for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header(name, value);
82
89
  if (cached.etag) {
83
90
  reply.header('ETag', cached.etag);
84
- if (ifNoneMatch === cached.etag) {
91
+ if (matchesETag(ifNoneMatch, cached.etag)) {
85
92
  reply.code(304);
86
93
  return reply.send();
87
94
  }
@@ -92,11 +99,12 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
92
99
  }
93
100
 
94
101
  reply.code(cached.status ?? 200);
95
- return reply.send(cached.body);
102
+ return reply.send(req.method === 'HEAD' ? undefined : responseBody(cached));
96
103
  }
97
104
 
98
105
  // Mark request for response capture in onSend
99
106
  req._tricacheKey = key;
107
+ req._tricacheCanCommit = activeCache!.captureMutationFence(key);
100
108
  const resolvedTags = typeof mergedOpts.tags === 'function'
101
109
  ? mergedOpts.tags(req)
102
110
  : mergedOpts.tags;
@@ -112,7 +120,8 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
112
120
  const statusCode = reply.statusCode ?? reply.raw?.statusCode ?? 200;
113
121
 
114
122
  // Status gate: only cache 2xx successful responses
115
- if (statusCode >= 200 && statusCode < 300 && payload !== undefined && payload !== null) {
123
+ if (req._tricacheCanCommit?.() && isCacheableHttpResponse(statusCode, name => reply.getHeader(name), mergedOpts) && payload !== undefined && payload !== null &&
124
+ !(typeof payload === 'object' && typeof (payload as { pipe?: unknown }).pipe === 'function')) {
116
125
  const payloadEtag = etag ? generateETag(payload) : undefined;
117
126
  const contentType = reply.getHeader('content-type')
118
127
  || (typeof payload === 'object' ? 'application/json' : 'text/plain');
@@ -125,22 +134,24 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
125
134
  ? (req.headers['if-none-match'] || req.headers['If-None-Match'])
126
135
  : undefined;
127
136
 
128
- if (ifNoneMatch && payloadEtag && ifNoneMatch === payloadEtag) {
129
- reply.code(304);
130
- return '';
131
- }
132
-
133
137
  // Asynchronously persist to cache without delaying current onSend pipeline
134
138
  const entry: CachedFastifyResponse = {
135
139
  body: payload,
136
140
  contentType,
137
141
  etag: payloadEtag,
138
142
  status: statusCode,
143
+ binary: Buffer.isBuffer(payload),
144
+ headers: reply.getHeaders ? Object.fromEntries(Object.entries(reply.getHeaders()).filter(([name]) =>
145
+ !['content-length', 'transfer-encoding', 'connection', 'set-cookie', 'content-type', 'etag'].includes(name.toLowerCase()))) as Record<string, string | string[]> : undefined,
139
146
  };
140
147
 
141
148
  void activeCache!.set(key, entry, mergedOpts.ttl ?? ttl, undefined, {
142
149
  tags: req._tricacheTags,
143
- });
150
+ }).catch(() => {});
151
+ if (payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
152
+ reply.code(304);
153
+ return '';
154
+ }
144
155
  }
145
156
 
146
157
  return payload;
@@ -173,7 +184,7 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
173
184
  const reply = second;
174
185
 
175
186
  if (req.method !== 'GET' && req.method !== 'HEAD') return;
176
- if (shouldSkipCache(req, options.skipCache)) return;
187
+ if (shouldSkipCache(req, options.skipCache, options)) return;
177
188
 
178
189
  let activeCache = options.cache;
179
190
  if (!activeCache) {
@@ -191,16 +202,13 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
191
202
  : undefined;
192
203
 
193
204
  // Fast-path probe
194
- const cached = await activeCache.get<CachedFastifyResponse | null>(
195
- key,
196
- async () => null,
197
- 0
198
- );
205
+ const cached = await activeCache.peek<CachedFastifyResponse>(key);
199
206
 
200
207
  if (cached && typeof cached === 'object' && cached.body !== null) {
208
+ for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header?.(name, value);
201
209
  if (cached.etag) {
202
210
  if (reply.header) reply.header('ETag', cached.etag);
203
- if (ifNoneMatch === cached.etag) {
211
+ if (matchesETag(ifNoneMatch, cached.etag)) {
204
212
  if (reply.code) reply.code(304);
205
213
  else if (reply.status) reply.status(304);
206
214
  if (reply.send) return reply.send();
@@ -217,11 +225,12 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
217
225
  else if (reply.status) reply.status(cached.status);
218
226
  }
219
227
 
220
- if (reply.send) return reply.send(cached.body);
228
+ if (reply.send) return reply.send(req.method === 'HEAD' ? undefined : responseBody(cached));
221
229
  return;
222
230
  }
223
231
 
224
232
  // Miss path: intercept reply.send on completion
233
+ const canCommit = activeCache.captureMutationFence(key);
225
234
  const origSend = reply.send?.bind(reply);
226
235
  if (origSend) {
227
236
  reply.send = function (resPayload: any) {
@@ -231,18 +240,19 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
231
240
  || (typeof resPayload === 'object' ? 'application/json' : 'text/plain');
232
241
 
233
242
  const respStatus = reply.statusCode ?? reply.raw?.statusCode ?? 200;
234
- if (respStatus >= 200 && respStatus < 300) {
243
+ const cacheable = isCacheableHttpResponse(respStatus, name => reply.getHeader?.(name), options);
244
+ if (cacheable && canCommit() && !(typeof resPayload === 'object' && typeof resPayload.pipe === 'function')) {
235
245
  const resolvedTags = typeof options.tags === 'function' ? options.tags(req) : options.tags;
236
246
  void activeCache!.set(
237
247
  key,
238
- { body: resPayload, contentType, etag: payloadEtag, status: respStatus },
248
+ { body: resPayload, contentType, etag: payloadEtag, status: respStatus, binary: Buffer.isBuffer(resPayload) },
239
249
  options.ttl ?? 300,
240
250
  undefined,
241
251
  { tags: resolvedTags }
242
- );
252
+ ).catch(() => {});
243
253
  }
244
254
 
245
- if (ifNoneMatch && ifNoneMatch === payloadEtag) {
255
+ if (cacheable && payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
246
256
  if (reply.code) reply.code(304);
247
257
  else if (reply.status) reply.status(304);
248
258
  return origSend();
package/src/http/utils.ts CHANGED
@@ -5,6 +5,45 @@ export interface KeyDerivationOptions {
5
5
  keyGenerator?: (req: any) => string;
6
6
  /** Optional list of header names (case-insensitive) to include in the cache key. */
7
7
  headerWhitelist?: string[];
8
+ /** Opt in to authenticated request caching with an identity-aware key. Default: false. */
9
+ cacheAuthenticated?: boolean;
10
+ }
11
+
12
+ export type HttpHeaderValue = string | number | string[] | undefined | null;
13
+
14
+ export function readHttpHeader(headers: any, name: string): HttpHeaderValue {
15
+ if (!headers) return undefined;
16
+ if (typeof headers.get === 'function') return headers.get(name);
17
+ const lower = name.toLowerCase();
18
+ return headers[lower] ?? headers[name] ?? Object.entries(headers).find(([key]) => key.toLowerCase() === lower)?.[1] as HttpHeaderValue;
19
+ }
20
+
21
+ export function hasCacheBypassDirective(value: HttpHeaderValue): boolean {
22
+ if (value == null) return false;
23
+ return String(value).split(',').some(part => /^(?:private|no-cache|no-store)(?:\s*=|\s*$)/i.test(part.trim()));
24
+ }
25
+
26
+ /** Shared-cache safety checks applied BEFORE a response enters storage or singleflight results. */
27
+ export function isShareableHttpResponse(
28
+ status: number,
29
+ header: (name: string) => HttpHeaderValue,
30
+ options: KeyDerivationOptions = {},
31
+ ): boolean {
32
+ if (status === 206 || hasCacheBypassDirective(header('cache-control')) || header('set-cookie')) return false;
33
+ if (String(header('content-type') ?? '').toLowerCase().includes('text/event-stream')) return false;
34
+ const vary = String(header('vary') ?? '').split(',').map(value => value.trim().toLowerCase()).filter(Boolean);
35
+ const keyedHeaders = new Set(options.headerWhitelist?.map(name => name.toLowerCase()));
36
+ return !vary.includes('*') && (Boolean(options.keyGenerator) || vary.every(name => keyedHeaders.has(name)));
37
+ }
38
+
39
+ export function isCacheableHttpResponse(status: number, header: (name: string) => HttpHeaderValue, options?: KeyDerivationOptions): boolean {
40
+ return status >= 200 && status < 300 && isShareableHttpResponse(status, header, options);
41
+ }
42
+
43
+ export function matchesETag(header: HttpHeaderValue, etag: string): boolean {
44
+ if (header == null) return false;
45
+ const normalized = etag.replace(/^W\//, '');
46
+ return String(header).split(',').some(value => value.trim() === '*' || value.trim().replace(/^W\//, '') === normalized);
8
47
  }
9
48
 
10
49
  /**
@@ -45,13 +84,15 @@ export function buildDeterministicKey(req: any, options?: KeyDerivationOptions):
45
84
  }
46
85
 
47
86
  if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
48
- const sortedHeaders = [...options.headerWhitelist].sort();
87
+ const sortedHeaders = [...new Set(options.headerWhitelist.map(h => h.toLowerCase()))].sort();
49
88
  for (const h of sortedHeaders) {
50
89
  const normalizedHeader = h.toLowerCase();
51
- const val = req.headers[normalizedHeader];
90
+ const val = readHttpHeader(req.headers, normalizedHeader);
52
91
  if (val !== undefined && val !== null && val !== '') {
53
92
  const headerStr = Array.isArray(val) ? val.join(',') : String(val);
54
- key += `|h:${normalizedHeader}=${headerStr}`;
93
+ const identity = /authorization|cookie|token|api-key/.test(normalizedHeader)
94
+ ? crypto.createHash('sha256').update(headerStr).digest('hex') : encodeURIComponent(headerStr);
95
+ key += `|h:${normalizedHeader}=${identity}`;
55
96
  }
56
97
  }
57
98
  }
@@ -63,17 +104,15 @@ export function buildDeterministicKey(req: any, options?: KeyDerivationOptions):
63
104
  * Checks if request specifies Cache-Control bypass directives (no-cache, no-store)
64
105
  * or matches a custom skipCache predicate.
65
106
  */
66
- export function shouldSkipCache(req: any, customSkip?: (req: any) => boolean): boolean {
107
+ export function shouldSkipCache(req: any, customSkip?: (req: any) => boolean, options: KeyDerivationOptions = {}): boolean {
67
108
  if (customSkip && customSkip(req)) return true;
68
-
69
- const cc = req.headers ? (req.headers['cache-control'] || req.headers['Cache-Control']) : undefined;
70
- if (typeof cc === 'string') {
71
- const lower = cc.toLowerCase();
72
- if (lower.includes('no-cache') || lower.includes('no-store')) {
73
- return true;
74
- }
109
+ if (hasCacheBypassDirective(readHttpHeader(req.headers, 'cache-control')) || readHttpHeader(req.headers, 'range')) return true;
110
+ const sensitiveHeaders = ['authorization', 'cookie', 'x-api-key', 'x-auth-token'].filter(name => readHttpHeader(req.headers, name));
111
+ if (sensitiveHeaders.length > 0) {
112
+ if (!options.cacheAuthenticated) return true;
113
+ const keyedHeaders = new Set(options.headerWhitelist?.map(name => name.toLowerCase()));
114
+ if (!options.keyGenerator && !sensitiveHeaders.every(name => keyedHeaders.has(name))) return true;
75
115
  }
76
-
77
116
  return false;
78
117
  }
79
118
 
@@ -81,12 +120,7 @@ export function shouldSkipCache(req: any, customSkip?: (req: any) => boolean): b
81
120
  * Compute a weak ETag (W/"...") from string, Buffer, or JSON-serializable object.
82
121
  */
83
122
  export function generateETag(data: unknown): string {
84
- const str = typeof data === 'string'
85
- ? data
86
- : Buffer.isBuffer(data)
87
- ? data.toString('utf8')
88
- : JSON.stringify(data);
89
-
90
- const hash = crypto.createHash('sha1').update(str).digest('hex').slice(0, 16);
91
- return `W/"${str.length.toString(16)}-${hash}"`;
123
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(typeof data === 'string' ? data : JSON.stringify(data) ?? '', 'utf8');
124
+ const hash = crypto.createHash('sha1').update(bytes).digest('hex').slice(0, 16);
125
+ return `W/"${bytes.length.toString(16)}-${hash}"`;
92
126
  }