tricache 0.7.1 → 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.
- package/LICENSE +21 -21
- package/README.md +87 -1371
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2790 -471
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2553 -470
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +2926 -562
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +220 -72
- package/dist/index.cjs +6936 -2518
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2494 -463
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2517 -483
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
- package/package.json +34 -6
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1339 -402
- package/src/cli.ts +120 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +203 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +39 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +290 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import type { CacheService } from '../cache-service.js';
|
|
2
|
+
import type { WrapOptions } from '../types.js';
|
|
3
|
+
import {
|
|
4
|
+
buildDeterministicKey,
|
|
5
|
+
generateETag,
|
|
6
|
+
shouldSkipCache,
|
|
7
|
+
type KeyDerivationOptions,
|
|
8
|
+
} from './utils.js';
|
|
9
|
+
|
|
10
|
+
export interface FastifyCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOptions {
|
|
11
|
+
/** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
|
|
12
|
+
cache?: CacheService;
|
|
13
|
+
/** Whether to generate and evaluate weak ETags. Default: true. */
|
|
14
|
+
etag?: boolean;
|
|
15
|
+
/** Custom predicate to skip caching dynamically for this request. */
|
|
16
|
+
skipCache?: (req: any) => boolean;
|
|
17
|
+
/** Dynamic tags derivation from request. */
|
|
18
|
+
tags?: string[] | ((req: any) => string[]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CachedFastifyResponse {
|
|
22
|
+
body: unknown;
|
|
23
|
+
contentType?: string;
|
|
24
|
+
etag?: string;
|
|
25
|
+
status: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Creates a Fastify plugin that registers `onRequest` and `onSend` lifecycle hooks.
|
|
30
|
+
*
|
|
31
|
+
* Designed to bypass Fastify's route encapsulation barrier (`skip-override`),
|
|
32
|
+
* allowing caching across global and nested route scopes.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* import Fastify from 'fastify';
|
|
36
|
+
* import { fastifyCachePlugin } from 'tricache/http';
|
|
37
|
+
*
|
|
38
|
+
* const app = Fastify();
|
|
39
|
+
* await app.register(fastifyCachePlugin, {
|
|
40
|
+
* ttl: 300,
|
|
41
|
+
* tags: ['api'],
|
|
42
|
+
* });
|
|
43
|
+
*/
|
|
44
|
+
export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
|
|
45
|
+
const plugin = async function (fastify: any, pluginOpts: FastifyCacheOptions = {}) {
|
|
46
|
+
const mergedOpts = { ...options, ...pluginOpts };
|
|
47
|
+
const etag = mergedOpts.etag ?? true;
|
|
48
|
+
const ttl = mergedOpts.ttl ?? 300;
|
|
49
|
+
let activeCache = mergedOpts.cache;
|
|
50
|
+
|
|
51
|
+
if (!activeCache) {
|
|
52
|
+
const { CacheService } = await import('../cache-service.js');
|
|
53
|
+
activeCache = CacheService.create();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
fastify.addHook('onRequest', async (req: any, reply: any) => {
|
|
57
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (shouldSkipCache(req, mergedOpts.skipCache)) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const key = buildDeterministicKey(req, {
|
|
66
|
+
keyGenerator: mergedOpts.keyGenerator,
|
|
67
|
+
headerWhitelist: mergedOpts.headerWhitelist,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const ifNoneMatch = req.headers
|
|
71
|
+
? (req.headers['if-none-match'] || req.headers['If-None-Match'])
|
|
72
|
+
: undefined;
|
|
73
|
+
|
|
74
|
+
// Fast probe in cache
|
|
75
|
+
const cached = await activeCache!.get<CachedFastifyResponse | null>(
|
|
76
|
+
key,
|
|
77
|
+
async () => null,
|
|
78
|
+
0
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
if (cached && typeof cached === 'object' && cached.body !== null) {
|
|
82
|
+
if (cached.etag) {
|
|
83
|
+
reply.header('ETag', cached.etag);
|
|
84
|
+
if (ifNoneMatch === cached.etag) {
|
|
85
|
+
reply.code(304);
|
|
86
|
+
return reply.send();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (cached.contentType) {
|
|
91
|
+
reply.header('Content-Type', cached.contentType);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
reply.code(cached.status ?? 200);
|
|
95
|
+
return reply.send(cached.body);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Mark request for response capture in onSend
|
|
99
|
+
req._tricacheKey = key;
|
|
100
|
+
const resolvedTags = typeof mergedOpts.tags === 'function'
|
|
101
|
+
? mergedOpts.tags(req)
|
|
102
|
+
: mergedOpts.tags;
|
|
103
|
+
req._tricacheTags = resolvedTags;
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
fastify.addHook('onSend', async (req: any, reply: any, payload: unknown) => {
|
|
107
|
+
const key = req._tricacheKey;
|
|
108
|
+
if (!key) {
|
|
109
|
+
return payload;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const statusCode = reply.statusCode ?? reply.raw?.statusCode ?? 200;
|
|
113
|
+
|
|
114
|
+
// Status gate: only cache 2xx successful responses
|
|
115
|
+
if (statusCode >= 200 && statusCode < 300 && payload !== undefined && payload !== null) {
|
|
116
|
+
const payloadEtag = etag ? generateETag(payload) : undefined;
|
|
117
|
+
const contentType = reply.getHeader('content-type')
|
|
118
|
+
|| (typeof payload === 'object' ? 'application/json' : 'text/plain');
|
|
119
|
+
|
|
120
|
+
if (payloadEtag) {
|
|
121
|
+
reply.header('ETag', payloadEtag);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const ifNoneMatch = req.headers
|
|
125
|
+
? (req.headers['if-none-match'] || req.headers['If-None-Match'])
|
|
126
|
+
: undefined;
|
|
127
|
+
|
|
128
|
+
if (ifNoneMatch && payloadEtag && ifNoneMatch === payloadEtag) {
|
|
129
|
+
reply.code(304);
|
|
130
|
+
return '';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Asynchronously persist to cache without delaying current onSend pipeline
|
|
134
|
+
const entry: CachedFastifyResponse = {
|
|
135
|
+
body: payload,
|
|
136
|
+
contentType,
|
|
137
|
+
etag: payloadEtag,
|
|
138
|
+
status: statusCode,
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
void activeCache!.set(key, entry, mergedOpts.ttl ?? ttl, undefined, {
|
|
142
|
+
tags: req._tricacheTags,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return payload;
|
|
147
|
+
});
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// Attach Fastify skip-override symbol so plugin is not scoped to child contexts
|
|
151
|
+
(plugin as any)[Symbol.for('skip-override')] = true;
|
|
152
|
+
return plugin;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Standard Fastify plugin export */
|
|
156
|
+
export const fastifyCachePlugin = createFastifyPlugin();
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Universal Fastify middleware: functions both as a Fastify plugin (`fastify.register(fastifyCache(options))`)
|
|
160
|
+
* and as a route preHandler hook (`fastify.get('/route', { preHandler: fastifyCache(options) })`).
|
|
161
|
+
*/
|
|
162
|
+
export function fastifyCache(options: FastifyCacheOptions = {}) {
|
|
163
|
+
const plugin = createFastifyPlugin(options);
|
|
164
|
+
|
|
165
|
+
const dualHandler = async function (first: any, second?: any) {
|
|
166
|
+
// If invoked as a Fastify plugin: (fastify, pluginOpts)
|
|
167
|
+
if (first && typeof first.addHook === 'function') {
|
|
168
|
+
return plugin(first, second);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Otherwise invoked as a route preHandler: (req, reply)
|
|
172
|
+
const req = first;
|
|
173
|
+
const reply = second;
|
|
174
|
+
|
|
175
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return;
|
|
176
|
+
if (shouldSkipCache(req, options.skipCache)) return;
|
|
177
|
+
|
|
178
|
+
let activeCache = options.cache;
|
|
179
|
+
if (!activeCache) {
|
|
180
|
+
const { CacheService } = await import('../cache-service.js');
|
|
181
|
+
activeCache = CacheService.create();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const key = buildDeterministicKey(req, {
|
|
185
|
+
keyGenerator: options.keyGenerator,
|
|
186
|
+
headerWhitelist: options.headerWhitelist,
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const ifNoneMatch = req.headers
|
|
190
|
+
? (req.headers['if-none-match'] || req.headers['If-None-Match'])
|
|
191
|
+
: undefined;
|
|
192
|
+
|
|
193
|
+
// Fast-path probe
|
|
194
|
+
const cached = await activeCache.get<CachedFastifyResponse | null>(
|
|
195
|
+
key,
|
|
196
|
+
async () => null,
|
|
197
|
+
0
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
if (cached && typeof cached === 'object' && cached.body !== null) {
|
|
201
|
+
if (cached.etag) {
|
|
202
|
+
if (reply.header) reply.header('ETag', cached.etag);
|
|
203
|
+
if (ifNoneMatch === cached.etag) {
|
|
204
|
+
if (reply.code) reply.code(304);
|
|
205
|
+
else if (reply.status) reply.status(304);
|
|
206
|
+
if (reply.send) return reply.send();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (cached.contentType && reply.header) {
|
|
212
|
+
reply.header('Content-Type', cached.contentType);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (cached.status) {
|
|
216
|
+
if (reply.code) reply.code(cached.status);
|
|
217
|
+
else if (reply.status) reply.status(cached.status);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (reply.send) return reply.send(cached.body);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Miss path: intercept reply.send on completion
|
|
225
|
+
const origSend = reply.send?.bind(reply);
|
|
226
|
+
if (origSend) {
|
|
227
|
+
reply.send = function (resPayload: any) {
|
|
228
|
+
if (resPayload !== undefined && resPayload !== null) {
|
|
229
|
+
const payloadEtag = options.etag !== false ? generateETag(resPayload) : undefined;
|
|
230
|
+
const contentType = (reply.getHeader && reply.getHeader('content-type'))
|
|
231
|
+
|| (typeof resPayload === 'object' ? 'application/json' : 'text/plain');
|
|
232
|
+
|
|
233
|
+
const respStatus = reply.statusCode ?? reply.raw?.statusCode ?? 200;
|
|
234
|
+
if (respStatus >= 200 && respStatus < 300) {
|
|
235
|
+
const resolvedTags = typeof options.tags === 'function' ? options.tags(req) : options.tags;
|
|
236
|
+
void activeCache!.set(
|
|
237
|
+
key,
|
|
238
|
+
{ body: resPayload, contentType, etag: payloadEtag, status: respStatus },
|
|
239
|
+
options.ttl ?? 300,
|
|
240
|
+
undefined,
|
|
241
|
+
{ tags: resolvedTags }
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (ifNoneMatch && ifNoneMatch === payloadEtag) {
|
|
246
|
+
if (reply.code) reply.code(304);
|
|
247
|
+
else if (reply.status) reply.status(304);
|
|
248
|
+
return origSend();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (payloadEtag && reply.header) reply.header('ETag', payloadEtag);
|
|
252
|
+
}
|
|
253
|
+
return origSend(resPayload);
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
(dualHandler as any)[Symbol.for('skip-override')] = true;
|
|
259
|
+
return dualHandler;
|
|
260
|
+
}
|
package/src/http/index.ts
CHANGED
|
@@ -1,265 +1,46 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* tricache/http — Universal HTTP Caching, ETag generation, and 304 Not Modified middleware
|
|
3
|
-
* for Express
|
|
3
|
+
* for Express and Fastify.
|
|
4
4
|
*
|
|
5
5
|
* Usage with Express:
|
|
6
|
-
* import {
|
|
7
|
-
* app.get('/api/users',
|
|
6
|
+
* import { createExpressMiddleware } from 'tricache/http';
|
|
7
|
+
* app.get('/api/users', createExpressMiddleware({ cache, ttl: 300, tags: ['users'] }), handler);
|
|
8
8
|
*
|
|
9
|
-
* Usage with
|
|
10
|
-
* import {
|
|
11
|
-
*
|
|
9
|
+
* Usage with Fastify:
|
|
10
|
+
* import { fastifyCachePlugin } from 'tricache/http';
|
|
11
|
+
* await fastify.register(fastifyCachePlugin, { cache, ttl: 300 });
|
|
12
|
+
*
|
|
13
|
+
* For Edge runtimes (Cloudflare Workers, Vercel Edge, Deno) and Hono, use:
|
|
14
|
+
* import { honoEdgeCache } from 'tricache/edge';
|
|
12
15
|
*/
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
return next();
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
let activeCache = cache;
|
|
48
|
-
if (!activeCache) {
|
|
49
|
-
const { CacheService } = await import('../cache-service.js');
|
|
50
|
-
activeCache = CacheService.create();
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.originalUrl || req.url}`;
|
|
54
|
-
const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
|
|
55
|
-
|
|
56
|
-
try {
|
|
57
|
-
const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string; status?: number }>(
|
|
58
|
-
key,
|
|
59
|
-
async () => {
|
|
60
|
-
return new Promise((resolve) => {
|
|
61
|
-
const origJson = res.json?.bind(res);
|
|
62
|
-
const origSend = res.send?.bind(res);
|
|
63
|
-
const origEnd = res.end?.bind(res);
|
|
64
|
-
const statusOf = () => (res as { statusCode?: number }).statusCode;
|
|
65
|
-
|
|
66
|
-
if (origJson) {
|
|
67
|
-
res.json = (body: any) => {
|
|
68
|
-
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
69
|
-
resolve({ body, contentType: 'application/json; charset=utf-8', etag: bodyEtag, status: statusOf() });
|
|
70
|
-
if (ifNoneMatch && ifNoneMatch === bodyEtag) {
|
|
71
|
-
res.status?.(304);
|
|
72
|
-
origEnd?.();
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
|
|
76
|
-
return origJson(body);
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
if (origSend) {
|
|
81
|
-
res.send = (body: any) => {
|
|
82
|
-
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
83
|
-
resolve({ body, contentType: res.getHeader ? (res.getHeader('content-type') as string | undefined) : undefined, etag: bodyEtag, status: statusOf() });
|
|
84
|
-
if (ifNoneMatch && ifNoneMatch === bodyEtag) {
|
|
85
|
-
res.status?.(304);
|
|
86
|
-
origEnd?.();
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
if (bodyEtag && res.setHeader) res.setHeader('ETag', bodyEtag);
|
|
90
|
-
return origSend(body);
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// Handlers that answer via res.end() (empty bodies, strings, buffers)
|
|
95
|
-
// previously never resolved the fetchFn promise — the middleware hung
|
|
96
|
-
// forever. end() is a third completion signal alongside json/send.
|
|
97
|
-
if (origEnd) {
|
|
98
|
-
res.end = (body?: unknown) => {
|
|
99
|
-
const bodyEtag = etag && body != null ? generateETag(body) : undefined;
|
|
100
|
-
resolve({ body, contentType: res.getHeader ? (res.getHeader('content-type') as string | undefined) : undefined, etag: bodyEtag, status: statusOf() });
|
|
101
|
-
return origEnd(body as never);
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
next();
|
|
106
|
-
});
|
|
107
|
-
},
|
|
108
|
-
ttl,
|
|
109
|
-
{ swr, tags }
|
|
110
|
-
);
|
|
111
|
-
|
|
112
|
-
// Status gate: error responses must never be cached. get() has already
|
|
113
|
-
// stored whatever the handler produced — evict it immediately so the next
|
|
114
|
-
// request re-runs the handler instead of replaying a transient 4xx/5xx
|
|
115
|
-
// for the whole TTL window.
|
|
116
|
-
const respStatus = (cached as { status?: number }).status;
|
|
117
|
-
if (typeof respStatus === 'number' && (respStatus < 200 || respStatus >= 300)) {
|
|
118
|
-
await activeCache.delete(key).catch(() => {});
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
if (!res.headersSent) {
|
|
123
|
-
if (cached.etag) {
|
|
124
|
-
if (res.setHeader) res.setHeader('ETag', cached.etag);
|
|
125
|
-
if (ifNoneMatch === cached.etag) {
|
|
126
|
-
return res.status(304).end();
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
if (cached.contentType && res.setHeader) {
|
|
130
|
-
res.setHeader('Content-Type', cached.contentType);
|
|
131
|
-
}
|
|
132
|
-
if (typeof cached.body === 'object' && cached.body !== null && res.json) {
|
|
133
|
-
return res.json(cached.body);
|
|
134
|
-
} else if (res.send) {
|
|
135
|
-
return res.send(cached.body);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
} catch (err) {
|
|
139
|
-
next(err);
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** Hono / Web Standard middleware */
|
|
145
|
-
export function honoCache(options: HttpCacheOptions = {}) {
|
|
146
|
-
const { cache, keyGenerator, etag = true, ttl = 300, swr, tags } = options;
|
|
147
|
-
|
|
148
|
-
return async (c: any, next: any) => {
|
|
149
|
-
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
|
|
150
|
-
return await next();
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
let activeCache = cache;
|
|
154
|
-
if (!activeCache) {
|
|
155
|
-
const { CacheService } = await import('../cache-service.js');
|
|
156
|
-
activeCache = CacheService.create();
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
const key = keyGenerator ? keyGenerator(c.req) : `http:${c.req.method}:${c.req.url}`;
|
|
160
|
-
const ifNoneMatch = c.req.header ? c.req.header('if-none-match') : undefined;
|
|
161
|
-
|
|
162
|
-
const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string; status?: number }>(
|
|
163
|
-
key,
|
|
164
|
-
async () => {
|
|
165
|
-
await next();
|
|
166
|
-
const res = c.res;
|
|
167
|
-
const text = await res.clone().text();
|
|
168
|
-
const bodyEtag = etag ? generateETag(text) : undefined;
|
|
169
|
-
return {
|
|
170
|
-
body: text,
|
|
171
|
-
contentType: res.headers.get('content-type') ?? 'text/plain',
|
|
172
|
-
etag: bodyEtag,
|
|
173
|
-
status: typeof (res as { status?: unknown }).status === 'number'
|
|
174
|
-
? (res as { status: number }).status
|
|
175
|
-
: undefined,
|
|
176
|
-
};
|
|
177
|
-
},
|
|
178
|
-
ttl,
|
|
179
|
-
{ swr, tags }
|
|
180
|
-
);
|
|
181
|
-
|
|
182
|
-
// Status gate: never replay a transient 4xx/5xx from cache — evict and let
|
|
183
|
-
// the (already-dispatched) live response stand for this request.
|
|
184
|
-
if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
|
|
185
|
-
await activeCache.delete(key).catch(() => {});
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
if (cached.etag && ifNoneMatch === cached.etag) {
|
|
190
|
-
return c.body(null, 304, { ETag: cached.etag });
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
const headers: Record<string, string> = {};
|
|
194
|
-
if (cached.etag) headers['ETag'] = cached.etag;
|
|
195
|
-
if (cached.contentType) headers['Content-Type'] = cached.contentType;
|
|
196
|
-
|
|
197
|
-
return c.body(cached.body, 200, headers);
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/** Fastify preHandler hook */
|
|
202
|
-
export function fastifyCache(options: HttpCacheOptions = {}) {
|
|
203
|
-
const { cache, keyGenerator, etag = true, ttl = 300, tags } = options;
|
|
204
|
-
|
|
205
|
-
return async (req: any, reply: any) => {
|
|
206
|
-
if (req.method !== 'GET' && req.method !== 'HEAD') return;
|
|
207
|
-
|
|
208
|
-
let activeCache = cache;
|
|
209
|
-
if (!activeCache) {
|
|
210
|
-
const { CacheService } = await import('../cache-service.js');
|
|
211
|
-
activeCache = CacheService.create();
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
const key = keyGenerator ? keyGenerator(req) : `http:${req.method}:${req.url}`;
|
|
215
|
-
const ifNoneMatch = req.headers ? req.headers['if-none-match'] : undefined;
|
|
216
|
-
|
|
217
|
-
// Fast-path: Check if already cached in L1 / Disk / Redis
|
|
218
|
-
const cached = await activeCache.get<{ body: unknown; contentType?: string; etag?: string } | null>(
|
|
219
|
-
key,
|
|
220
|
-
async () => null,
|
|
221
|
-
0
|
|
222
|
-
);
|
|
223
|
-
|
|
224
|
-
if (cached) {
|
|
225
|
-
if (cached.etag) {
|
|
226
|
-
if (reply.header) reply.header('ETag', cached.etag);
|
|
227
|
-
if (ifNoneMatch === cached.etag) {
|
|
228
|
-
if (reply.code) reply.code(304);
|
|
229
|
-
else if (reply.status) reply.status(304);
|
|
230
|
-
if (reply.send) return reply.send();
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
if (cached.contentType && reply.header) {
|
|
235
|
-
reply.header('Content-Type', cached.contentType);
|
|
236
|
-
}
|
|
237
|
-
if (reply.send) return reply.send(cached.body);
|
|
238
|
-
return;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
// Miss path: intercept reply.send on completion
|
|
242
|
-
const origSend = reply.send?.bind(reply);
|
|
243
|
-
if (origSend) {
|
|
244
|
-
reply.send = function (payload: any) {
|
|
245
|
-
if (payload !== undefined && payload !== null) {
|
|
246
|
-
const payloadEtag = etag ? generateETag(payload) : undefined;
|
|
247
|
-
const contentType = (reply.getHeader && reply.getHeader('content-type')) || (typeof payload === 'object' ? 'application/json' : 'text/plain');
|
|
248
|
-
// Status gate: only cache 2xx. A transient 4xx/5xx must not poison
|
|
249
|
-
// this key for the whole TTL window.
|
|
250
|
-
const respStatus = reply.statusCode ?? reply.raw?.statusCode;
|
|
251
|
-
if (respStatus === undefined || (respStatus >= 200 && respStatus < 300)) {
|
|
252
|
-
activeCache!.set(key, { body: payload, contentType, etag: payloadEtag }, ttl, undefined, { tags }).catch(() => {});
|
|
253
|
-
}
|
|
254
|
-
if (ifNoneMatch && ifNoneMatch === payloadEtag) {
|
|
255
|
-
if (reply.code) reply.code(304);
|
|
256
|
-
else if (reply.status) reply.status(304);
|
|
257
|
-
return origSend();
|
|
258
|
-
}
|
|
259
|
-
if (payloadEtag && reply.header) reply.header('ETag', payloadEtag);
|
|
260
|
-
}
|
|
261
|
-
return origSend(payload);
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
};
|
|
265
|
-
}
|
|
17
|
+
export {
|
|
18
|
+
buildDeterministicKey,
|
|
19
|
+
shouldSkipCache,
|
|
20
|
+
generateETag,
|
|
21
|
+
type KeyDerivationOptions,
|
|
22
|
+
} from './utils.js';
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
createExpressMiddleware,
|
|
26
|
+
expressCache,
|
|
27
|
+
type ExpressCacheOptions,
|
|
28
|
+
type ExpressCacheOptions as HttpCacheOptions,
|
|
29
|
+
type CachedHttpResponse,
|
|
30
|
+
} from './express.js';
|
|
31
|
+
|
|
32
|
+
export {
|
|
33
|
+
createFastifyPlugin,
|
|
34
|
+
fastifyCachePlugin,
|
|
35
|
+
fastifyCache,
|
|
36
|
+
type FastifyCacheOptions,
|
|
37
|
+
type CachedFastifyResponse,
|
|
38
|
+
} from './fastify.js';
|
|
39
|
+
|
|
40
|
+
export {
|
|
41
|
+
honoEdgeCache as honoCache,
|
|
42
|
+
computeEdgeETag,
|
|
43
|
+
buildEdgeDeterministicKey,
|
|
44
|
+
type HonoEdgeCacheOptions,
|
|
45
|
+
type CachedEdgeHttpResponse,
|
|
46
|
+
} from '../edge/hono.js';
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
|
|
3
|
+
export interface KeyDerivationOptions {
|
|
4
|
+
/** Custom key derivation function. Overrides default URL and query string serialization. */
|
|
5
|
+
keyGenerator?: (req: any) => string;
|
|
6
|
+
/** Optional list of header names (case-insensitive) to include in the cache key. */
|
|
7
|
+
headerWhitelist?: string[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Generates a deterministic HTTP cache key from request method, URL path, sorted query parameters,
|
|
12
|
+
* and optional whitelisted headers.
|
|
13
|
+
*
|
|
14
|
+
* Example:
|
|
15
|
+
* GET /api/products?sort=desc&page=2
|
|
16
|
+
* GET /api/products?page=2&sort=desc
|
|
17
|
+
* Both map to: http:GET:/api/products?page=2&sort=desc
|
|
18
|
+
*/
|
|
19
|
+
export function buildDeterministicKey(req: any, options?: KeyDerivationOptions): string {
|
|
20
|
+
if (options?.keyGenerator) {
|
|
21
|
+
return options.keyGenerator(req);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
25
|
+
const rawUrl = req.originalUrl || req.url || '/';
|
|
26
|
+
|
|
27
|
+
const qIdx = rawUrl.indexOf('?');
|
|
28
|
+
const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
|
|
29
|
+
let queryString = '';
|
|
30
|
+
|
|
31
|
+
if (qIdx >= 0) {
|
|
32
|
+
const rawQuery = rawUrl.slice(qIdx + 1);
|
|
33
|
+
try {
|
|
34
|
+
const params = new URLSearchParams(rawQuery);
|
|
35
|
+
params.sort();
|
|
36
|
+
queryString = params.toString();
|
|
37
|
+
} catch {
|
|
38
|
+
queryString = rawQuery;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let key = `http:${method}:${path}`;
|
|
43
|
+
if (queryString) {
|
|
44
|
+
key += `?${queryString}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
|
|
48
|
+
const sortedHeaders = [...options.headerWhitelist].sort();
|
|
49
|
+
for (const h of sortedHeaders) {
|
|
50
|
+
const normalizedHeader = h.toLowerCase();
|
|
51
|
+
const val = req.headers[normalizedHeader];
|
|
52
|
+
if (val !== undefined && val !== null && val !== '') {
|
|
53
|
+
const headerStr = Array.isArray(val) ? val.join(',') : String(val);
|
|
54
|
+
key += `|h:${normalizedHeader}=${headerStr}`;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return key;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Checks if request specifies Cache-Control bypass directives (no-cache, no-store)
|
|
64
|
+
* or matches a custom skipCache predicate.
|
|
65
|
+
*/
|
|
66
|
+
export function shouldSkipCache(req: any, customSkip?: (req: any) => boolean): boolean {
|
|
67
|
+
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
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Compute a weak ETag (W/"...") from string, Buffer, or JSON-serializable object.
|
|
82
|
+
*/
|
|
83
|
+
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}"`;
|
|
92
|
+
}
|