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,182 @@
|
|
|
1
|
+
import {
|
|
2
|
+
base64ToUint8Array,
|
|
3
|
+
uint8ArrayToBase64,
|
|
4
|
+
utf8ToUint8Array,
|
|
5
|
+
uint8ArrayToUtf8,
|
|
6
|
+
} from './utils/base64';
|
|
7
|
+
|
|
8
|
+
export type WebCryptoMode = 'aes-256-gcm' | 'aes-128-gcm';
|
|
9
|
+
|
|
10
|
+
const PREFIX_256 = 'enc:v1:';
|
|
11
|
+
const PREFIX_128 = 'a128:v1:';
|
|
12
|
+
const IV_LEN = 12;
|
|
13
|
+
const TAG_LEN = 16;
|
|
14
|
+
const HEADER_LEN = IV_LEN + TAG_LEN; // 28 bytes
|
|
15
|
+
|
|
16
|
+
export interface WebCryptoOptions {
|
|
17
|
+
keyBase64: string;
|
|
18
|
+
prevKeyBase64?: string;
|
|
19
|
+
mode?: WebCryptoMode;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Pure Web Crypto API implementation of TriCache AEAD encryption.
|
|
24
|
+
* Compatible with Cloudflare Workers, Fastly Compute, Vercel Edge, Deno, and modern browsers.
|
|
25
|
+
*
|
|
26
|
+
* Interoperates with Node.js `CacheEncryption` by reordering Web Crypto's trailing tag
|
|
27
|
+
* into TriCache's standard wire envelope:
|
|
28
|
+
* Envelope = IV[12] || Tag[16] || Ciphertext[N]
|
|
29
|
+
*/
|
|
30
|
+
export class WebCryptoEncryption {
|
|
31
|
+
readonly isEnabled: boolean;
|
|
32
|
+
private readonly mode: WebCryptoMode;
|
|
33
|
+
private keyPromise: Promise<CryptoKey> | null = null;
|
|
34
|
+
private prevKeyPromise: Promise<CryptoKey> | null = null;
|
|
35
|
+
|
|
36
|
+
constructor(options?: WebCryptoOptions) {
|
|
37
|
+
if (!options?.keyBase64) {
|
|
38
|
+
this.isEnabled = false;
|
|
39
|
+
this.mode = 'aes-256-gcm';
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
this.isEnabled = true;
|
|
44
|
+
this.mode = options.mode ?? 'aes-256-gcm';
|
|
45
|
+
|
|
46
|
+
const expectedBytes = this.mode === 'aes-256-gcm' ? 32 : 16;
|
|
47
|
+
const rawKey = base64ToUint8Array(options.keyBase64);
|
|
48
|
+
if (rawKey.length !== expectedBytes) {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`WebCryptoEncryption: key length mismatch for ${this.mode}. Expected ${expectedBytes} bytes, received ${rawKey.length} bytes.`,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
this.keyPromise = this._importKey(rawKey);
|
|
55
|
+
|
|
56
|
+
if (options.prevKeyBase64) {
|
|
57
|
+
const rawPrevKey = base64ToUint8Array(options.prevKeyBase64);
|
|
58
|
+
if (rawPrevKey.length === expectedBytes) {
|
|
59
|
+
this.prevKeyPromise = this._importKey(rawPrevKey);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private async _importKey(rawBytes: Uint8Array): Promise<CryptoKey> {
|
|
65
|
+
const cryptoSubtle = globalThis.crypto?.subtle;
|
|
66
|
+
if (!cryptoSubtle) {
|
|
67
|
+
throw new Error('WebCryptoEncryption: globalThis.crypto.subtle is not available in this environment.');
|
|
68
|
+
}
|
|
69
|
+
// Web Crypto requires raw ArrayBuffer
|
|
70
|
+
const keyBuf = rawBytes.buffer.slice(rawBytes.byteOffset, rawBytes.byteOffset + rawBytes.byteLength) as ArrayBuffer;
|
|
71
|
+
return cryptoSubtle.importKey(
|
|
72
|
+
'raw',
|
|
73
|
+
keyBuf,
|
|
74
|
+
{ name: 'AES-GCM' },
|
|
75
|
+
false,
|
|
76
|
+
['encrypt', 'decrypt'],
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Encrypts a plaintext string into a TriCache standard wire envelope.
|
|
82
|
+
* Format: `enc:v1:<base64(IV[12] | Tag[16] | Ciphertext)>`
|
|
83
|
+
*/
|
|
84
|
+
async encrypt(plaintext: string): Promise<string> {
|
|
85
|
+
if (!this.isEnabled || !this.keyPromise) return plaintext;
|
|
86
|
+
|
|
87
|
+
const cryptoObj = globalThis.crypto;
|
|
88
|
+
const key = await this.keyPromise;
|
|
89
|
+
const iv = cryptoObj.getRandomValues(new Uint8Array(IV_LEN));
|
|
90
|
+
const plaintextBytes = utf8ToUint8Array(plaintext);
|
|
91
|
+
|
|
92
|
+
// Web Crypto outputs: Ciphertext || Tag[16]
|
|
93
|
+
const encryptedBuf = await cryptoObj.subtle.encrypt(
|
|
94
|
+
{
|
|
95
|
+
name: 'AES-GCM',
|
|
96
|
+
iv: iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength) as ArrayBuffer,
|
|
97
|
+
tagLength: 128,
|
|
98
|
+
},
|
|
99
|
+
key,
|
|
100
|
+
plaintextBytes.buffer.slice(plaintextBytes.byteOffset, plaintextBytes.byteOffset + plaintextBytes.byteLength) as ArrayBuffer,
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
const encryptedBytes = new Uint8Array(encryptedBuf);
|
|
104
|
+
const ctLen = encryptedBytes.length - TAG_LEN;
|
|
105
|
+
const ciphertext = encryptedBytes.subarray(0, ctLen);
|
|
106
|
+
const tag = encryptedBytes.subarray(ctLen);
|
|
107
|
+
|
|
108
|
+
// Reorder to TriCache wire layout: IV[12] || Tag[16] || Ciphertext[N]
|
|
109
|
+
const envelope = new Uint8Array(HEADER_LEN + ctLen);
|
|
110
|
+
envelope.set(iv, 0);
|
|
111
|
+
envelope.set(tag, IV_LEN);
|
|
112
|
+
envelope.set(ciphertext, HEADER_LEN);
|
|
113
|
+
|
|
114
|
+
const prefix = this.mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
|
|
115
|
+
return prefix + uint8ArrayToBase64(envelope);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Decrypts a TriCache standard wire envelope into plaintext.
|
|
120
|
+
* Handles envelopes created by both WebCryptoEncryption and Node.js CacheEncryption.
|
|
121
|
+
*/
|
|
122
|
+
async decrypt(envelopeStr: string): Promise<string> {
|
|
123
|
+
if (!this.isEnabled || !this.keyPromise) return envelopeStr;
|
|
124
|
+
|
|
125
|
+
let base64Data: string;
|
|
126
|
+
if (envelopeStr.startsWith(PREFIX_256)) {
|
|
127
|
+
base64Data = envelopeStr.slice(PREFIX_256.length);
|
|
128
|
+
} else if (envelopeStr.startsWith(PREFIX_128)) {
|
|
129
|
+
base64Data = envelopeStr.slice(PREFIX_128.length);
|
|
130
|
+
} else {
|
|
131
|
+
// Unencrypted or unrecognized prefix
|
|
132
|
+
return envelopeStr;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const envelopeBytes = base64ToUint8Array(base64Data);
|
|
136
|
+
if (envelopeBytes.length < HEADER_LEN) {
|
|
137
|
+
throw new Error(`WebCryptoEncryption: malformed envelope, length ${envelopeBytes.length} < header ${HEADER_LEN}`);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
const activeKey = await this.keyPromise;
|
|
142
|
+
return await this._decryptWithKey(activeKey, envelopeBytes);
|
|
143
|
+
} catch (primaryErr) {
|
|
144
|
+
if (this.prevKeyPromise) {
|
|
145
|
+
try {
|
|
146
|
+
const prevKey = await this.prevKeyPromise;
|
|
147
|
+
return await this._decryptWithKey(prevKey, envelopeBytes);
|
|
148
|
+
} catch {
|
|
149
|
+
// Re-throw primary error on key rotation failure
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
throw primaryErr;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private async _decryptWithKey(key: CryptoKey, envelopeBytes: Uint8Array): Promise<string> {
|
|
157
|
+
const cryptoSubtle = globalThis.crypto.subtle;
|
|
158
|
+
const iv = envelopeBytes.subarray(0, IV_LEN);
|
|
159
|
+
const tag = envelopeBytes.subarray(IV_LEN, HEADER_LEN);
|
|
160
|
+
const ciphertext = envelopeBytes.subarray(HEADER_LEN);
|
|
161
|
+
|
|
162
|
+
// Web Crypto decrypt expects: Ciphertext || Tag[16]
|
|
163
|
+
const webCryptoInput = new Uint8Array(ciphertext.length + TAG_LEN);
|
|
164
|
+
webCryptoInput.set(ciphertext, 0);
|
|
165
|
+
webCryptoInput.set(tag, ciphertext.length);
|
|
166
|
+
|
|
167
|
+
const ivBuf = iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength) as ArrayBuffer;
|
|
168
|
+
const dataBuf = webCryptoInput.buffer.slice(webCryptoInput.byteOffset, webCryptoInput.byteOffset + webCryptoInput.byteLength) as ArrayBuffer;
|
|
169
|
+
|
|
170
|
+
const decryptedBuf = await cryptoSubtle.decrypt(
|
|
171
|
+
{
|
|
172
|
+
name: 'AES-GCM',
|
|
173
|
+
iv: ivBuf,
|
|
174
|
+
tagLength: 128,
|
|
175
|
+
},
|
|
176
|
+
key,
|
|
177
|
+
dataBuf,
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
return uint8ArrayToUtf8(new Uint8Array(decryptedBuf));
|
|
181
|
+
}
|
|
182
|
+
}
|
package/src/edge/hono.ts
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import type { EdgeCacheService } from './cache.js';
|
|
2
|
+
|
|
3
|
+
export interface HonoEdgeCacheOptions {
|
|
4
|
+
/** EdgeCacheService instance. If omitted, requires explicit cache passing. */
|
|
5
|
+
cache?: EdgeCacheService | any;
|
|
6
|
+
/** Custom key generator. Defaults to deterministic method + URL + sorted query string. */
|
|
7
|
+
keyGenerator?: (c: any) => string;
|
|
8
|
+
/** Optional list of header names to include in the cache key. */
|
|
9
|
+
headerWhitelist?: string[];
|
|
10
|
+
/** Whether to generate and evaluate weak ETags. Default: true. */
|
|
11
|
+
etag?: boolean;
|
|
12
|
+
/** TTL in seconds. Default: 300. */
|
|
13
|
+
ttl?: number;
|
|
14
|
+
/** Stale-While-Revalidate window in seconds. Default: undefined. */
|
|
15
|
+
swr?: number;
|
|
16
|
+
/** Cache tags for invalidation. */
|
|
17
|
+
tags?: string[] | ((c: any) => string[]);
|
|
18
|
+
/** Predicate to skip caching dynamically. */
|
|
19
|
+
skipCache?: (c: any) => boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface CachedEdgeHttpResponse {
|
|
23
|
+
body: string;
|
|
24
|
+
contentType: string;
|
|
25
|
+
headers?: Record<string, string>;
|
|
26
|
+
etag?: string;
|
|
27
|
+
status: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Computes a weak ETag using Web Crypto API (crypto.subtle) without importing Node.js modules.
|
|
32
|
+
*/
|
|
33
|
+
export async function computeEdgeETag(text: string): Promise<string> {
|
|
34
|
+
try {
|
|
35
|
+
if (typeof crypto !== 'undefined' && crypto.subtle) {
|
|
36
|
+
const encoder = new TextEncoder();
|
|
37
|
+
const data = encoder.encode(text);
|
|
38
|
+
const hashBuf = await crypto.subtle.digest('SHA-1', data);
|
|
39
|
+
const hashArr = Array.from(new Uint8Array(hashBuf));
|
|
40
|
+
const hashHex = hashArr.map((b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16);
|
|
41
|
+
return `W/"${text.length.toString(16)}-${hashHex}"`;
|
|
42
|
+
}
|
|
43
|
+
} catch {
|
|
44
|
+
// Fallback if subtle crypto is unavailable in test environment
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let h = 0;
|
|
48
|
+
for (let i = 0; i < text.length; i++) {
|
|
49
|
+
h = (Math.imul(31, h) + text.charCodeAt(i)) | 0;
|
|
50
|
+
}
|
|
51
|
+
return `W/"${text.length.toString(16)}-${Math.abs(h).toString(16)}"`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Generates a deterministic cache key from standard Web Request / Hono context.
|
|
56
|
+
*/
|
|
57
|
+
export function buildEdgeDeterministicKey(c: any, options?: { keyGenerator?: (c: any) => string; headerWhitelist?: string[] }): string {
|
|
58
|
+
if (options?.keyGenerator) {
|
|
59
|
+
return options.keyGenerator(c);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const req = c.req;
|
|
63
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
64
|
+
const rawUrl = req.url || '/';
|
|
65
|
+
|
|
66
|
+
const qIdx = rawUrl.indexOf('?');
|
|
67
|
+
const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
|
|
68
|
+
let queryString = '';
|
|
69
|
+
|
|
70
|
+
if (qIdx >= 0) {
|
|
71
|
+
const rawQuery = rawUrl.slice(qIdx + 1);
|
|
72
|
+
try {
|
|
73
|
+
const params = new URLSearchParams(rawQuery);
|
|
74
|
+
params.sort();
|
|
75
|
+
queryString = params.toString();
|
|
76
|
+
} catch {
|
|
77
|
+
queryString = rawQuery;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
let key = `edge:http:${method}:${path}`;
|
|
82
|
+
if (queryString) {
|
|
83
|
+
key += `?${queryString}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.header) {
|
|
87
|
+
const sortedHeaders = [...options.headerWhitelist].sort();
|
|
88
|
+
for (const h of sortedHeaders) {
|
|
89
|
+
const val = req.header(h);
|
|
90
|
+
if (val !== undefined && val !== null && val !== '') {
|
|
91
|
+
key += `|h:${h.toLowerCase()}=${val}`;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return key;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
class NonCacheableEdgeResponseError extends Error {
|
|
100
|
+
readonly isNonCacheable = true;
|
|
101
|
+
constructor(readonly response: CachedEdgeHttpResponse) {
|
|
102
|
+
super(`Non-cacheable status: ${response.status}`);
|
|
103
|
+
this.name = 'NonCacheableEdgeResponseError';
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Pure Web Standards Hono middleware for V8 Edge Isolates (Cloudflare Workers, Fastly, Vercel Edge).
|
|
109
|
+
*
|
|
110
|
+
* Operates strictly with Web Request/Response and Web Crypto APIs.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* import { Hono } from 'hono';
|
|
114
|
+
* import { EdgeCacheService, honoEdgeCache } from 'tricache/edge';
|
|
115
|
+
*
|
|
116
|
+
* const app = new Hono();
|
|
117
|
+
* const cache = new EdgeCacheService({ maxKeys: 10_000 });
|
|
118
|
+
*
|
|
119
|
+
* app.get('/api/feed', honoEdgeCache({ cache, ttl: 60 }), async (c) => {
|
|
120
|
+
* return c.json({ status: 'ok', timestamp: Date.now() });
|
|
121
|
+
* });
|
|
122
|
+
*/
|
|
123
|
+
export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
|
|
124
|
+
const {
|
|
125
|
+
cache,
|
|
126
|
+
etag = true,
|
|
127
|
+
ttl = 300,
|
|
128
|
+
swr,
|
|
129
|
+
tags,
|
|
130
|
+
skipCache,
|
|
131
|
+
keyGenerator,
|
|
132
|
+
headerWhitelist,
|
|
133
|
+
} = options;
|
|
134
|
+
|
|
135
|
+
return async (c: any, next: () => Promise<void>) => {
|
|
136
|
+
const method = c.req.method;
|
|
137
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
138
|
+
return await next();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (skipCache && skipCache(c)) {
|
|
142
|
+
return await next();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const cc = c.req.header?.('cache-control') || c.req.header?.('Cache-Control');
|
|
146
|
+
if (typeof cc === 'string') {
|
|
147
|
+
const lower = cc.toLowerCase();
|
|
148
|
+
if (lower.includes('no-cache') || lower.includes('no-store')) {
|
|
149
|
+
return await next();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (!cache) {
|
|
154
|
+
// If no cache instance passed, proceed without caching
|
|
155
|
+
return await next();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
|
|
159
|
+
const ifNoneMatch = c.req.header?.('if-none-match') || c.req.header?.('If-None-Match');
|
|
160
|
+
const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
|
|
161
|
+
|
|
162
|
+
let ranNext = false;
|
|
163
|
+
try {
|
|
164
|
+
const cached = await cache.get(
|
|
165
|
+
key,
|
|
166
|
+
async () => {
|
|
167
|
+
ranNext = true;
|
|
168
|
+
await next();
|
|
169
|
+
const res = c.res;
|
|
170
|
+
if (!res) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const contentType = res.headers?.get?.('content-type') || 'text/plain; charset=utf-8';
|
|
175
|
+
if (contentType.toLowerCase().includes('text/event-stream')) {
|
|
176
|
+
throw new NonCacheableEdgeResponseError({
|
|
177
|
+
body: '',
|
|
178
|
+
contentType,
|
|
179
|
+
status: 0,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const cc = res.headers?.get?.('cache-control');
|
|
184
|
+
if (cc) {
|
|
185
|
+
const lowerCc = cc.toLowerCase();
|
|
186
|
+
if (lowerCc.includes('no-store') || lowerCc.includes('no-cache') || lowerCc.includes('private')) {
|
|
187
|
+
throw new NonCacheableEdgeResponseError({
|
|
188
|
+
body: '',
|
|
189
|
+
contentType,
|
|
190
|
+
status: 0,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const statusCode = res.status ?? 200;
|
|
196
|
+
if (statusCode < 200 || statusCode >= 300 || statusCode === 206) {
|
|
197
|
+
throw new NonCacheableEdgeResponseError({
|
|
198
|
+
body: '',
|
|
199
|
+
contentType,
|
|
200
|
+
status: statusCode,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const clone = res.clone();
|
|
205
|
+
const text = await clone.text();
|
|
206
|
+
const bodyEtag = etag ? await computeEdgeETag(text) : undefined;
|
|
207
|
+
|
|
208
|
+
const capturedHeaders: Record<string, string> = {};
|
|
209
|
+
if (res.headers && typeof res.headers.forEach === 'function') {
|
|
210
|
+
res.headers.forEach((value: string, name: string) => {
|
|
211
|
+
const lower = name.toLowerCase();
|
|
212
|
+
if (
|
|
213
|
+
lower !== 'content-length' &&
|
|
214
|
+
lower !== 'transfer-encoding' &&
|
|
215
|
+
lower !== 'connection' &&
|
|
216
|
+
lower !== 'etag' &&
|
|
217
|
+
lower !== 'content-type'
|
|
218
|
+
) {
|
|
219
|
+
capturedHeaders[name] = value;
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const snapshot: CachedEdgeHttpResponse = {
|
|
225
|
+
body: text,
|
|
226
|
+
contentType,
|
|
227
|
+
headers: capturedHeaders,
|
|
228
|
+
etag: bodyEtag,
|
|
229
|
+
status: statusCode,
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
return snapshot;
|
|
233
|
+
},
|
|
234
|
+
ttl,
|
|
235
|
+
{
|
|
236
|
+
swr,
|
|
237
|
+
tags: resolvedTags,
|
|
238
|
+
ctx: c.executionCtx,
|
|
239
|
+
}
|
|
240
|
+
);
|
|
241
|
+
|
|
242
|
+
if (!cached) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (cached.etag && ifNoneMatch === cached.etag) {
|
|
247
|
+
const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
|
|
248
|
+
if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
|
|
249
|
+
if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
|
|
250
|
+
return applyEdgeResponse(c, null, 304, notModifiedHeaders);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const headers: Record<string, string> = { ...cached.headers };
|
|
254
|
+
if (cached.etag) headers['ETag'] = cached.etag;
|
|
255
|
+
if (cached.contentType) headers['Content-Type'] = cached.contentType;
|
|
256
|
+
|
|
257
|
+
return applyEdgeResponse(c, cached.body, cached.status ?? 200, headers);
|
|
258
|
+
} catch (err: unknown) {
|
|
259
|
+
if (err instanceof NonCacheableEdgeResponseError) {
|
|
260
|
+
if (!ranNext) {
|
|
261
|
+
return await next();
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
throw err;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Hono's `compose` ignores a middleware return value once `next()` has set
|
|
272
|
+
* `c.res` (`finalized === true`). Assigning `c.res` replaces the downstream
|
|
273
|
+
* body so weak ETags and 304s are visible on both cache miss and hit.
|
|
274
|
+
*/
|
|
275
|
+
function applyEdgeResponse(
|
|
276
|
+
c: any,
|
|
277
|
+
body: string | null,
|
|
278
|
+
status: number,
|
|
279
|
+
headers: Record<string, string>,
|
|
280
|
+
): Response {
|
|
281
|
+
const response = c.body(body, status, headers);
|
|
282
|
+
c.res = response;
|
|
283
|
+
return response;
|
|
284
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export { EdgeCacheService } from './cache';
|
|
2
|
+
export { WebCryptoEncryption, type WebCryptoOptions, type WebCryptoMode } from './crypto';
|
|
3
|
+
export { UpstashRedisAdapter } from './adapters/upstash';
|
|
4
|
+
export { CloudflareKVAdapter } from './adapters/cloudflare-kv';
|
|
5
|
+
export { CloudflareDOStorageAdapter } from './adapters/cloudflare-do';
|
|
6
|
+
export {
|
|
7
|
+
uint8ArrayToBase64,
|
|
8
|
+
base64ToUint8Array,
|
|
9
|
+
utf8ToUint8Array,
|
|
10
|
+
uint8ArrayToUtf8,
|
|
11
|
+
} from './utils/base64';
|
|
12
|
+
export { WasmBloomFilter } from '../wasm/bloom-filter-wasm';
|
|
13
|
+
export { Murmur3BloomFilter, murmur3_32, type BloomFilterStats } from './utils/murmur3';
|
|
14
|
+
export type {
|
|
15
|
+
IEdgeRemoteStorage,
|
|
16
|
+
IEdgeBloomFilter,
|
|
17
|
+
EdgeCacheOptions,
|
|
18
|
+
EdgeGetOptions,
|
|
19
|
+
UpstashRedisOptions,
|
|
20
|
+
CloudflareKVNamespace,
|
|
21
|
+
CloudflareDOStorage,
|
|
22
|
+
CloudflareR2Bucket,
|
|
23
|
+
CloudflareR2Object,
|
|
24
|
+
EdgeSnapshotSource,
|
|
25
|
+
EdgeHydrateOptions,
|
|
26
|
+
EdgeExportSnapshotOptions,
|
|
27
|
+
EdgeSnapshotPayload,
|
|
28
|
+
} from './types';
|
|
29
|
+
|
|
30
|
+
export {
|
|
31
|
+
honoEdgeCache,
|
|
32
|
+
computeEdgeETag,
|
|
33
|
+
buildEdgeDeterministicKey,
|
|
34
|
+
type HonoEdgeCacheOptions,
|
|
35
|
+
type CachedEdgeHttpResponse,
|
|
36
|
+
} from './hono';
|
|
37
|
+
|