tricache 0.7.1 → 0.9.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 +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -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 +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- 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 +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- 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-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -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 +284 -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/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -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 +315 -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,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache/hono — first-class Node.js Hono middleware on CacheService.
|
|
3
|
+
*
|
|
4
|
+
* This is the Node three-tier path (L1 RAM → L1.5 disk → L2 Redis), not the
|
|
5
|
+
* Web-Crypto edge helper exported from `tricache/edge` / `tricache/http`.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* import { Hono } from 'hono';
|
|
9
|
+
* import { cacheMiddleware } from 'tricache/hono';
|
|
10
|
+
*
|
|
11
|
+
* const app = new Hono();
|
|
12
|
+
* app.get('/api/posts', cacheMiddleware({ ttl: 300, tags: ['posts'] }), (c) => {
|
|
13
|
+
* return c.json({ data: '...' });
|
|
14
|
+
* });
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { CacheService } from '../cache-service.js';
|
|
18
|
+
import type { WrapOptions } from '../types.js';
|
|
19
|
+
import {
|
|
20
|
+
buildDeterministicKey,
|
|
21
|
+
generateETag,
|
|
22
|
+
shouldSkipCache,
|
|
23
|
+
type KeyDerivationOptions,
|
|
24
|
+
} from '../http/utils.js';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Minimal Hono context surface used by the middleware.
|
|
28
|
+
* Compatible with `import('hono').Context` without taking a runtime dependency.
|
|
29
|
+
*/
|
|
30
|
+
export interface HonoCacheContext {
|
|
31
|
+
req: {
|
|
32
|
+
method: string;
|
|
33
|
+
url: string;
|
|
34
|
+
header?: (name: string) => string | undefined;
|
|
35
|
+
headers?: Headers | Record<string, string | string[] | undefined>;
|
|
36
|
+
};
|
|
37
|
+
res?: {
|
|
38
|
+
status?: number;
|
|
39
|
+
headers?: { get(name: string): string | null | undefined };
|
|
40
|
+
clone?: () => { text: () => Promise<string> };
|
|
41
|
+
body?: unknown;
|
|
42
|
+
};
|
|
43
|
+
body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
|
|
44
|
+
executionCtx?: unknown;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type HonoNext = () => Promise<void>;
|
|
48
|
+
export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
|
|
49
|
+
|
|
50
|
+
export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
|
|
51
|
+
/** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
|
|
52
|
+
cache?: CacheService;
|
|
53
|
+
/** Whether to generate and evaluate weak ETags. Default: true. */
|
|
54
|
+
etag?: boolean;
|
|
55
|
+
/** Custom cache key. Overrides default method + URL + sorted query derivation. */
|
|
56
|
+
keyGenerator?: (c: HonoCacheContext) => string;
|
|
57
|
+
/** Custom predicate to skip caching dynamically (e.g. authenticated sessions). */
|
|
58
|
+
skipCache?: (c: HonoCacheContext) => boolean;
|
|
59
|
+
/** Dynamic tags derivation from the Hono context. */
|
|
60
|
+
tags?: string[] | ((c: HonoCacheContext) => string[]);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface CachedHonoResponse {
|
|
64
|
+
body: string;
|
|
65
|
+
contentType?: string;
|
|
66
|
+
headers?: Record<string, string>;
|
|
67
|
+
etag?: string;
|
|
68
|
+
status: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function readRequestHeader(c: HonoCacheContext, name: string): string | undefined {
|
|
72
|
+
const headerFn = c.req.header;
|
|
73
|
+
if (typeof headerFn === 'function') {
|
|
74
|
+
const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
|
|
75
|
+
if (viaFn !== undefined && viaFn !== null && viaFn !== '') {
|
|
76
|
+
return viaFn;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const raw = c.req.headers;
|
|
81
|
+
if (!raw) return undefined;
|
|
82
|
+
|
|
83
|
+
if (typeof (raw as Headers).get === 'function') {
|
|
84
|
+
const viaGet = (raw as Headers).get(name);
|
|
85
|
+
if (viaGet) return viaGet;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const record = raw as Record<string, string | string[] | undefined>;
|
|
89
|
+
const val = record[name.toLowerCase()] ?? record[name];
|
|
90
|
+
if (val === undefined || val === null || val === '') return undefined;
|
|
91
|
+
return Array.isArray(val) ? val.join(',') : String(val);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function toRequestLike(c: HonoCacheContext, headerWhitelist?: string[]) {
|
|
95
|
+
const headers: Record<string, string | undefined> = {};
|
|
96
|
+
const cacheControl = readRequestHeader(c, 'cache-control');
|
|
97
|
+
const ifNoneMatch = readRequestHeader(c, 'if-none-match');
|
|
98
|
+
|
|
99
|
+
if (cacheControl) {
|
|
100
|
+
headers['cache-control'] = cacheControl;
|
|
101
|
+
headers['Cache-Control'] = cacheControl;
|
|
102
|
+
}
|
|
103
|
+
if (ifNoneMatch) {
|
|
104
|
+
headers['if-none-match'] = ifNoneMatch;
|
|
105
|
+
headers['If-None-Match'] = ifNoneMatch;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (headerWhitelist) {
|
|
109
|
+
for (const h of headerWhitelist) {
|
|
110
|
+
headers[h.toLowerCase()] = readRequestHeader(c, h);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
method: (c.req.method || 'GET').toUpperCase(),
|
|
116
|
+
url: c.req.url || '/',
|
|
117
|
+
headers,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isCacheableStatus(status: number): boolean {
|
|
122
|
+
// Only standard successful full responses (never 206 Partial Content or non-2xx)
|
|
123
|
+
return status >= 200 && status < 300 && status !== 206;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function hasNoStoreDirective(cacheControl: string | null | undefined): boolean {
|
|
127
|
+
if (!cacheControl) return false;
|
|
128
|
+
const lower = cacheControl.toLowerCase();
|
|
129
|
+
return lower.includes('no-store') || lower.includes('no-cache') || lower.includes('private');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function applyHonoCachedResponse(
|
|
133
|
+
c: HonoCacheContext,
|
|
134
|
+
cached: CachedHonoResponse,
|
|
135
|
+
ifNoneMatch: string | undefined,
|
|
136
|
+
): unknown {
|
|
137
|
+
if (cached.etag && ifNoneMatch === cached.etag) {
|
|
138
|
+
const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
|
|
139
|
+
if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
|
|
140
|
+
if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
|
|
141
|
+
const result = c.body(null, 304, notModifiedHeaders);
|
|
142
|
+
if (result != null) {
|
|
143
|
+
c.res = result as HonoCacheContext['res'];
|
|
144
|
+
}
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const headers: Record<string, string> = { ...cached.headers };
|
|
149
|
+
if (cached.etag) headers['ETag'] = cached.etag;
|
|
150
|
+
if (cached.contentType) headers['Content-Type'] = cached.contentType;
|
|
151
|
+
|
|
152
|
+
const result = c.body(cached.body, cached.status ?? 200, headers);
|
|
153
|
+
if (result != null) {
|
|
154
|
+
c.res = result as HonoCacheContext['res'];
|
|
155
|
+
}
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function snapshotHonoResponse(
|
|
160
|
+
c: HonoCacheContext,
|
|
161
|
+
etag: boolean,
|
|
162
|
+
): Promise<CachedHonoResponse> {
|
|
163
|
+
const res = c.res;
|
|
164
|
+
if (!res) {
|
|
165
|
+
return { body: '', status: 0 };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const contentType = res.headers?.get?.('content-type') || 'text/plain; charset=utf-8';
|
|
169
|
+
if (contentType.toLowerCase().includes('text/event-stream')) {
|
|
170
|
+
// Never buffer or cache Server-Sent Events / infinite streams
|
|
171
|
+
return { body: '', contentType, status: 0 };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const cacheControl = res.headers?.get?.('cache-control');
|
|
175
|
+
if (hasNoStoreDirective(cacheControl)) {
|
|
176
|
+
// Response explicitly forbids caching / shared caching
|
|
177
|
+
return { body: '', contentType, status: 0 };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const status = res.status ?? 200;
|
|
181
|
+
if (!isCacheableStatus(status)) {
|
|
182
|
+
return { body: '', contentType, status };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const clone = typeof res.clone === 'function' ? res.clone() : undefined;
|
|
186
|
+
const text = clone && typeof clone.text === 'function'
|
|
187
|
+
? await clone.text()
|
|
188
|
+
: typeof res.body === 'string'
|
|
189
|
+
? res.body
|
|
190
|
+
: '';
|
|
191
|
+
|
|
192
|
+
const bodyEtag = etag ? generateETag(text) : undefined;
|
|
193
|
+
|
|
194
|
+
const capturedHeaders: Record<string, string> = {};
|
|
195
|
+
if (res.headers && typeof (res.headers as any).forEach === 'function') {
|
|
196
|
+
(res.headers as any).forEach((value: string, name: string) => {
|
|
197
|
+
const lower = name.toLowerCase();
|
|
198
|
+
if (
|
|
199
|
+
lower !== 'content-length' &&
|
|
200
|
+
lower !== 'transfer-encoding' &&
|
|
201
|
+
lower !== 'connection' &&
|
|
202
|
+
lower !== 'etag' &&
|
|
203
|
+
lower !== 'content-type'
|
|
204
|
+
) {
|
|
205
|
+
capturedHeaders[name] = value;
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
body: text,
|
|
212
|
+
contentType,
|
|
213
|
+
headers: capturedHeaders,
|
|
214
|
+
etag: bodyEtag,
|
|
215
|
+
status,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
class NonCacheableHonoResponseError extends Error {
|
|
220
|
+
readonly isNonCacheable = true;
|
|
221
|
+
constructor(readonly response: CachedHonoResponse) {
|
|
222
|
+
super(`Non-cacheable response: status=${response.status}`);
|
|
223
|
+
this.name = 'NonCacheableHonoResponseError';
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Creates a Hono middleware that caches GET/HEAD responses through Node
|
|
229
|
+
* `CacheService`, with Express-aligned ttl/tags/SWR options, weak ETags, and
|
|
230
|
+
* RFC 7232 `If-None-Match` → `304 Not Modified`. Non-2xx, 206 Partial Content,
|
|
231
|
+
* private/no-store, and streaming SSE responses are never kept.
|
|
232
|
+
*
|
|
233
|
+
* @example
|
|
234
|
+
* import { Hono } from 'hono';
|
|
235
|
+
* import { CacheService } from 'tricache';
|
|
236
|
+
* import { cacheMiddleware } from 'tricache/hono';
|
|
237
|
+
*
|
|
238
|
+
* const app = new Hono();
|
|
239
|
+
* const cache = CacheService.create();
|
|
240
|
+
*
|
|
241
|
+
* app.get(
|
|
242
|
+
* '/api/posts',
|
|
243
|
+
* cacheMiddleware({ cache, ttl: 300, tags: ['posts'] }),
|
|
244
|
+
* (c) => c.json({ data: '...' }),
|
|
245
|
+
* );
|
|
246
|
+
*/
|
|
247
|
+
export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware {
|
|
248
|
+
const {
|
|
249
|
+
cache,
|
|
250
|
+
etag = true,
|
|
251
|
+
ttl = 300,
|
|
252
|
+
swr,
|
|
253
|
+
tags,
|
|
254
|
+
skipCache,
|
|
255
|
+
keyGenerator,
|
|
256
|
+
headerWhitelist,
|
|
257
|
+
} = options;
|
|
258
|
+
|
|
259
|
+
let resolvedCache = cache;
|
|
260
|
+
|
|
261
|
+
return async (c, next) => {
|
|
262
|
+
const method = (c.req.method || 'GET').toUpperCase();
|
|
263
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
264
|
+
return await next();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const reqLike = toRequestLike(c, headerWhitelist);
|
|
268
|
+
if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined)) {
|
|
269
|
+
return await next();
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (!resolvedCache) {
|
|
273
|
+
const { CacheService } = await import('../cache-service.js');
|
|
274
|
+
resolvedCache = CacheService.create();
|
|
275
|
+
}
|
|
276
|
+
const activeCache = resolvedCache;
|
|
277
|
+
|
|
278
|
+
const key = keyGenerator
|
|
279
|
+
? keyGenerator(c)
|
|
280
|
+
: buildDeterministicKey(reqLike, { headerWhitelist });
|
|
281
|
+
|
|
282
|
+
const ifNoneMatch = readRequestHeader(c, 'if-none-match');
|
|
283
|
+
const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
|
|
284
|
+
|
|
285
|
+
let ranNext = false;
|
|
286
|
+
try {
|
|
287
|
+
const cached = await activeCache.get<CachedHonoResponse>(
|
|
288
|
+
key,
|
|
289
|
+
async () => {
|
|
290
|
+
ranNext = true;
|
|
291
|
+
await next();
|
|
292
|
+
const snapshot = await snapshotHonoResponse(c, etag);
|
|
293
|
+
if (!isCacheableStatus(snapshot.status)) {
|
|
294
|
+
throw new NonCacheableHonoResponseError(snapshot);
|
|
295
|
+
}
|
|
296
|
+
return snapshot;
|
|
297
|
+
},
|
|
298
|
+
ttl,
|
|
299
|
+
{ swr, tags: resolvedTags },
|
|
300
|
+
);
|
|
301
|
+
|
|
302
|
+
return applyHonoCachedResponse(c, cached, ifNoneMatch);
|
|
303
|
+
} catch (err: unknown) {
|
|
304
|
+
if (err instanceof NonCacheableHonoResponseError) {
|
|
305
|
+
if (!ranNext) {
|
|
306
|
+
return await next();
|
|
307
|
+
}
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
throw err;
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Alias matching `createExpressMiddleware` / `createKoaMiddleware` naming. */
|
|
316
|
+
export const createHonoMiddleware = cacheMiddleware;
|
|
@@ -0,0 +1,195 @@
|
|
|
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 ExpressCacheOptions 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 (e.g. authenticated sessions). */
|
|
16
|
+
skipCache?: (req: any) => boolean;
|
|
17
|
+
/** Dynamic tags derivation from request. */
|
|
18
|
+
tags?: string[] | ((req: any) => string[]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CachedHttpResponse {
|
|
22
|
+
body: unknown;
|
|
23
|
+
contentType?: string;
|
|
24
|
+
etag?: string;
|
|
25
|
+
status: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Creates an Express / Connect middleware that provides deterministic response caching,
|
|
30
|
+
* weak ETag generation, conditional 304 Not Modified short-circuiting, and Cache-Control bypass controls.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* import express from 'express';
|
|
34
|
+
* import { CacheService } from 'tricache';
|
|
35
|
+
* import { createExpressMiddleware } from 'tricache/http';
|
|
36
|
+
*
|
|
37
|
+
* const app = express();
|
|
38
|
+
* const cache = CacheService.create();
|
|
39
|
+
*
|
|
40
|
+
* app.get(
|
|
41
|
+
* '/api/products',
|
|
42
|
+
* createExpressMiddleware({
|
|
43
|
+
* cache,
|
|
44
|
+
* ttl: 120,
|
|
45
|
+
* tags: ['products'],
|
|
46
|
+
* headerWhitelist: ['accept-language'],
|
|
47
|
+
* }),
|
|
48
|
+
* async (req, res) => {
|
|
49
|
+
* const data = await getProducts();
|
|
50
|
+
* res.json(data);
|
|
51
|
+
* }
|
|
52
|
+
* );
|
|
53
|
+
*/
|
|
54
|
+
export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
55
|
+
const {
|
|
56
|
+
cache,
|
|
57
|
+
etag = true,
|
|
58
|
+
ttl = 300,
|
|
59
|
+
swr,
|
|
60
|
+
tags,
|
|
61
|
+
skipCache,
|
|
62
|
+
keyGenerator,
|
|
63
|
+
headerWhitelist,
|
|
64
|
+
} = options;
|
|
65
|
+
|
|
66
|
+
return async (req: any, res: any, next: any) => {
|
|
67
|
+
// Only cache safe, idempotent HTTP read methods
|
|
68
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
69
|
+
return next();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (shouldSkipCache(req, skipCache)) {
|
|
73
|
+
return next();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let activeCache = cache;
|
|
77
|
+
if (!activeCache) {
|
|
78
|
+
const { CacheService } = await import('../cache-service.js');
|
|
79
|
+
activeCache = CacheService.create();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const key = buildDeterministicKey(req, { keyGenerator, headerWhitelist });
|
|
83
|
+
const ifNoneMatch = req.headers ? (req.headers['if-none-match'] || req.headers['If-None-Match']) : undefined;
|
|
84
|
+
|
|
85
|
+
const resolvedTags = typeof tags === 'function' ? tags(req) : tags;
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
const cached = await activeCache.get<CachedHttpResponse>(
|
|
89
|
+
key,
|
|
90
|
+
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);
|
|
95
|
+
|
|
96
|
+
const getStatusCode = () => (res.statusCode ?? 200);
|
|
97
|
+
|
|
98
|
+
if (origJson) {
|
|
99
|
+
res.json = (body: any) => {
|
|
100
|
+
const status = getStatusCode();
|
|
101
|
+
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
102
|
+
const contentType = res.getHeader?.('content-type') || 'application/json; charset=utf-8';
|
|
103
|
+
|
|
104
|
+
resolve({ body, contentType, etag: bodyEtag, status });
|
|
105
|
+
|
|
106
|
+
if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
107
|
+
res.status?.(304);
|
|
108
|
+
origEnd?.();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (bodyEtag && res.setHeader) {
|
|
113
|
+
res.setHeader('ETag', bodyEtag);
|
|
114
|
+
}
|
|
115
|
+
return origJson(body);
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (origSend) {
|
|
120
|
+
res.send = (body: any) => {
|
|
121
|
+
const status = getStatusCode();
|
|
122
|
+
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
123
|
+
const contentType = res.getHeader?.('content-type') as string | undefined;
|
|
124
|
+
|
|
125
|
+
resolve({ body, contentType, etag: bodyEtag, status });
|
|
126
|
+
|
|
127
|
+
if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
128
|
+
res.status?.(304);
|
|
129
|
+
origEnd?.();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (bodyEtag && res.setHeader) {
|
|
134
|
+
res.setHeader('ETag', bodyEtag);
|
|
135
|
+
}
|
|
136
|
+
return origSend(body);
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (origEnd) {
|
|
141
|
+
res.end = (body?: unknown) => {
|
|
142
|
+
const status = getStatusCode();
|
|
143
|
+
const bodyEtag = etag && body != null ? generateETag(body) : undefined;
|
|
144
|
+
const contentType = res.getHeader?.('content-type') as string | undefined;
|
|
145
|
+
|
|
146
|
+
resolve({ body, contentType, etag: bodyEtag, status });
|
|
147
|
+
return origEnd(body as never);
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
next();
|
|
152
|
+
});
|
|
153
|
+
},
|
|
154
|
+
ttl,
|
|
155
|
+
{ swr, tags: resolvedTags }
|
|
156
|
+
);
|
|
157
|
+
|
|
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) {
|
|
165
|
+
if (cached.etag) {
|
|
166
|
+
if (res.setHeader) res.setHeader('ETag', cached.etag);
|
|
167
|
+
if (ifNoneMatch === cached.etag) {
|
|
168
|
+
return res.status(304).end();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (cached.contentType && res.setHeader) {
|
|
173
|
+
res.setHeader('Content-Type', cached.contentType);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (cached.status && res.status) {
|
|
177
|
+
res.status(cached.status);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (typeof cached.body === 'object' && cached.body !== null && res.json) {
|
|
181
|
+
return res.json(cached.body);
|
|
182
|
+
} else if (res.send) {
|
|
183
|
+
return res.send(cached.body);
|
|
184
|
+
} else if (res.end) {
|
|
185
|
+
return res.end(cached.body);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} catch (err) {
|
|
189
|
+
next(err);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Alias matching legacy nomenclature */
|
|
195
|
+
export const expressCache = createExpressMiddleware;
|