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.
- package/README.md +36 -28
- package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
- package/dist/cache-service-CWI4jkS7.d.cts +963 -0
- package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/chunk-OYDU3SMI.js +89 -0
- package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
- package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
- package/dist/cli.cjs +1367 -625
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +27 -6
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +1370 -624
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +227 -123
- package/dist/edge/index.d.cts +127 -0
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +201 -117
- package/dist/hono/index.cjs +1418 -644
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
- package/dist/hono-C886ok3X.d.cts +391 -0
- package/dist/http/index.cjs +1514 -679
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +92 -43
- package/dist/index.cjs +1671 -790
- package/dist/index.d.cts +1006 -0
- package/dist/index.d.ts +39 -8
- package/dist/index.js +8 -8
- package/dist/murmur3-CMGw9PbV.d.cts +98 -0
- package/dist/nestjs/index.cjs +1454 -649
- package/dist/nestjs/index.d.cts +285 -0
- package/dist/nestjs/index.d.ts +103 -30
- package/dist/nestjs/index.js +115 -32
- package/dist/next/index.cjs +1512 -718
- package/dist/next/index.d.cts +232 -0
- package/dist/next/index.d.ts +33 -11
- package/dist/next/index.js +172 -99
- package/dist/prisma/index.cjs +11 -1
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +11 -1
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
- package/dist/types-BA4pz1A0.d.ts +1519 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +96 -36
- package/src/adapters/auto-pipeliner.ts +107 -24
- package/src/adapters/node-redis.ts +106 -27
- package/src/cache-service.ts +802 -502
- package/src/cli.ts +24 -6
- package/src/cross-region.ts +21 -3
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +171 -65
- package/src/edge/cache.ts +145 -97
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +2 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +62 -17
- package/src/http/fastify.ts +35 -21
- package/src/http/utils.ts +54 -20
- package/src/ipc-telemetry.ts +35 -9
- package/src/nestjs/decorators.ts +1 -1
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +13 -11
- package/src/nestjs/tricache.store.ts +51 -20
- package/src/nestjs/types.ts +29 -15
- package/src/next/cache-handler.ts +131 -53
- package/src/next/index.ts +1 -0
- package/src/next/types.ts +21 -0
- package/src/prisma/index.ts +12 -1
- package/src/smart-memory-cache.ts +63 -26
- package/src/types.ts +25 -2
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/wasm/bloom-filter-wasm.ts +9 -4
- package/src/worker-pool.ts +17 -8
- package/src/wtiny-lfu.ts +20 -6
- package/dist/chunk-BQRURGGD.js +0 -60
package/src/http/express.ts
CHANGED
|
@@ -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,7 +92,8 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
79
92
|
activeCache = CacheService.create();
|
|
80
93
|
}
|
|
81
94
|
|
|
82
|
-
const
|
|
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;
|
|
@@ -94,15 +108,18 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
94
108
|
const rawJson = res.json;
|
|
95
109
|
const rawSend = res.send;
|
|
96
110
|
const rawEnd = res.end;
|
|
111
|
+
const rawWrite = res.write;
|
|
97
112
|
const origJson = rawJson?.bind(res);
|
|
98
113
|
const origSend = rawSend?.bind(res);
|
|
99
114
|
const origEnd = rawEnd?.bind(res);
|
|
100
115
|
let settled = false;
|
|
116
|
+
let streamed = false;
|
|
101
117
|
|
|
102
118
|
const cleanup = () => {
|
|
103
119
|
if (rawJson !== undefined) res.json = rawJson;
|
|
104
120
|
if (rawSend !== undefined) res.send = rawSend;
|
|
105
121
|
if (rawEnd !== undefined) res.end = rawEnd;
|
|
122
|
+
if (rawWrite !== undefined) res.write = rawWrite;
|
|
106
123
|
res.removeListener?.('close', onClose);
|
|
107
124
|
};
|
|
108
125
|
|
|
@@ -110,8 +127,20 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
110
127
|
if (settled) return;
|
|
111
128
|
settled = true;
|
|
112
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);
|
|
113
141
|
cleanup();
|
|
114
|
-
resolve(response);
|
|
142
|
+
if (!streamed && isCacheableHttpResponse(response.status, header, keyOptions)) resolve(response);
|
|
143
|
+
else reject(new UncacheableHttpResponse(response, !streamed && isShareableHttpResponse(response.status, header, keyOptions)));
|
|
115
144
|
};
|
|
116
145
|
|
|
117
146
|
const onClose = () => {
|
|
@@ -123,6 +152,10 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
123
152
|
};
|
|
124
153
|
|
|
125
154
|
res.once?.('close', onClose);
|
|
155
|
+
if (rawWrite) res.write = (...args: unknown[]) => {
|
|
156
|
+
streamed = true;
|
|
157
|
+
return rawWrite.apply(res, args);
|
|
158
|
+
};
|
|
126
159
|
|
|
127
160
|
const getStatusCode = () => (res.statusCode ?? 200);
|
|
128
161
|
|
|
@@ -134,7 +167,7 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
134
167
|
|
|
135
168
|
settle({ body, contentType, etag: bodyEtag, status });
|
|
136
169
|
|
|
137
|
-
if (status
|
|
170
|
+
if (isCacheableHttpResponse(status, name => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
|
|
138
171
|
res.status?.(304);
|
|
139
172
|
origEnd?.();
|
|
140
173
|
return;
|
|
@@ -155,7 +188,7 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
155
188
|
|
|
156
189
|
settle({ body, contentType, etag: bodyEtag, status });
|
|
157
190
|
|
|
158
|
-
if (status
|
|
191
|
+
if (isCacheableHttpResponse(status, name => res.getHeader?.(name), keyOptions) && bodyEtag && matchesETag(ifNoneMatch, bodyEtag)) {
|
|
159
192
|
res.status?.(304);
|
|
160
193
|
origEnd?.();
|
|
161
194
|
return;
|
|
@@ -169,13 +202,13 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
169
202
|
}
|
|
170
203
|
|
|
171
204
|
if (origEnd) {
|
|
172
|
-
res.end = (body?: unknown) => {
|
|
205
|
+
res.end = (body?: unknown, ...args: unknown[]) => {
|
|
173
206
|
const status = getStatusCode();
|
|
174
207
|
const bodyEtag = etag && body != null ? generateETag(body) : undefined;
|
|
175
208
|
const contentType = res.getHeader?.('content-type') as string | undefined;
|
|
176
209
|
|
|
177
210
|
settle({ body, contentType, etag: bodyEtag, status });
|
|
178
|
-
return origEnd(body
|
|
211
|
+
return origEnd(body, ...args);
|
|
179
212
|
};
|
|
180
213
|
}
|
|
181
214
|
|
|
@@ -191,19 +224,15 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
191
224
|
});
|
|
192
225
|
},
|
|
193
226
|
ttl,
|
|
194
|
-
|
|
227
|
+
// res/next belong to this request and cannot be reused for background SWR.
|
|
228
|
+
{ swr: 0, tags: resolvedTags }
|
|
195
229
|
);
|
|
196
230
|
|
|
197
|
-
// Status gate: only cache 2xx successful responses
|
|
198
|
-
const isNon2xx = typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300);
|
|
199
|
-
if (isNon2xx) {
|
|
200
|
-
await activeCache.delete(key).catch(() => {});
|
|
201
|
-
}
|
|
202
|
-
|
|
203
231
|
if (!respondedLocally && !res.headersSent) {
|
|
204
|
-
|
|
232
|
+
for (const [name, value] of Object.entries(cached.headers ?? {})) res.setHeader?.(name, value);
|
|
233
|
+
if (cached.etag) {
|
|
205
234
|
if (res.setHeader) res.setHeader('ETag', cached.etag);
|
|
206
|
-
if (ifNoneMatch
|
|
235
|
+
if (matchesETag(ifNoneMatch, cached.etag)) {
|
|
207
236
|
return res.status(304).end();
|
|
208
237
|
}
|
|
209
238
|
}
|
|
@@ -216,6 +245,11 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
216
245
|
res.status(cached.status);
|
|
217
246
|
}
|
|
218
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
|
+
}
|
|
219
253
|
if (typeof cached.body === 'object' && cached.body !== null && res.json) {
|
|
220
254
|
return res.json(cached.body);
|
|
221
255
|
} else if (res.send) {
|
|
@@ -225,6 +259,17 @@ export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
|
225
259
|
}
|
|
226
260
|
}
|
|
227
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
|
+
}
|
|
228
273
|
next(err);
|
|
229
274
|
}
|
|
230
275
|
};
|
package/src/http/fastify.ts
CHANGED
|
@@ -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
|
|
|
@@ -75,9 +85,10 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
|
|
|
75
85
|
const cached = await activeCache!.peek<CachedFastifyResponse>(key);
|
|
76
86
|
|
|
77
87
|
if (cached && typeof cached === 'object' && cached.body !== null) {
|
|
88
|
+
for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header(name, value);
|
|
78
89
|
if (cached.etag) {
|
|
79
90
|
reply.header('ETag', cached.etag);
|
|
80
|
-
if (ifNoneMatch
|
|
91
|
+
if (matchesETag(ifNoneMatch, cached.etag)) {
|
|
81
92
|
reply.code(304);
|
|
82
93
|
return reply.send();
|
|
83
94
|
}
|
|
@@ -88,11 +99,12 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
|
|
|
88
99
|
}
|
|
89
100
|
|
|
90
101
|
reply.code(cached.status ?? 200);
|
|
91
|
-
return reply.send(cached
|
|
102
|
+
return reply.send(req.method === 'HEAD' ? undefined : responseBody(cached));
|
|
92
103
|
}
|
|
93
104
|
|
|
94
105
|
// Mark request for response capture in onSend
|
|
95
106
|
req._tricacheKey = key;
|
|
107
|
+
req._tricacheCanCommit = activeCache!.captureMutationFence(key);
|
|
96
108
|
const resolvedTags = typeof mergedOpts.tags === 'function'
|
|
97
109
|
? mergedOpts.tags(req)
|
|
98
110
|
: mergedOpts.tags;
|
|
@@ -108,7 +120,8 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
|
|
|
108
120
|
const statusCode = reply.statusCode ?? reply.raw?.statusCode ?? 200;
|
|
109
121
|
|
|
110
122
|
// Status gate: only cache 2xx successful responses
|
|
111
|
-
if (
|
|
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')) {
|
|
112
125
|
const payloadEtag = etag ? generateETag(payload) : undefined;
|
|
113
126
|
const contentType = reply.getHeader('content-type')
|
|
114
127
|
|| (typeof payload === 'object' ? 'application/json' : 'text/plain');
|
|
@@ -121,22 +134,24 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
|
|
|
121
134
|
? (req.headers['if-none-match'] || req.headers['If-None-Match'])
|
|
122
135
|
: undefined;
|
|
123
136
|
|
|
124
|
-
if (ifNoneMatch && payloadEtag && ifNoneMatch === payloadEtag) {
|
|
125
|
-
reply.code(304);
|
|
126
|
-
return '';
|
|
127
|
-
}
|
|
128
|
-
|
|
129
137
|
// Asynchronously persist to cache without delaying current onSend pipeline
|
|
130
138
|
const entry: CachedFastifyResponse = {
|
|
131
139
|
body: payload,
|
|
132
140
|
contentType,
|
|
133
141
|
etag: payloadEtag,
|
|
134
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,
|
|
135
146
|
};
|
|
136
147
|
|
|
137
148
|
void activeCache!.set(key, entry, mergedOpts.ttl ?? ttl, undefined, {
|
|
138
149
|
tags: req._tricacheTags,
|
|
139
150
|
}).catch(() => {});
|
|
151
|
+
if (payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
|
|
152
|
+
reply.code(304);
|
|
153
|
+
return '';
|
|
154
|
+
}
|
|
140
155
|
}
|
|
141
156
|
|
|
142
157
|
return payload;
|
|
@@ -169,7 +184,7 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
|
|
|
169
184
|
const reply = second;
|
|
170
185
|
|
|
171
186
|
if (req.method !== 'GET' && req.method !== 'HEAD') return;
|
|
172
|
-
if (shouldSkipCache(req, options.skipCache)) return;
|
|
187
|
+
if (shouldSkipCache(req, options.skipCache, options)) return;
|
|
173
188
|
|
|
174
189
|
let activeCache = options.cache;
|
|
175
190
|
if (!activeCache) {
|
|
@@ -187,16 +202,13 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
|
|
|
187
202
|
: undefined;
|
|
188
203
|
|
|
189
204
|
// Fast-path probe
|
|
190
|
-
const cached = await activeCache.
|
|
191
|
-
key,
|
|
192
|
-
async () => null,
|
|
193
|
-
0
|
|
194
|
-
);
|
|
205
|
+
const cached = await activeCache.peek<CachedFastifyResponse>(key);
|
|
195
206
|
|
|
196
207
|
if (cached && typeof cached === 'object' && cached.body !== null) {
|
|
208
|
+
for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header?.(name, value);
|
|
197
209
|
if (cached.etag) {
|
|
198
210
|
if (reply.header) reply.header('ETag', cached.etag);
|
|
199
|
-
if (ifNoneMatch
|
|
211
|
+
if (matchesETag(ifNoneMatch, cached.etag)) {
|
|
200
212
|
if (reply.code) reply.code(304);
|
|
201
213
|
else if (reply.status) reply.status(304);
|
|
202
214
|
if (reply.send) return reply.send();
|
|
@@ -213,11 +225,12 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
|
|
|
213
225
|
else if (reply.status) reply.status(cached.status);
|
|
214
226
|
}
|
|
215
227
|
|
|
216
|
-
if (reply.send) return reply.send(cached
|
|
228
|
+
if (reply.send) return reply.send(req.method === 'HEAD' ? undefined : responseBody(cached));
|
|
217
229
|
return;
|
|
218
230
|
}
|
|
219
231
|
|
|
220
232
|
// Miss path: intercept reply.send on completion
|
|
233
|
+
const canCommit = activeCache.captureMutationFence(key);
|
|
221
234
|
const origSend = reply.send?.bind(reply);
|
|
222
235
|
if (origSend) {
|
|
223
236
|
reply.send = function (resPayload: any) {
|
|
@@ -227,18 +240,19 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
|
|
|
227
240
|
|| (typeof resPayload === 'object' ? 'application/json' : 'text/plain');
|
|
228
241
|
|
|
229
242
|
const respStatus = reply.statusCode ?? reply.raw?.statusCode ?? 200;
|
|
230
|
-
|
|
243
|
+
const cacheable = isCacheableHttpResponse(respStatus, name => reply.getHeader?.(name), options);
|
|
244
|
+
if (cacheable && canCommit() && !(typeof resPayload === 'object' && typeof resPayload.pipe === 'function')) {
|
|
231
245
|
const resolvedTags = typeof options.tags === 'function' ? options.tags(req) : options.tags;
|
|
232
246
|
void activeCache!.set(
|
|
233
247
|
key,
|
|
234
|
-
{ body: resPayload, contentType, etag: payloadEtag, status: respStatus },
|
|
248
|
+
{ body: resPayload, contentType, etag: payloadEtag, status: respStatus, binary: Buffer.isBuffer(resPayload) },
|
|
235
249
|
options.ttl ?? 300,
|
|
236
250
|
undefined,
|
|
237
251
|
{ tags: resolvedTags }
|
|
238
|
-
);
|
|
252
|
+
).catch(() => {});
|
|
239
253
|
}
|
|
240
254
|
|
|
241
|
-
if (
|
|
255
|
+
if (cacheable && payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
|
|
242
256
|
if (reply.code) reply.code(304);
|
|
243
257
|
else if (reply.status) reply.status(304);
|
|
244
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
|
|
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
|
-
|
|
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
|
|
70
|
-
if (
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
|
85
|
-
|
|
86
|
-
|
|
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
|
}
|
package/src/ipc-telemetry.ts
CHANGED
|
@@ -56,6 +56,8 @@ export class IpcTelemetryServer {
|
|
|
56
56
|
private server: net.Server | null = null;
|
|
57
57
|
public readonly socketPath: string;
|
|
58
58
|
private _closed = false;
|
|
59
|
+
private _starting: Promise<void> | null = null;
|
|
60
|
+
private readonly sockets = new Set<net.Socket>();
|
|
59
61
|
private _exitHandler: (() => void) | null = null;
|
|
60
62
|
private _sigintHandler: (() => void) | null = null;
|
|
61
63
|
private _sigtermHandler: (() => void) | null = null;
|
|
@@ -71,12 +73,20 @@ export class IpcTelemetryServer {
|
|
|
71
73
|
* Start listening on the IPC socket / pipe.
|
|
72
74
|
*/
|
|
73
75
|
async start(): Promise<void> {
|
|
74
|
-
if (this.
|
|
76
|
+
if (this._closed || this.server?.listening) return;
|
|
77
|
+
if (this._starting) return this._starting;
|
|
78
|
+
this._starting = this.startInternal();
|
|
79
|
+
try { await this._starting; }
|
|
80
|
+
finally { this._starting = null; }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private async startInternal(): Promise<void> {
|
|
75
84
|
|
|
76
85
|
// Hygiene on POSIX: check if an orphaned socket file exists from a crashed run
|
|
77
86
|
if (process.platform !== 'win32' && fs.existsSync(this.socketPath)) {
|
|
78
87
|
await new Promise<void>((resolve) => {
|
|
79
88
|
const testSocket = net.createConnection(this.socketPath);
|
|
89
|
+
testSocket.setTimeout(1000, () => { testSocket.destroy(); resolve(); });
|
|
80
90
|
testSocket.once('connect', () => {
|
|
81
91
|
testSocket.destroy();
|
|
82
92
|
// Active server already listening on this socket
|
|
@@ -94,22 +104,30 @@ export class IpcTelemetryServer {
|
|
|
94
104
|
});
|
|
95
105
|
});
|
|
96
106
|
}
|
|
107
|
+
if (this._closed) return;
|
|
97
108
|
|
|
98
109
|
this.server = net.createServer((socket) => {
|
|
110
|
+
if (this._closed) { socket.destroy(); return; }
|
|
111
|
+
this.sockets.add(socket);
|
|
112
|
+
socket.once('close', () => this.sockets.delete(socket));
|
|
113
|
+
socket.setTimeout(5000, () => socket.destroy());
|
|
99
114
|
let buffer = '';
|
|
115
|
+
let pending = 0;
|
|
100
116
|
|
|
101
117
|
socket.on('data', (chunk) => {
|
|
118
|
+
if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) { socket.destroy(); return; }
|
|
102
119
|
buffer += chunk.toString('utf8');
|
|
103
120
|
let newlineIndex: number;
|
|
104
121
|
while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
|
|
105
122
|
const line = buffer.slice(0, newlineIndex).trim();
|
|
106
123
|
buffer = buffer.slice(newlineIndex + 1);
|
|
107
124
|
if (!line) continue;
|
|
125
|
+
if (++pending > 8) { socket.destroy(); return; }
|
|
108
126
|
|
|
109
127
|
// Non-blocking telemetry pull: pull stats snapshot on tick boundaries
|
|
110
128
|
// using setImmediate so serialization never introduces event loop stalls.
|
|
111
129
|
setImmediate(() => {
|
|
112
|
-
if (socket.destroyed) return;
|
|
130
|
+
if (socket.destroyed) { pending--; return; }
|
|
113
131
|
try {
|
|
114
132
|
let cmd = line;
|
|
115
133
|
try {
|
|
@@ -138,6 +156,8 @@ export class IpcTelemetryServer {
|
|
|
138
156
|
if (!socket.destroyed) {
|
|
139
157
|
socket.write(JSON.stringify({ error: (err as Error).message }) + '\n');
|
|
140
158
|
}
|
|
159
|
+
} finally {
|
|
160
|
+
pending--;
|
|
141
161
|
}
|
|
142
162
|
});
|
|
143
163
|
}
|
|
@@ -147,24 +167,29 @@ export class IpcTelemetryServer {
|
|
|
147
167
|
// Suppress client disconnection errors on IPC socket
|
|
148
168
|
});
|
|
149
169
|
});
|
|
170
|
+
this.server.maxConnections = 128;
|
|
150
171
|
|
|
151
172
|
await new Promise<void>((resolve, reject) => {
|
|
152
|
-
this.server
|
|
153
|
-
|
|
154
|
-
|
|
173
|
+
const server = this.server!;
|
|
174
|
+
const cleanup = () => { server.off('error', failed); server.off('close', closed); };
|
|
175
|
+
const failed = (error: Error) => { cleanup(); reject(error); };
|
|
176
|
+
const closed = () => { cleanup(); resolve(); }; // close() can cancel listen before its callback fires.
|
|
177
|
+
server.once('error', failed);
|
|
178
|
+
server.once('close', closed);
|
|
179
|
+
server.listen(this.socketPath, () => {
|
|
180
|
+
cleanup();
|
|
155
181
|
resolve();
|
|
156
182
|
});
|
|
157
183
|
});
|
|
184
|
+
if (this._closed) { if (this.server.listening) this.server.close(); return; }
|
|
158
185
|
|
|
159
186
|
// Register process termination handlers to guarantee socket hygiene
|
|
160
187
|
this._exitHandler = () => this._unlinkSocket();
|
|
161
188
|
this._sigintHandler = () => {
|
|
162
189
|
this._unlinkSocket();
|
|
163
|
-
process.exit(0);
|
|
164
190
|
};
|
|
165
191
|
this._sigtermHandler = () => {
|
|
166
192
|
this._unlinkSocket();
|
|
167
|
-
process.exit(0);
|
|
168
193
|
};
|
|
169
194
|
|
|
170
195
|
process.once('exit', this._exitHandler);
|
|
@@ -198,6 +223,7 @@ export class IpcTelemetryServer {
|
|
|
198
223
|
private _unlinkSocket(): void {
|
|
199
224
|
if (this._closed) return;
|
|
200
225
|
this._closed = true;
|
|
226
|
+
for (const socket of this.sockets) socket.destroy();
|
|
201
227
|
try {
|
|
202
228
|
this.server?.close();
|
|
203
229
|
} catch {
|
|
@@ -218,6 +244,8 @@ export class IpcTelemetryServer {
|
|
|
218
244
|
* Gracefully close the IPC telemetry server and clean up handlers and sockets.
|
|
219
245
|
*/
|
|
220
246
|
async close(): Promise<void> {
|
|
247
|
+
this._unlinkSocket();
|
|
248
|
+
await this._starting?.catch(() => {});
|
|
221
249
|
if (this._exitHandler) {
|
|
222
250
|
process.removeListener('exit', this._exitHandler);
|
|
223
251
|
this._exitHandler = null;
|
|
@@ -231,8 +259,6 @@ export class IpcTelemetryServer {
|
|
|
231
259
|
this._sigtermHandler = null;
|
|
232
260
|
}
|
|
233
261
|
|
|
234
|
-
this._unlinkSocket();
|
|
235
|
-
|
|
236
262
|
return new Promise<void>((resolve) => {
|
|
237
263
|
if (!this.server || !this.server.listening) {
|
|
238
264
|
resolve();
|
package/src/nestjs/decorators.ts
CHANGED
|
@@ -81,7 +81,7 @@ export function Cacheable(options: CacheableOptions = {}): MethodDecorator {
|
|
|
81
81
|
const rawTtl = options.ttl;
|
|
82
82
|
if (typeof rawTtl === 'number') {
|
|
83
83
|
if (options.ttlUnit === 'milliseconds' || (rawTtl >= 1000 && rawTtl % 1000 === 0 && options.ttlUnit !== 'seconds')) {
|
|
84
|
-
ttlSeconds =
|
|
84
|
+
ttlSeconds = rawTtl / 1000;
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
|
package/src/nestjs/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { TriCacheModule } from './tricache.module.js';
|
|
|
2
2
|
|
|
3
3
|
export { TriCacheModule };
|
|
4
4
|
export { TriCacheStore } from './tricache.store.js';
|
|
5
|
+
export { TriCacheKeyvAdapter } from './keyv-adapter.js';
|
|
5
6
|
export {
|
|
6
7
|
Cacheable,
|
|
7
8
|
CacheEvict,
|
|
@@ -18,6 +19,7 @@ export {
|
|
|
18
19
|
type TriCacheAsyncOptions,
|
|
19
20
|
type TriCacheOptionsFactory,
|
|
20
21
|
type NestCacheStore,
|
|
22
|
+
type TriCacheModuleOptions,
|
|
21
23
|
} from './types.js';
|
|
22
24
|
|
|
23
25
|
export default TriCacheModule;
|