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,1109 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Murmur3BloomFilter,
|
|
3
|
+
murmur3_32
|
|
4
|
+
} from "../chunk-UGD4VEPD.js";
|
|
5
|
+
import {
|
|
6
|
+
WasmBloomFilter,
|
|
7
|
+
base64ToUint8Array,
|
|
8
|
+
uint8ArrayToBase64,
|
|
9
|
+
uint8ArrayToUtf8,
|
|
10
|
+
utf8ToUint8Array
|
|
11
|
+
} from "../chunk-XZL45ABR.js";
|
|
12
|
+
import {
|
|
13
|
+
buildEdgeDeterministicKey,
|
|
14
|
+
computeEdgeETag,
|
|
15
|
+
honoEdgeCache
|
|
16
|
+
} from "../chunk-IITRFWHY.js";
|
|
17
|
+
|
|
18
|
+
// src/edge/crypto.ts
|
|
19
|
+
var PREFIX_256 = "enc:v1:";
|
|
20
|
+
var PREFIX_128 = "a128:v1:";
|
|
21
|
+
var IV_LEN = 12;
|
|
22
|
+
var TAG_LEN = 16;
|
|
23
|
+
var HEADER_LEN = IV_LEN + TAG_LEN;
|
|
24
|
+
var WebCryptoEncryption = class {
|
|
25
|
+
isEnabled;
|
|
26
|
+
mode;
|
|
27
|
+
keyPromise = null;
|
|
28
|
+
prevKeyPromise = null;
|
|
29
|
+
constructor(options) {
|
|
30
|
+
if (!options?.keyBase64) {
|
|
31
|
+
this.isEnabled = false;
|
|
32
|
+
this.mode = "aes-256-gcm";
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
this.isEnabled = true;
|
|
36
|
+
this.mode = options.mode ?? "aes-256-gcm";
|
|
37
|
+
const expectedBytes = this.mode === "aes-256-gcm" ? 32 : 16;
|
|
38
|
+
const rawKey = base64ToUint8Array(options.keyBase64);
|
|
39
|
+
if (rawKey.length !== expectedBytes) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
`WebCryptoEncryption: key length mismatch for ${this.mode}. Expected ${expectedBytes} bytes, received ${rawKey.length} bytes.`
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
this.keyPromise = this._importKey(rawKey);
|
|
45
|
+
if (options.prevKeyBase64) {
|
|
46
|
+
const rawPrevKey = base64ToUint8Array(options.prevKeyBase64);
|
|
47
|
+
if (rawPrevKey.length === expectedBytes) {
|
|
48
|
+
this.prevKeyPromise = this._importKey(rawPrevKey);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async _importKey(rawBytes) {
|
|
53
|
+
const cryptoSubtle = globalThis.crypto?.subtle;
|
|
54
|
+
if (!cryptoSubtle) {
|
|
55
|
+
throw new Error("WebCryptoEncryption: globalThis.crypto.subtle is not available in this environment.");
|
|
56
|
+
}
|
|
57
|
+
const keyBuf = rawBytes.buffer.slice(rawBytes.byteOffset, rawBytes.byteOffset + rawBytes.byteLength);
|
|
58
|
+
return cryptoSubtle.importKey(
|
|
59
|
+
"raw",
|
|
60
|
+
keyBuf,
|
|
61
|
+
{ name: "AES-GCM" },
|
|
62
|
+
false,
|
|
63
|
+
["encrypt", "decrypt"]
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Encrypts a plaintext string into a TriCache standard wire envelope.
|
|
68
|
+
* Format: `enc:v1:<base64(IV[12] | Tag[16] | Ciphertext)>`
|
|
69
|
+
*/
|
|
70
|
+
async encrypt(plaintext) {
|
|
71
|
+
if (!this.isEnabled || !this.keyPromise) return plaintext;
|
|
72
|
+
const cryptoObj = globalThis.crypto;
|
|
73
|
+
const key = await this.keyPromise;
|
|
74
|
+
const iv = cryptoObj.getRandomValues(new Uint8Array(IV_LEN));
|
|
75
|
+
const plaintextBytes = utf8ToUint8Array(plaintext);
|
|
76
|
+
const encryptedBuf = await cryptoObj.subtle.encrypt(
|
|
77
|
+
{
|
|
78
|
+
name: "AES-GCM",
|
|
79
|
+
iv: iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength),
|
|
80
|
+
tagLength: 128
|
|
81
|
+
},
|
|
82
|
+
key,
|
|
83
|
+
plaintextBytes.buffer.slice(plaintextBytes.byteOffset, plaintextBytes.byteOffset + plaintextBytes.byteLength)
|
|
84
|
+
);
|
|
85
|
+
const encryptedBytes = new Uint8Array(encryptedBuf);
|
|
86
|
+
const ctLen = encryptedBytes.length - TAG_LEN;
|
|
87
|
+
const ciphertext = encryptedBytes.subarray(0, ctLen);
|
|
88
|
+
const tag = encryptedBytes.subarray(ctLen);
|
|
89
|
+
const envelope = new Uint8Array(HEADER_LEN + ctLen);
|
|
90
|
+
envelope.set(iv, 0);
|
|
91
|
+
envelope.set(tag, IV_LEN);
|
|
92
|
+
envelope.set(ciphertext, HEADER_LEN);
|
|
93
|
+
const prefix = this.mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
|
|
94
|
+
return prefix + uint8ArrayToBase64(envelope);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Decrypts a TriCache standard wire envelope into plaintext.
|
|
98
|
+
* Handles envelopes created by both WebCryptoEncryption and Node.js CacheEncryption.
|
|
99
|
+
*/
|
|
100
|
+
async decrypt(envelopeStr) {
|
|
101
|
+
if (!this.isEnabled || !this.keyPromise) return envelopeStr;
|
|
102
|
+
let base64Data;
|
|
103
|
+
if (envelopeStr.startsWith(PREFIX_256)) {
|
|
104
|
+
base64Data = envelopeStr.slice(PREFIX_256.length);
|
|
105
|
+
} else if (envelopeStr.startsWith(PREFIX_128)) {
|
|
106
|
+
base64Data = envelopeStr.slice(PREFIX_128.length);
|
|
107
|
+
} else {
|
|
108
|
+
return envelopeStr;
|
|
109
|
+
}
|
|
110
|
+
const envelopeBytes = base64ToUint8Array(base64Data);
|
|
111
|
+
if (envelopeBytes.length < HEADER_LEN) {
|
|
112
|
+
throw new Error(`WebCryptoEncryption: malformed envelope, length ${envelopeBytes.length} < header ${HEADER_LEN}`);
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
const activeKey = await this.keyPromise;
|
|
116
|
+
return await this._decryptWithKey(activeKey, envelopeBytes);
|
|
117
|
+
} catch (primaryErr) {
|
|
118
|
+
if (this.prevKeyPromise) {
|
|
119
|
+
try {
|
|
120
|
+
const prevKey = await this.prevKeyPromise;
|
|
121
|
+
return await this._decryptWithKey(prevKey, envelopeBytes);
|
|
122
|
+
} catch {
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
throw primaryErr;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async _decryptWithKey(key, envelopeBytes) {
|
|
129
|
+
const cryptoSubtle = globalThis.crypto.subtle;
|
|
130
|
+
const iv = envelopeBytes.subarray(0, IV_LEN);
|
|
131
|
+
const tag = envelopeBytes.subarray(IV_LEN, HEADER_LEN);
|
|
132
|
+
const ciphertext = envelopeBytes.subarray(HEADER_LEN);
|
|
133
|
+
const webCryptoInput = new Uint8Array(ciphertext.length + TAG_LEN);
|
|
134
|
+
webCryptoInput.set(ciphertext, 0);
|
|
135
|
+
webCryptoInput.set(tag, ciphertext.length);
|
|
136
|
+
const ivBuf = iv.buffer.slice(iv.byteOffset, iv.byteOffset + iv.byteLength);
|
|
137
|
+
const dataBuf = webCryptoInput.buffer.slice(webCryptoInput.byteOffset, webCryptoInput.byteOffset + webCryptoInput.byteLength);
|
|
138
|
+
const decryptedBuf = await cryptoSubtle.decrypt(
|
|
139
|
+
{
|
|
140
|
+
name: "AES-GCM",
|
|
141
|
+
iv: ivBuf,
|
|
142
|
+
tagLength: 128
|
|
143
|
+
},
|
|
144
|
+
key,
|
|
145
|
+
dataBuf
|
|
146
|
+
);
|
|
147
|
+
return uint8ArrayToUtf8(new Uint8Array(decryptedBuf));
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
// src/edge/cache.ts
|
|
152
|
+
var EdgeCacheService = class {
|
|
153
|
+
maxKeys;
|
|
154
|
+
maxBytes;
|
|
155
|
+
defaultTtl;
|
|
156
|
+
namespace;
|
|
157
|
+
remoteStorage;
|
|
158
|
+
enc;
|
|
159
|
+
tracer;
|
|
160
|
+
bloomFilter;
|
|
161
|
+
// L1 Dual-bounded LRU
|
|
162
|
+
l1 = /* @__PURE__ */ new Map();
|
|
163
|
+
currentBytes = 0;
|
|
164
|
+
// Single-flight in-flight stampede coalescing map
|
|
165
|
+
inflight = /* @__PURE__ */ new Map();
|
|
166
|
+
// Tag indexing for edge
|
|
167
|
+
tagIndex = /* @__PURE__ */ new Map();
|
|
168
|
+
// Tag version in-isolate cache with 800ms micro-TTL (prevents HTTP fetch amplification on L1 hits)
|
|
169
|
+
tagVersionCache = /* @__PURE__ */ new Map();
|
|
170
|
+
tagVersionTtlMs = 800;
|
|
171
|
+
constructor(options) {
|
|
172
|
+
this.maxKeys = options?.maxKeys ?? 1e4;
|
|
173
|
+
this.maxBytes = options?.maxBytes ?? 32 * 1024 * 1024;
|
|
174
|
+
this.defaultTtl = options?.defaultTtlSeconds ?? 300;
|
|
175
|
+
this.namespace = options?.namespace?.trim() ?? "";
|
|
176
|
+
this.remoteStorage = options?.remoteStorage ?? null;
|
|
177
|
+
this.tracer = options?.tracer ?? null;
|
|
178
|
+
this.enc = new WebCryptoEncryption(options?.encryption);
|
|
179
|
+
if (options?.bloomFilter === true) {
|
|
180
|
+
try {
|
|
181
|
+
this.bloomFilter = new WasmBloomFilter();
|
|
182
|
+
} catch {
|
|
183
|
+
this.bloomFilter = new Murmur3BloomFilter();
|
|
184
|
+
}
|
|
185
|
+
} else if (options?.bloomFilter) {
|
|
186
|
+
this.bloomFilter = options.bloomFilter;
|
|
187
|
+
} else {
|
|
188
|
+
this.bloomFilter = null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Active Bloom filter instance defending against cold miss penetration, or null.
|
|
193
|
+
*/
|
|
194
|
+
get bloom() {
|
|
195
|
+
return this.bloomFilter;
|
|
196
|
+
}
|
|
197
|
+
nk(key) {
|
|
198
|
+
return this.namespace ? `${this.namespace}:${key}` : key;
|
|
199
|
+
}
|
|
200
|
+
_estimateBytes(key, serialized) {
|
|
201
|
+
return (key.length + serialized.length) * 2 + 64;
|
|
202
|
+
}
|
|
203
|
+
_evictIfNeeded(newBytes) {
|
|
204
|
+
while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
|
|
205
|
+
const oldestKey = this.l1.keys().next().value;
|
|
206
|
+
if (oldestKey === void 0) break;
|
|
207
|
+
this._deleteL1(oldestKey);
|
|
208
|
+
}
|
|
209
|
+
while (this.l1.size >= this.maxKeys) {
|
|
210
|
+
const oldestKey = this.l1.keys().next().value;
|
|
211
|
+
if (oldestKey === void 0) break;
|
|
212
|
+
this._deleteL1(oldestKey);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
_deleteL1(k) {
|
|
216
|
+
const entry = this.l1.get(k);
|
|
217
|
+
if (entry) {
|
|
218
|
+
this.currentBytes = Math.max(0, this.currentBytes - entry.bytes);
|
|
219
|
+
this.l1.delete(k);
|
|
220
|
+
if (entry.tags) {
|
|
221
|
+
for (const tag of entry.tags) {
|
|
222
|
+
const s = this.tagIndex.get(tag);
|
|
223
|
+
if (s) {
|
|
224
|
+
s.delete(k);
|
|
225
|
+
if (s.size === 0) this.tagIndex.delete(tag);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
_startSpan(name) {
|
|
232
|
+
if (this.tracer) {
|
|
233
|
+
const span = this.tracer.startSpan(name);
|
|
234
|
+
if (this.namespace) span.setAttribute("cache.namespace", this.namespace);
|
|
235
|
+
return span;
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
setAttribute() {
|
|
239
|
+
return this;
|
|
240
|
+
},
|
|
241
|
+
setStatus() {
|
|
242
|
+
return this;
|
|
243
|
+
},
|
|
244
|
+
recordException() {
|
|
245
|
+
return this;
|
|
246
|
+
},
|
|
247
|
+
end() {
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
async _getTagVersion(tag) {
|
|
252
|
+
const cached = this.tagVersionCache.get(tag);
|
|
253
|
+
const now = Date.now();
|
|
254
|
+
if (cached && cached.expiresAt > now) {
|
|
255
|
+
return cached.version;
|
|
256
|
+
}
|
|
257
|
+
let version = 1;
|
|
258
|
+
if (this.remoteStorage) {
|
|
259
|
+
try {
|
|
260
|
+
if (typeof this.remoteStorage.getTagVersion === "function") {
|
|
261
|
+
version = await this.remoteStorage.getTagVersion(this.nk(tag));
|
|
262
|
+
} else {
|
|
263
|
+
const raw = await this.remoteStorage.get(this.nk(`tag_ver:${tag}`));
|
|
264
|
+
version = raw ? parseInt(raw, 10) || 1 : 1;
|
|
265
|
+
}
|
|
266
|
+
} catch {
|
|
267
|
+
version = cached?.version ?? 1;
|
|
268
|
+
}
|
|
269
|
+
} else {
|
|
270
|
+
version = cached?.version ?? 1;
|
|
271
|
+
}
|
|
272
|
+
this.tagVersionCache.set(tag, { version, expiresAt: now + this.tagVersionTtlMs });
|
|
273
|
+
return version;
|
|
274
|
+
}
|
|
275
|
+
async _batchGetTagVersions(tags) {
|
|
276
|
+
const now = Date.now();
|
|
277
|
+
const result = {};
|
|
278
|
+
const missingTags = [];
|
|
279
|
+
for (const t of tags) {
|
|
280
|
+
const c = this.tagVersionCache.get(t);
|
|
281
|
+
if (c && c.expiresAt > now) {
|
|
282
|
+
result[t] = c.version;
|
|
283
|
+
} else {
|
|
284
|
+
missingTags.push(t);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (missingTags.length > 0 && this.remoteStorage) {
|
|
288
|
+
try {
|
|
289
|
+
if (typeof this.remoteStorage.batchGetTagVersions === "function") {
|
|
290
|
+
const nsTags = missingTags.map((t) => this.nk(t));
|
|
291
|
+
const remoteVersions = await this.remoteStorage.batchGetTagVersions(nsTags);
|
|
292
|
+
for (let i = 0; i < missingTags.length; i++) {
|
|
293
|
+
const t = missingTags[i];
|
|
294
|
+
const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
|
|
295
|
+
result[t] = v;
|
|
296
|
+
this.tagVersionCache.set(t, { version: v, expiresAt: now + this.tagVersionTtlMs });
|
|
297
|
+
}
|
|
298
|
+
} else {
|
|
299
|
+
await Promise.all(missingTags.map(async (t) => {
|
|
300
|
+
const v = await this._getTagVersion(t);
|
|
301
|
+
result[t] = v;
|
|
302
|
+
}));
|
|
303
|
+
}
|
|
304
|
+
} catch {
|
|
305
|
+
for (const t of missingTags) {
|
|
306
|
+
result[t] = this.tagVersionCache.get(t)?.version ?? 1;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
} else {
|
|
310
|
+
for (const t of missingTags) {
|
|
311
|
+
result[t] = this.tagVersionCache.get(t)?.version ?? 1;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return result;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Reads or fetches a value by key.
|
|
318
|
+
*/
|
|
319
|
+
async get(key, fetchFn, ttlSeconds, options) {
|
|
320
|
+
const span = this._startSpan("tricache.get");
|
|
321
|
+
span.setAttribute("cache.key", key);
|
|
322
|
+
const nsKey = this.nk(key);
|
|
323
|
+
const now = Date.now();
|
|
324
|
+
const resolvedTtl = ttlSeconds ?? this.defaultTtl;
|
|
325
|
+
try {
|
|
326
|
+
const l1Entry = this.l1.get(nsKey);
|
|
327
|
+
if (l1Entry) {
|
|
328
|
+
let isTagStale = false;
|
|
329
|
+
if (l1Entry.tagVersions) {
|
|
330
|
+
const tagNames = Object.keys(l1Entry.tagVersions);
|
|
331
|
+
const currentVers = await this._batchGetTagVersions(tagNames);
|
|
332
|
+
for (const tag of tagNames) {
|
|
333
|
+
if (currentVers[tag] > l1Entry.tagVersions[tag]) {
|
|
334
|
+
isTagStale = true;
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (isTagStale) {
|
|
340
|
+
this._deleteL1(nsKey);
|
|
341
|
+
} else {
|
|
342
|
+
this.l1.delete(nsKey);
|
|
343
|
+
this.l1.set(nsKey, l1Entry);
|
|
344
|
+
if (l1Entry.expiresAt > now) {
|
|
345
|
+
span.setAttribute("cache.hit", true);
|
|
346
|
+
span.setAttribute("cache.item.tier", "memory");
|
|
347
|
+
span.setAttribute("cache.hit_tier", "l1");
|
|
348
|
+
return l1Entry.value;
|
|
349
|
+
}
|
|
350
|
+
if (l1Entry.staleUntil > now && fetchFn) {
|
|
351
|
+
span.setAttribute("cache.hit", true);
|
|
352
|
+
span.setAttribute("cache.item.tier", "memory");
|
|
353
|
+
span.setAttribute("cache.hit_tier", "l1");
|
|
354
|
+
span.setAttribute("cache.stale", true);
|
|
355
|
+
const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
|
|
356
|
+
if (options?.ctx?.waitUntil) {
|
|
357
|
+
options.ctx.waitUntil(revalPromise);
|
|
358
|
+
}
|
|
359
|
+
return l1Entry.value;
|
|
360
|
+
}
|
|
361
|
+
this._deleteL1(nsKey);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (this.remoteStorage) {
|
|
365
|
+
if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
|
|
366
|
+
span.setAttribute("cache.bloom.filtered", true);
|
|
367
|
+
} else {
|
|
368
|
+
try {
|
|
369
|
+
const rawRemote = await this.remoteStorage.get(nsKey);
|
|
370
|
+
if (rawRemote !== null) {
|
|
371
|
+
const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
|
|
372
|
+
const parsedJson = JSON.parse(plain);
|
|
373
|
+
let parsed;
|
|
374
|
+
let activeTagVersions;
|
|
375
|
+
let isStaleRemote = false;
|
|
376
|
+
if (parsedJson && typeof parsedJson === "object" && "__t_val" in parsedJson && "__t_tv" in parsedJson) {
|
|
377
|
+
parsed = parsedJson.__t_val;
|
|
378
|
+
activeTagVersions = parsedJson.__t_tv;
|
|
379
|
+
const tagNames = Object.keys(activeTagVersions);
|
|
380
|
+
const currentVers = await this._batchGetTagVersions(tagNames);
|
|
381
|
+
for (const tag of tagNames) {
|
|
382
|
+
if (currentVers[tag] > activeTagVersions[tag]) {
|
|
383
|
+
isStaleRemote = true;
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
} else {
|
|
388
|
+
parsed = parsedJson;
|
|
389
|
+
}
|
|
390
|
+
if (!isStaleRemote) {
|
|
391
|
+
await this.set(key, parsed, resolvedTtl, options);
|
|
392
|
+
span.setAttribute("cache.hit", true);
|
|
393
|
+
span.setAttribute("cache.item.tier", "remote");
|
|
394
|
+
span.setAttribute("cache.hit_tier", "l2");
|
|
395
|
+
return parsed;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
} catch (remoteErr) {
|
|
399
|
+
span.recordException?.(remoteErr);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (!fetchFn) {
|
|
404
|
+
span.setAttribute("cache.hit", false);
|
|
405
|
+
span.setAttribute("cache.hit_tier", "miss");
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
let inflightPromise = this.inflight.get(nsKey);
|
|
409
|
+
let coalesced = false;
|
|
410
|
+
if (inflightPromise) {
|
|
411
|
+
coalesced = true;
|
|
412
|
+
} else {
|
|
413
|
+
inflightPromise = (async () => {
|
|
414
|
+
try {
|
|
415
|
+
const fresh = await fetchFn();
|
|
416
|
+
await this.set(key, fresh, resolvedTtl, options);
|
|
417
|
+
return fresh;
|
|
418
|
+
} finally {
|
|
419
|
+
this.inflight.delete(nsKey);
|
|
420
|
+
}
|
|
421
|
+
})();
|
|
422
|
+
this.inflight.set(nsKey, inflightPromise);
|
|
423
|
+
}
|
|
424
|
+
span.setAttribute("cache.hit", coalesced);
|
|
425
|
+
span.setAttribute("cache.hit_tier", coalesced ? "l1" : "miss");
|
|
426
|
+
span.setAttribute("cache.stampede_coalesced", coalesced);
|
|
427
|
+
const result = await inflightPromise;
|
|
428
|
+
return result;
|
|
429
|
+
} catch (err) {
|
|
430
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
431
|
+
span.recordException?.(err);
|
|
432
|
+
throw err;
|
|
433
|
+
} finally {
|
|
434
|
+
span.end();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async _revalidate(key, fetchFn, ttl, options) {
|
|
438
|
+
const nsKey = this.nk(key);
|
|
439
|
+
if (this.inflight.has(nsKey)) return;
|
|
440
|
+
const task = (async () => {
|
|
441
|
+
try {
|
|
442
|
+
const fresh = await fetchFn();
|
|
443
|
+
await this.set(key, fresh, ttl, options);
|
|
444
|
+
} catch {
|
|
445
|
+
} finally {
|
|
446
|
+
this.inflight.delete(nsKey);
|
|
447
|
+
}
|
|
448
|
+
})();
|
|
449
|
+
this.inflight.set(nsKey, task);
|
|
450
|
+
await task;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Sets a value in the cache with an optional TTL and tags.
|
|
454
|
+
*/
|
|
455
|
+
async set(key, value, ttlSeconds, options) {
|
|
456
|
+
const span = this._startSpan("tricache.set");
|
|
457
|
+
span.setAttribute("cache.key", key);
|
|
458
|
+
const nsKey = this.nk(key);
|
|
459
|
+
const resolvedTtl = ttlSeconds ?? this.defaultTtl;
|
|
460
|
+
const now = Date.now();
|
|
461
|
+
const swrSeconds = options?.swr ?? 0;
|
|
462
|
+
try {
|
|
463
|
+
let activeTagVersions;
|
|
464
|
+
if (options?.tags?.length) {
|
|
465
|
+
activeTagVersions = await this._batchGetTagVersions(options.tags);
|
|
466
|
+
}
|
|
467
|
+
const serialized = JSON.stringify(value);
|
|
468
|
+
const bytes = this._estimateBytes(nsKey, serialized);
|
|
469
|
+
this._deleteL1(nsKey);
|
|
470
|
+
this._evictIfNeeded(bytes);
|
|
471
|
+
const entry = {
|
|
472
|
+
value,
|
|
473
|
+
serialized,
|
|
474
|
+
bytes,
|
|
475
|
+
expiresAt: now + resolvedTtl * 1e3,
|
|
476
|
+
staleUntil: now + (resolvedTtl + swrSeconds) * 1e3,
|
|
477
|
+
tags: options?.tags,
|
|
478
|
+
tagVersions: activeTagVersions
|
|
479
|
+
};
|
|
480
|
+
this.l1.set(nsKey, entry);
|
|
481
|
+
this.currentBytes += bytes;
|
|
482
|
+
if (options?.tags) {
|
|
483
|
+
for (const tag of options.tags) {
|
|
484
|
+
let s = this.tagIndex.get(tag);
|
|
485
|
+
if (!s) {
|
|
486
|
+
s = /* @__PURE__ */ new Set();
|
|
487
|
+
this.tagIndex.set(tag, s);
|
|
488
|
+
}
|
|
489
|
+
s.add(nsKey);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (this.remoteStorage) {
|
|
493
|
+
const toStoreRaw = activeTagVersions ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions }) : serialized;
|
|
494
|
+
const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
|
|
495
|
+
await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
|
|
496
|
+
}
|
|
497
|
+
if (this.bloomFilter) {
|
|
498
|
+
this.bloomFilter.add(nsKey);
|
|
499
|
+
}
|
|
500
|
+
} catch (err) {
|
|
501
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
502
|
+
span.recordException?.(err);
|
|
503
|
+
throw err;
|
|
504
|
+
} finally {
|
|
505
|
+
span.end();
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Deletes a key from all tiers.
|
|
510
|
+
*/
|
|
511
|
+
async delete(key) {
|
|
512
|
+
const span = this._startSpan("tricache.delete");
|
|
513
|
+
span.setAttribute("cache.key", key);
|
|
514
|
+
const nsKey = this.nk(key);
|
|
515
|
+
try {
|
|
516
|
+
this._deleteL1(nsKey);
|
|
517
|
+
if (this.remoteStorage) {
|
|
518
|
+
await this.remoteStorage.delete(nsKey);
|
|
519
|
+
}
|
|
520
|
+
} catch (err) {
|
|
521
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
522
|
+
span.recordException?.(err);
|
|
523
|
+
throw err;
|
|
524
|
+
} finally {
|
|
525
|
+
span.end();
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Invalidates all cached entries associated with a tag.
|
|
530
|
+
*/
|
|
531
|
+
async invalidateTag(tag) {
|
|
532
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
533
|
+
span.setAttribute("cache.tag", tag);
|
|
534
|
+
try {
|
|
535
|
+
let newVer = 1;
|
|
536
|
+
if (this.remoteStorage) {
|
|
537
|
+
try {
|
|
538
|
+
if (typeof this.remoteStorage.incrementTagVersion === "function") {
|
|
539
|
+
newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
|
|
540
|
+
} else {
|
|
541
|
+
const key = this.nk(`tag_ver:${tag}`);
|
|
542
|
+
const current = await this._getTagVersion(tag);
|
|
543
|
+
newVer = Math.max(current + 1, Date.now());
|
|
544
|
+
await this.remoteStorage.set(key, String(newVer));
|
|
545
|
+
}
|
|
546
|
+
} catch {
|
|
547
|
+
const current = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
548
|
+
newVer = current + 1;
|
|
549
|
+
}
|
|
550
|
+
} else {
|
|
551
|
+
const current = this.tagVersionCache.get(tag)?.version ?? 1;
|
|
552
|
+
newVer = current + 1;
|
|
553
|
+
}
|
|
554
|
+
this.tagVersionCache.set(tag, { version: newVer, expiresAt: Date.now() + 6e4 });
|
|
555
|
+
const keys = this.tagIndex.get(tag);
|
|
556
|
+
if (keys) {
|
|
557
|
+
const keysArr = Array.from(keys);
|
|
558
|
+
for (const k of keysArr) {
|
|
559
|
+
this._deleteL1(k);
|
|
560
|
+
}
|
|
561
|
+
this.tagIndex.delete(tag);
|
|
562
|
+
}
|
|
563
|
+
} catch (err) {
|
|
564
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
565
|
+
span.recordException?.(err);
|
|
566
|
+
throw err;
|
|
567
|
+
} finally {
|
|
568
|
+
span.end();
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Clears all entries from the edge cache.
|
|
573
|
+
*/
|
|
574
|
+
async clear() {
|
|
575
|
+
const span = this._startSpan("tricache.clear");
|
|
576
|
+
try {
|
|
577
|
+
this.l1.clear();
|
|
578
|
+
this.currentBytes = 0;
|
|
579
|
+
this.tagIndex.clear();
|
|
580
|
+
this.tagVersionCache.clear();
|
|
581
|
+
if (this.bloomFilter) {
|
|
582
|
+
this.bloomFilter.reset();
|
|
583
|
+
}
|
|
584
|
+
if (this.remoteStorage) {
|
|
585
|
+
await this.remoteStorage.clear?.(this.namespace || void 0);
|
|
586
|
+
}
|
|
587
|
+
} catch (err) {
|
|
588
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
589
|
+
span.recordException?.(err);
|
|
590
|
+
throw err;
|
|
591
|
+
} finally {
|
|
592
|
+
span.end();
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Batch get with miss-fetching.
|
|
597
|
+
*/
|
|
598
|
+
async mget(keys, fetchFn, ttlSeconds) {
|
|
599
|
+
const span = this._startSpan("tricache.mget");
|
|
600
|
+
span.setAttribute("cache.batch.size", keys.length);
|
|
601
|
+
try {
|
|
602
|
+
const results = Array.from({ length: keys.length }, () => null);
|
|
603
|
+
const missIndices = [];
|
|
604
|
+
const missKeys = [];
|
|
605
|
+
for (let i = 0; i < keys.length; i++) {
|
|
606
|
+
const val = await this.get(keys[i]);
|
|
607
|
+
if (val !== null) {
|
|
608
|
+
results[i] = val;
|
|
609
|
+
} else {
|
|
610
|
+
missIndices.push(i);
|
|
611
|
+
missKeys.push(keys[i]);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
span.setAttribute("cache.hits", keys.length - missKeys.length);
|
|
615
|
+
span.setAttribute("cache.misses", missKeys.length);
|
|
616
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
617
|
+
const fetchedMap = await fetchFn(missKeys);
|
|
618
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
619
|
+
const k = missKeys[j];
|
|
620
|
+
const fetchedVal = fetchedMap[k];
|
|
621
|
+
if (fetchedVal !== void 0) {
|
|
622
|
+
results[missIndices[j]] = fetchedVal;
|
|
623
|
+
await this.set(k, fetchedVal, ttlSeconds);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return results;
|
|
628
|
+
} catch (err) {
|
|
629
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
630
|
+
span.recordException?.(err);
|
|
631
|
+
throw err;
|
|
632
|
+
} finally {
|
|
633
|
+
span.end();
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Serializes active, unexpired L1 entries into a snapshot string (encrypted if WebCrypto encryption is enabled).
|
|
638
|
+
* Ideal for persisting Edge state to Cloudflare R2 before worker restart.
|
|
639
|
+
*/
|
|
640
|
+
async exportSnapshot(options) {
|
|
641
|
+
const now = Date.now();
|
|
642
|
+
const entries = [];
|
|
643
|
+
for (const [nsKey, entry] of this.l1.entries()) {
|
|
644
|
+
if (entry.expiresAt > now || entry.staleUntil > now) {
|
|
645
|
+
const cleanKey = this.namespace && nsKey.startsWith(this.namespace + ":") ? nsKey.slice(this.namespace.length + 1) : nsKey;
|
|
646
|
+
entries.push({
|
|
647
|
+
key: cleanKey,
|
|
648
|
+
value: entry.value,
|
|
649
|
+
expiresAt: entry.expiresAt,
|
|
650
|
+
staleUntil: entry.staleUntil,
|
|
651
|
+
tags: entry.tags,
|
|
652
|
+
tagVersions: entry.tagVersions
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const payload = {
|
|
657
|
+
version: 1,
|
|
658
|
+
writtenAt: now,
|
|
659
|
+
entries
|
|
660
|
+
};
|
|
661
|
+
const jsonStr = JSON.stringify(payload);
|
|
662
|
+
const shouldEncrypt = options?.encrypt ?? this.enc.isEnabled;
|
|
663
|
+
if (shouldEncrypt && this.enc.isEnabled) {
|
|
664
|
+
return await this.enc.encrypt(jsonStr);
|
|
665
|
+
}
|
|
666
|
+
return jsonStr;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Hydrates L1 memory and primes the Bloom filter directly from Cloudflare R2 or snapshot sources on edge isolate initialization.
|
|
670
|
+
*
|
|
671
|
+
* @param source Cloudflare R2 bucket binding (env.MY_BUCKET), reader object, snapshot string, or ArrayBuffer.
|
|
672
|
+
* @param options Configuration options (key, maxAgeMs, clockSkewToleranceMs).
|
|
673
|
+
* @returns Number of cache entries successfully restored into L1.
|
|
674
|
+
*
|
|
675
|
+
* @example
|
|
676
|
+
* // In Cloudflare Worker:
|
|
677
|
+
* export default {
|
|
678
|
+
* async fetch(request, env, ctx) {
|
|
679
|
+
* await edgeCache.hydrate(env.CACHE_R2_BUCKET);
|
|
680
|
+
* return handleRequest(request);
|
|
681
|
+
* }
|
|
682
|
+
* }
|
|
683
|
+
*/
|
|
684
|
+
async hydrate(source, options) {
|
|
685
|
+
let rawStr = null;
|
|
686
|
+
if (source && typeof source === "object") {
|
|
687
|
+
if ("get" in source && typeof source.get === "function") {
|
|
688
|
+
const key = options?.key ?? "tricache-edge.snap";
|
|
689
|
+
const obj = await source.get(key);
|
|
690
|
+
if (!obj) return 0;
|
|
691
|
+
if (typeof obj === "string") {
|
|
692
|
+
rawStr = obj;
|
|
693
|
+
} else if (obj instanceof ArrayBuffer || typeof Uint8Array !== "undefined" && obj instanceof Uint8Array) {
|
|
694
|
+
rawStr = new TextDecoder().decode(obj);
|
|
695
|
+
} else if (typeof obj.text === "function") {
|
|
696
|
+
rawStr = await obj.text();
|
|
697
|
+
} else if (typeof obj.arrayBuffer === "function") {
|
|
698
|
+
const ab = await obj.arrayBuffer();
|
|
699
|
+
rawStr = new TextDecoder().decode(ab);
|
|
700
|
+
}
|
|
701
|
+
} else if (source instanceof ArrayBuffer) {
|
|
702
|
+
rawStr = new TextDecoder().decode(source);
|
|
703
|
+
} else if (typeof Uint8Array !== "undefined" && source instanceof Uint8Array) {
|
|
704
|
+
rawStr = new TextDecoder().decode(source);
|
|
705
|
+
}
|
|
706
|
+
} else if (typeof source === "string") {
|
|
707
|
+
rawStr = source;
|
|
708
|
+
}
|
|
709
|
+
if (!rawStr) return 0;
|
|
710
|
+
if (rawStr.startsWith("enc:v1:") || rawStr.startsWith("a128:v1:")) {
|
|
711
|
+
try {
|
|
712
|
+
rawStr = await this.enc.decrypt(rawStr);
|
|
713
|
+
} catch {
|
|
714
|
+
return 0;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
let payload;
|
|
718
|
+
try {
|
|
719
|
+
payload = JSON.parse(rawStr);
|
|
720
|
+
} catch {
|
|
721
|
+
return 0;
|
|
722
|
+
}
|
|
723
|
+
if (!payload || !Array.isArray(payload.entries)) {
|
|
724
|
+
return 0;
|
|
725
|
+
}
|
|
726
|
+
const now = Date.now();
|
|
727
|
+
const maxAgeMs = options?.maxAgeMs ?? 72e5;
|
|
728
|
+
const tolerance = options?.clockSkewToleranceMs ?? 250;
|
|
729
|
+
const writtenAt = payload.writtenAt ?? 0;
|
|
730
|
+
if (writtenAt - now > tolerance) {
|
|
731
|
+
return 0;
|
|
732
|
+
}
|
|
733
|
+
const ageMs = Math.max(0, now - writtenAt);
|
|
734
|
+
if (ageMs > maxAgeMs) {
|
|
735
|
+
return 0;
|
|
736
|
+
}
|
|
737
|
+
let imported = 0;
|
|
738
|
+
for (const item of payload.entries) {
|
|
739
|
+
if (!item || typeof item.key !== "string") continue;
|
|
740
|
+
if (item.expiresAt <= now && item.staleUntil <= now) continue;
|
|
741
|
+
const nsKey = this.nk(item.key);
|
|
742
|
+
const serialized = JSON.stringify(item.value);
|
|
743
|
+
const bytes = this._estimateBytes(nsKey, serialized);
|
|
744
|
+
this._deleteL1(nsKey);
|
|
745
|
+
this._evictIfNeeded(bytes);
|
|
746
|
+
const entry = {
|
|
747
|
+
value: item.value,
|
|
748
|
+
serialized,
|
|
749
|
+
bytes,
|
|
750
|
+
expiresAt: item.expiresAt,
|
|
751
|
+
staleUntil: item.staleUntil,
|
|
752
|
+
tags: item.tags,
|
|
753
|
+
tagVersions: item.tagVersions
|
|
754
|
+
};
|
|
755
|
+
this.l1.set(nsKey, entry);
|
|
756
|
+
this.currentBytes += bytes;
|
|
757
|
+
if (item.tags) {
|
|
758
|
+
for (const tag of item.tags) {
|
|
759
|
+
let s = this.tagIndex.get(tag);
|
|
760
|
+
if (!s) {
|
|
761
|
+
s = /* @__PURE__ */ new Set();
|
|
762
|
+
this.tagIndex.set(tag, s);
|
|
763
|
+
}
|
|
764
|
+
s.add(nsKey);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (this.bloomFilter) {
|
|
768
|
+
this.bloomFilter.add(item.key);
|
|
769
|
+
}
|
|
770
|
+
imported++;
|
|
771
|
+
}
|
|
772
|
+
return imported;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Diagnostic snapshot of edge cache memory usage.
|
|
776
|
+
*/
|
|
777
|
+
stats() {
|
|
778
|
+
return {
|
|
779
|
+
keys: this.l1.size,
|
|
780
|
+
bytes: this.currentBytes,
|
|
781
|
+
maxKeys: this.maxKeys,
|
|
782
|
+
maxBytes: this.maxBytes,
|
|
783
|
+
tags: this.tagIndex.size
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
// src/edge/adapters/upstash.ts
|
|
789
|
+
var UpstashRedisAdapter = class {
|
|
790
|
+
baseUrl;
|
|
791
|
+
token;
|
|
792
|
+
customFetch;
|
|
793
|
+
constructor(options) {
|
|
794
|
+
if (!options?.url || !options?.token) {
|
|
795
|
+
throw new Error("UpstashRedisAdapter: url and token are required.");
|
|
796
|
+
}
|
|
797
|
+
this.baseUrl = options.url.replace(/\/+$/, "");
|
|
798
|
+
this.token = options.token;
|
|
799
|
+
this.customFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
800
|
+
}
|
|
801
|
+
async _executeCommand(command) {
|
|
802
|
+
const res = await this.customFetch(this.baseUrl, {
|
|
803
|
+
method: "POST",
|
|
804
|
+
headers: {
|
|
805
|
+
Authorization: `Bearer ${this.token}`,
|
|
806
|
+
"Content-Type": "application/json"
|
|
807
|
+
},
|
|
808
|
+
body: JSON.stringify(command)
|
|
809
|
+
});
|
|
810
|
+
if (!res.ok) {
|
|
811
|
+
const text = await res.text().catch(() => "");
|
|
812
|
+
throw new Error(`Upstash HTTP error (${res.status} ${res.statusText}): ${text}`);
|
|
813
|
+
}
|
|
814
|
+
const json = await res.json();
|
|
815
|
+
if (json.error) {
|
|
816
|
+
throw new Error(`Upstash Redis command error: ${json.error}`);
|
|
817
|
+
}
|
|
818
|
+
return json.result;
|
|
819
|
+
}
|
|
820
|
+
async _executePipeline(commands) {
|
|
821
|
+
const res = await this.customFetch(`${this.baseUrl}/pipeline`, {
|
|
822
|
+
method: "POST",
|
|
823
|
+
headers: {
|
|
824
|
+
Authorization: `Bearer ${this.token}`,
|
|
825
|
+
"Content-Type": "application/json"
|
|
826
|
+
},
|
|
827
|
+
body: JSON.stringify(commands)
|
|
828
|
+
});
|
|
829
|
+
if (!res.ok) {
|
|
830
|
+
const text = await res.text().catch(() => "");
|
|
831
|
+
throw new Error(`Upstash Pipeline error (${res.status} ${res.statusText}): ${text}`);
|
|
832
|
+
}
|
|
833
|
+
const json = await res.json();
|
|
834
|
+
return json.map((item) => {
|
|
835
|
+
if (item.error) {
|
|
836
|
+
throw new Error(`Upstash Redis pipeline item error: ${item.error}`);
|
|
837
|
+
}
|
|
838
|
+
return item.result;
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
async get(key) {
|
|
842
|
+
const res = await this._executeCommand(["GET", key]);
|
|
843
|
+
return res ?? null;
|
|
844
|
+
}
|
|
845
|
+
async set(key, value, ttlSeconds) {
|
|
846
|
+
if (typeof ttlSeconds === "number" && ttlSeconds > 0) {
|
|
847
|
+
await this._executeCommand(["SET", key, value, "EX", Math.round(ttlSeconds)]);
|
|
848
|
+
} else {
|
|
849
|
+
await this._executeCommand(["SET", key, value]);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
async delete(key) {
|
|
853
|
+
await this._executeCommand(["DEL", key]);
|
|
854
|
+
}
|
|
855
|
+
async mget(keys) {
|
|
856
|
+
if (keys.length === 0) return [];
|
|
857
|
+
const res = await this._executeCommand(["MGET", ...keys]);
|
|
858
|
+
return Array.isArray(res) ? res : [];
|
|
859
|
+
}
|
|
860
|
+
async mset(entries, ttlSeconds) {
|
|
861
|
+
const keys = Object.keys(entries);
|
|
862
|
+
if (keys.length === 0) return;
|
|
863
|
+
if (typeof ttlSeconds === "number" && ttlSeconds > 0) {
|
|
864
|
+
const roundedTtl = Math.round(ttlSeconds);
|
|
865
|
+
const commands = keys.map((k) => ["SET", k, entries[k], "EX", roundedTtl]);
|
|
866
|
+
await this._executePipeline(commands);
|
|
867
|
+
} else {
|
|
868
|
+
const args = [];
|
|
869
|
+
for (const k of keys) {
|
|
870
|
+
args.push(k, entries[k]);
|
|
871
|
+
}
|
|
872
|
+
await this._executeCommand(["MSET", ...args]);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
async clear(prefix) {
|
|
876
|
+
if (prefix) {
|
|
877
|
+
const pattern = prefix.endsWith("*") ? prefix : `${prefix}*`;
|
|
878
|
+
const keys = await this._executeCommand(["KEYS", pattern]);
|
|
879
|
+
if (Array.isArray(keys) && keys.length > 0) {
|
|
880
|
+
await this._executeCommand(["DEL", ...keys]);
|
|
881
|
+
}
|
|
882
|
+
} else {
|
|
883
|
+
await this._executeCommand(["FLUSHDB"]);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
async incrementTagVersion(tag) {
|
|
887
|
+
const res = await this._executeCommand(["INCR", `tag_ver:${tag}`]);
|
|
888
|
+
return typeof res === "number" ? res : 1;
|
|
889
|
+
}
|
|
890
|
+
async getTagVersion(tag) {
|
|
891
|
+
const res = await this._executeCommand(["GET", `tag_ver:${tag}`]);
|
|
892
|
+
return res ? parseInt(res, 10) || 1 : 1;
|
|
893
|
+
}
|
|
894
|
+
async batchGetTagVersions(tags) {
|
|
895
|
+
if (tags.length === 0) return {};
|
|
896
|
+
const keys = tags.map((t) => `tag_ver:${t}`);
|
|
897
|
+
const res = await this.mget(keys);
|
|
898
|
+
const result = {};
|
|
899
|
+
for (let i = 0; i < tags.length; i++) {
|
|
900
|
+
const raw = res[i];
|
|
901
|
+
result[tags[i]] = raw ? parseInt(raw, 10) || 1 : 1;
|
|
902
|
+
}
|
|
903
|
+
return result;
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
|
|
907
|
+
// src/edge/adapters/cloudflare-kv.ts
|
|
908
|
+
var MIN_CF_KV_TTL = 60;
|
|
909
|
+
var CloudflareKVAdapter = class {
|
|
910
|
+
kv;
|
|
911
|
+
constructor(kv) {
|
|
912
|
+
if (!kv) {
|
|
913
|
+
throw new Error("CloudflareKVAdapter: KVNamespace instance is required.");
|
|
914
|
+
}
|
|
915
|
+
this.kv = kv;
|
|
916
|
+
}
|
|
917
|
+
async get(key) {
|
|
918
|
+
const raw = await this.kv.get(key, { type: "text" });
|
|
919
|
+
if (raw === null) return null;
|
|
920
|
+
if (raw.startsWith('{"exp":') && raw.includes('"val":')) {
|
|
921
|
+
try {
|
|
922
|
+
const parsed = JSON.parse(raw);
|
|
923
|
+
if (typeof parsed.exp === "number" && typeof parsed.val === "string") {
|
|
924
|
+
if (Date.now() >= parsed.exp) {
|
|
925
|
+
void this.kv.delete(key).catch(() => {
|
|
926
|
+
});
|
|
927
|
+
return null;
|
|
928
|
+
}
|
|
929
|
+
return parsed.val;
|
|
930
|
+
}
|
|
931
|
+
} catch {
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
return raw;
|
|
935
|
+
}
|
|
936
|
+
async set(key, value, ttlSeconds) {
|
|
937
|
+
if (typeof ttlSeconds === "number" && ttlSeconds > 0) {
|
|
938
|
+
if (ttlSeconds < MIN_CF_KV_TTL) {
|
|
939
|
+
const envelope = {
|
|
940
|
+
exp: Date.now() + Math.round(ttlSeconds * 1e3),
|
|
941
|
+
val: value
|
|
942
|
+
};
|
|
943
|
+
await this.kv.put(key, JSON.stringify(envelope), { expirationTtl: MIN_CF_KV_TTL });
|
|
944
|
+
} else {
|
|
945
|
+
await this.kv.put(key, value, { expirationTtl: Math.round(ttlSeconds) });
|
|
946
|
+
}
|
|
947
|
+
} else {
|
|
948
|
+
await this.kv.put(key, value);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
async delete(key) {
|
|
952
|
+
await this.kv.delete(key);
|
|
953
|
+
}
|
|
954
|
+
async mget(keys) {
|
|
955
|
+
return Promise.all(keys.map((k) => this.get(k)));
|
|
956
|
+
}
|
|
957
|
+
async mset(entries, ttlSeconds) {
|
|
958
|
+
const keys = Object.keys(entries);
|
|
959
|
+
await Promise.all(keys.map((k) => this.set(k, entries[k], ttlSeconds)));
|
|
960
|
+
}
|
|
961
|
+
async clear(prefix) {
|
|
962
|
+
if (!this.kv.list) return;
|
|
963
|
+
let cursor;
|
|
964
|
+
do {
|
|
965
|
+
const res = await this.kv.list({ prefix, cursor });
|
|
966
|
+
if (res.keys.length > 0) {
|
|
967
|
+
await Promise.all(res.keys.map((item) => this.kv.delete(item.name)));
|
|
968
|
+
}
|
|
969
|
+
cursor = res.list_complete ? void 0 : res.cursor;
|
|
970
|
+
} while (cursor);
|
|
971
|
+
}
|
|
972
|
+
async incrementTagVersion(tag) {
|
|
973
|
+
const key = `tag_ver:${tag}`;
|
|
974
|
+
const raw = await this.kv.get(key);
|
|
975
|
+
const prev = raw ? parseInt(raw, 10) || 0 : 0;
|
|
976
|
+
const nextVer = Math.max(prev + 1, Date.now());
|
|
977
|
+
await this.kv.put(key, String(nextVer));
|
|
978
|
+
return nextVer;
|
|
979
|
+
}
|
|
980
|
+
async getTagVersion(tag) {
|
|
981
|
+
const raw = await this.kv.get(`tag_ver:${tag}`);
|
|
982
|
+
return raw ? parseInt(raw, 10) || 1 : 1;
|
|
983
|
+
}
|
|
984
|
+
async batchGetTagVersions(tags) {
|
|
985
|
+
const vers = await Promise.all(tags.map((t) => this.getTagVersion(t)));
|
|
986
|
+
const res = {};
|
|
987
|
+
for (let i = 0; i < tags.length; i++) {
|
|
988
|
+
res[tags[i]] = vers[i];
|
|
989
|
+
}
|
|
990
|
+
return res;
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
// src/edge/adapters/cloudflare-do.ts
|
|
995
|
+
var CloudflareDOStorageAdapter = class {
|
|
996
|
+
storage;
|
|
997
|
+
constructor(storage) {
|
|
998
|
+
if (!storage) {
|
|
999
|
+
throw new Error("CloudflareDOStorageAdapter: DurableObjectStorage instance is required.");
|
|
1000
|
+
}
|
|
1001
|
+
this.storage = storage;
|
|
1002
|
+
}
|
|
1003
|
+
async get(key) {
|
|
1004
|
+
const entry = await this.storage.get(key);
|
|
1005
|
+
if (entry === void 0 || entry === null) return null;
|
|
1006
|
+
if (typeof entry === "object" && "val" in entry && "exp" in entry) {
|
|
1007
|
+
if (entry.exp > 0 && Date.now() >= entry.exp) {
|
|
1008
|
+
void this.storage.delete(key).catch(() => {
|
|
1009
|
+
});
|
|
1010
|
+
return null;
|
|
1011
|
+
}
|
|
1012
|
+
return entry.val;
|
|
1013
|
+
}
|
|
1014
|
+
return String(entry);
|
|
1015
|
+
}
|
|
1016
|
+
async set(key, value, ttlSeconds) {
|
|
1017
|
+
const exp = typeof ttlSeconds === "number" && ttlSeconds > 0 ? Date.now() + Math.round(ttlSeconds * 1e3) : 0;
|
|
1018
|
+
const entry = { val: value, exp };
|
|
1019
|
+
await this.storage.put(key, entry);
|
|
1020
|
+
}
|
|
1021
|
+
async delete(key) {
|
|
1022
|
+
await this.storage.delete(key);
|
|
1023
|
+
}
|
|
1024
|
+
async mget(keys) {
|
|
1025
|
+
if (keys.length === 0) return [];
|
|
1026
|
+
const map = await this.storage.get(keys);
|
|
1027
|
+
const now = Date.now();
|
|
1028
|
+
const result = [];
|
|
1029
|
+
for (const k of keys) {
|
|
1030
|
+
const entry = map.get(k);
|
|
1031
|
+
if (entry === void 0 || entry === null) {
|
|
1032
|
+
result.push(null);
|
|
1033
|
+
} else if (typeof entry === "object" && "val" in entry && "exp" in entry) {
|
|
1034
|
+
if (entry.exp > 0 && now >= entry.exp) {
|
|
1035
|
+
void this.storage.delete(k).catch(() => {
|
|
1036
|
+
});
|
|
1037
|
+
result.push(null);
|
|
1038
|
+
} else {
|
|
1039
|
+
result.push(entry.val);
|
|
1040
|
+
}
|
|
1041
|
+
} else {
|
|
1042
|
+
result.push(String(entry));
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
return result;
|
|
1046
|
+
}
|
|
1047
|
+
async mset(entries, ttlSeconds) {
|
|
1048
|
+
const exp = typeof ttlSeconds === "number" && ttlSeconds > 0 ? Date.now() + Math.round(ttlSeconds * 1e3) : 0;
|
|
1049
|
+
const record = {};
|
|
1050
|
+
for (const [k, v] of Object.entries(entries)) {
|
|
1051
|
+
record[k] = { val: v, exp };
|
|
1052
|
+
}
|
|
1053
|
+
await this.storage.put(record);
|
|
1054
|
+
}
|
|
1055
|
+
async clear(prefix) {
|
|
1056
|
+
if (!this.storage.list) return;
|
|
1057
|
+
const map = await this.storage.list({ prefix });
|
|
1058
|
+
const keysToDelete = Array.from(map.keys());
|
|
1059
|
+
if (keysToDelete.length > 0) {
|
|
1060
|
+
await this.storage.delete(keysToDelete);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
async incrementTagVersion(tag) {
|
|
1064
|
+
const key = `tag_ver:${tag}`;
|
|
1065
|
+
const raw = await this.storage.get(key);
|
|
1066
|
+
const prev = raw && typeof raw === "object" && "val" in raw ? parseInt(raw.val, 10) || 0 : typeof raw === "string" ? parseInt(raw, 10) || 0 : 0;
|
|
1067
|
+
const nextVer = prev + 1;
|
|
1068
|
+
await this.storage.put(key, { val: String(nextVer), exp: 0 });
|
|
1069
|
+
return nextVer;
|
|
1070
|
+
}
|
|
1071
|
+
async getTagVersion(tag) {
|
|
1072
|
+
const raw = await this.storage.get(`tag_ver:${tag}`);
|
|
1073
|
+
if (raw && typeof raw === "object" && "val" in raw) {
|
|
1074
|
+
return parseInt(raw.val, 10) || 1;
|
|
1075
|
+
}
|
|
1076
|
+
return typeof raw === "string" ? parseInt(raw, 10) || 1 : 1;
|
|
1077
|
+
}
|
|
1078
|
+
async batchGetTagVersions(tags) {
|
|
1079
|
+
const keys = tags.map((t) => `tag_ver:${t}`);
|
|
1080
|
+
const map = await this.storage.get(keys);
|
|
1081
|
+
const result = {};
|
|
1082
|
+
for (const tag of tags) {
|
|
1083
|
+
const entry = map.get(`tag_ver:${tag}`);
|
|
1084
|
+
if (entry && typeof entry === "object" && "val" in entry) {
|
|
1085
|
+
result[tag] = parseInt(entry.val, 10) || 1;
|
|
1086
|
+
} else {
|
|
1087
|
+
result[tag] = typeof entry === "string" ? parseInt(entry, 10) || 1 : 1;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
return result;
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
export {
|
|
1094
|
+
CloudflareDOStorageAdapter,
|
|
1095
|
+
CloudflareKVAdapter,
|
|
1096
|
+
EdgeCacheService,
|
|
1097
|
+
Murmur3BloomFilter,
|
|
1098
|
+
UpstashRedisAdapter,
|
|
1099
|
+
WasmBloomFilter,
|
|
1100
|
+
WebCryptoEncryption,
|
|
1101
|
+
base64ToUint8Array,
|
|
1102
|
+
buildEdgeDeterministicKey,
|
|
1103
|
+
computeEdgeETag,
|
|
1104
|
+
honoEdgeCache,
|
|
1105
|
+
murmur3_32,
|
|
1106
|
+
uint8ArrayToBase64,
|
|
1107
|
+
uint8ArrayToUtf8,
|
|
1108
|
+
utf8ToUint8Array
|
|
1109
|
+
};
|