tricache 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -0,0 +1,797 @@
1
+ import type { ICacheSpan, ICacheTracer } from '../types';
2
+ import type {
3
+ EdgeCacheOptions,
4
+ EdgeGetOptions,
5
+ IEdgeRemoteStorage,
6
+ IEdgeBloomFilter,
7
+ CloudflareR2Object,
8
+ EdgeSnapshotSource,
9
+ EdgeHydrateOptions,
10
+ EdgeExportSnapshotOptions,
11
+ EdgeSnapshotPayload,
12
+ } from './types';
13
+ import { WebCryptoEncryption } from './crypto';
14
+ import { WasmBloomFilter } from '../wasm/bloom-filter-wasm';
15
+ import { Murmur3BloomFilter } from './utils/murmur3';
16
+
17
+ interface EdgeL1Entry<T = unknown> {
18
+ value: T;
19
+ serialized: string;
20
+ bytes: number;
21
+ expiresAt: number;
22
+ staleUntil: number;
23
+ tags?: string[];
24
+ tagVersions?: Record<string, number>;
25
+ }
26
+
27
+ /**
28
+ * Enterprise-grade cache service designed specifically for pure V8 Edge Isolates
29
+ * (Cloudflare Workers, Fastly Compute, Vercel Edge, Next.js Edge Runtime, Deno).
30
+ *
31
+ * Characteristics:
32
+ * - Zero Node.js dependencies (no node:fs, node:v8, node:net, worker_threads)
33
+ * - Dual-bounded LRU with zero background intervals (allows isolates to suspend cleanly)
34
+ * - In-flight Promise Coalescing (prevents thundering herd on edge cold starts)
35
+ * - Edge-safe Stale-While-Revalidate with ctx.waitUntil() isolation fence
36
+ * - Web Crypto AEAD at-rest encryption cross-compatible with Node.js
37
+ * - OpenTelemetry semantic conventions instrumentation
38
+ */
39
+ export class EdgeCacheService {
40
+ private readonly maxKeys: number;
41
+ private readonly maxBytes: number;
42
+ private readonly defaultTtl: number;
43
+ private readonly namespace: string;
44
+ private readonly remoteStorage: IEdgeRemoteStorage | null;
45
+ private readonly enc: WebCryptoEncryption;
46
+ private readonly tracer: ICacheTracer | null;
47
+ private readonly bloomFilter: IEdgeBloomFilter | null;
48
+
49
+ // L1 Dual-bounded LRU
50
+ private readonly l1 = new Map<string, EdgeL1Entry>();
51
+ private currentBytes = 0;
52
+
53
+ // Single-flight in-flight stampede coalescing map
54
+ private readonly inflight = new Map<string, Promise<unknown>>();
55
+
56
+ // Tag indexing for edge
57
+ private readonly tagIndex = new Map<string, Set<string>>();
58
+
59
+ // Tag version in-isolate cache with 800ms micro-TTL (prevents HTTP fetch amplification on L1 hits)
60
+ private readonly tagVersionCache = new Map<string, { version: number; expiresAt: number }>();
61
+ private readonly tagVersionTtlMs = 800;
62
+
63
+ constructor(options?: EdgeCacheOptions) {
64
+ this.maxKeys = options?.maxKeys ?? 10_000;
65
+ this.maxBytes = options?.maxBytes ?? 32 * 1024 * 1024; // 32 MB
66
+ this.defaultTtl = options?.defaultTtlSeconds ?? 300;
67
+ this.namespace = options?.namespace?.trim() ?? '';
68
+ this.remoteStorage = options?.remoteStorage ?? null;
69
+ this.tracer = options?.tracer ?? null;
70
+ this.enc = new WebCryptoEncryption(options?.encryption);
71
+
72
+ if (options?.bloomFilter === true) {
73
+ try {
74
+ this.bloomFilter = new WasmBloomFilter();
75
+ } catch {
76
+ this.bloomFilter = new Murmur3BloomFilter();
77
+ }
78
+ } else if (options?.bloomFilter) {
79
+ this.bloomFilter = options.bloomFilter;
80
+ } else {
81
+ this.bloomFilter = null;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Active Bloom filter instance defending against cold miss penetration, or null.
87
+ */
88
+ get bloom(): IEdgeBloomFilter | null {
89
+ return this.bloomFilter;
90
+ }
91
+
92
+ private nk(key: string): string {
93
+ return this.namespace ? `${this.namespace}:${key}` : key;
94
+ }
95
+
96
+ private _estimateBytes(key: string, serialized: string): number {
97
+ // Approximate UTF-16 / UTF-8 memory footprint
98
+ return (key.length + serialized.length) * 2 + 64;
99
+ }
100
+
101
+ private _evictIfNeeded(newBytes: number): void {
102
+ // 1. Evict based on byte ceiling
103
+ while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
104
+ const oldestKey = this.l1.keys().next().value;
105
+ if (oldestKey === undefined) break;
106
+ this._deleteL1(oldestKey);
107
+ }
108
+
109
+ // 2. Evict based on key ceiling
110
+ while (this.l1.size >= this.maxKeys) {
111
+ const oldestKey = this.l1.keys().next().value;
112
+ if (oldestKey === undefined) break;
113
+ this._deleteL1(oldestKey);
114
+ }
115
+ }
116
+
117
+ private _deleteL1(k: string): void {
118
+ const entry = this.l1.get(k);
119
+ if (entry) {
120
+ this.currentBytes = Math.max(0, this.currentBytes - entry.bytes);
121
+ this.l1.delete(k);
122
+ // Clean up tag index
123
+ if (entry.tags) {
124
+ for (const tag of entry.tags) {
125
+ const s = this.tagIndex.get(tag);
126
+ if (s) {
127
+ s.delete(k);
128
+ if (s.size === 0) this.tagIndex.delete(tag);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ private _startSpan(name: string): ICacheSpan {
136
+ if (this.tracer) {
137
+ const span = this.tracer.startSpan(name);
138
+ if (this.namespace) span.setAttribute('cache.namespace', this.namespace);
139
+ return span;
140
+ }
141
+ return {
142
+ setAttribute() { return this; },
143
+ setStatus() { return this; },
144
+ recordException() { return this; },
145
+ end() {},
146
+ };
147
+ }
148
+
149
+ private async _getTagVersion(tag: string): Promise<number> {
150
+ const cached = this.tagVersionCache.get(tag);
151
+ const now = Date.now();
152
+ if (cached && cached.expiresAt > now) {
153
+ return cached.version;
154
+ }
155
+ let version = 1;
156
+ if (this.remoteStorage) {
157
+ try {
158
+ if (typeof this.remoteStorage.getTagVersion === 'function') {
159
+ version = await this.remoteStorage.getTagVersion(this.nk(tag));
160
+ } else {
161
+ const raw = await this.remoteStorage.get(this.nk(`tag_ver:${tag}`));
162
+ version = raw ? parseInt(raw, 10) || 1 : 1;
163
+ }
164
+ } catch {
165
+ version = cached?.version ?? 1;
166
+ }
167
+ } else {
168
+ version = cached?.version ?? 1;
169
+ }
170
+ this.tagVersionCache.set(tag, { version, expiresAt: now + this.tagVersionTtlMs });
171
+ return version;
172
+ }
173
+
174
+ private async _batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
175
+ const now = Date.now();
176
+ const result: Record<string, number> = {};
177
+ const missingTags: string[] = [];
178
+
179
+ for (const t of tags) {
180
+ const c = this.tagVersionCache.get(t);
181
+ if (c && c.expiresAt > now) {
182
+ result[t] = c.version;
183
+ } else {
184
+ missingTags.push(t);
185
+ }
186
+ }
187
+
188
+ if (missingTags.length > 0 && this.remoteStorage) {
189
+ try {
190
+ if (typeof this.remoteStorage.batchGetTagVersions === 'function') {
191
+ const nsTags = missingTags.map(t => this.nk(t));
192
+ const remoteVersions = await this.remoteStorage.batchGetTagVersions(nsTags);
193
+ for (let i = 0; i < missingTags.length; i++) {
194
+ const t = missingTags[i];
195
+ const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
196
+ result[t] = v;
197
+ this.tagVersionCache.set(t, { version: v, expiresAt: now + this.tagVersionTtlMs });
198
+ }
199
+ } else {
200
+ await Promise.all(missingTags.map(async t => {
201
+ const v = await this._getTagVersion(t);
202
+ result[t] = v;
203
+ }));
204
+ }
205
+ } catch {
206
+ for (const t of missingTags) {
207
+ result[t] = this.tagVersionCache.get(t)?.version ?? 1;
208
+ }
209
+ }
210
+ } else {
211
+ for (const t of missingTags) {
212
+ result[t] = this.tagVersionCache.get(t)?.version ?? 1;
213
+ }
214
+ }
215
+
216
+ return result;
217
+ }
218
+
219
+ /**
220
+ * Reads or fetches a value by key.
221
+ */
222
+ async get<T>(
223
+ key: string,
224
+ fetchFn?: () => Promise<T>,
225
+ ttlSeconds?: number,
226
+ options?: EdgeGetOptions,
227
+ ): Promise<T | null> {
228
+ const span = this._startSpan('tricache.get');
229
+ span.setAttribute('cache.key', key);
230
+ const nsKey = this.nk(key);
231
+ const now = Date.now();
232
+ const resolvedTtl = ttlSeconds ?? this.defaultTtl;
233
+
234
+ try {
235
+ // 1. Check L1 Memory
236
+ const l1Entry = this.l1.get(nsKey);
237
+ if (l1Entry) {
238
+ // Check generational tag staleness
239
+ let isTagStale = false;
240
+ if (l1Entry.tagVersions) {
241
+ const tagNames = Object.keys(l1Entry.tagVersions);
242
+ const currentVers = await this._batchGetTagVersions(tagNames);
243
+ for (const tag of tagNames) {
244
+ if (currentVers[tag] > l1Entry.tagVersions[tag]) {
245
+ isTagStale = true;
246
+ break;
247
+ }
248
+ }
249
+ }
250
+
251
+ if (isTagStale) {
252
+ this._deleteL1(nsKey);
253
+ } else {
254
+ // Move to end of Map for LRU freshness
255
+ this.l1.delete(nsKey);
256
+ this.l1.set(nsKey, l1Entry);
257
+
258
+ if (l1Entry.expiresAt > now) {
259
+ // Fresh hit
260
+ span.setAttribute('cache.hit', true);
261
+ span.setAttribute('cache.item.tier', 'memory');
262
+ span.setAttribute('cache.hit_tier', 'l1');
263
+ return l1Entry.value as T;
264
+ }
265
+
266
+ if (l1Entry.staleUntil > now && fetchFn) {
267
+ // Stale hit — trigger background revalidation
268
+ span.setAttribute('cache.hit', true);
269
+ span.setAttribute('cache.item.tier', 'memory');
270
+ span.setAttribute('cache.hit_tier', 'l1');
271
+ span.setAttribute('cache.stale', true);
272
+
273
+ const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
274
+ if (options?.ctx?.waitUntil) {
275
+ options.ctx.waitUntil(revalPromise);
276
+ }
277
+ return l1Entry.value as T;
278
+ }
279
+
280
+ // Hard expired in L1
281
+ this._deleteL1(nsKey);
282
+ }
283
+ }
284
+
285
+ // 2. Check L2 Remote Storage (defended by Bloom filter against cold-miss penetration)
286
+ if (this.remoteStorage) {
287
+ if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
288
+ span.setAttribute('cache.bloom.filtered', true);
289
+ } else {
290
+ try {
291
+ const rawRemote = await this.remoteStorage.get(nsKey);
292
+ if (rawRemote !== null) {
293
+ const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
294
+ const parsedJson = JSON.parse(plain);
295
+ let parsed: T;
296
+ let activeTagVersions: Record<string, number> | undefined;
297
+ let isStaleRemote = false;
298
+
299
+ if (parsedJson && typeof parsedJson === 'object' && '__t_val' in parsedJson && '__t_tv' in parsedJson) {
300
+ parsed = parsedJson.__t_val as T;
301
+ activeTagVersions = parsedJson.__t_tv as Record<string, number>;
302
+ const tagNames = Object.keys(activeTagVersions);
303
+ const currentVers = await this._batchGetTagVersions(tagNames);
304
+ for (const tag of tagNames) {
305
+ if (currentVers[tag] > activeTagVersions[tag]) {
306
+ isStaleRemote = true;
307
+ break;
308
+ }
309
+ }
310
+ } else {
311
+ parsed = parsedJson as T;
312
+ }
313
+
314
+ if (!isStaleRemote) {
315
+ // Warm L1
316
+ await this.set(key, parsed, resolvedTtl, options);
317
+
318
+ span.setAttribute('cache.hit', true);
319
+ span.setAttribute('cache.item.tier', 'remote');
320
+ span.setAttribute('cache.hit_tier', 'l2');
321
+ return parsed;
322
+ }
323
+ }
324
+ } catch (remoteErr) {
325
+ span.recordException?.(remoteErr);
326
+ }
327
+ }
328
+ }
329
+
330
+ // 3. Cache Miss — Single-flight fetch promise coalescing
331
+ if (!fetchFn) {
332
+ span.setAttribute('cache.hit', false);
333
+ span.setAttribute('cache.hit_tier', 'miss');
334
+ return null;
335
+ }
336
+
337
+ let inflightPromise = this.inflight.get(nsKey) as Promise<T> | undefined;
338
+ let coalesced = false;
339
+
340
+ if (inflightPromise) {
341
+ coalesced = true;
342
+ } else {
343
+ inflightPromise = (async () => {
344
+ try {
345
+ const fresh = await fetchFn();
346
+ await this.set(key, fresh, resolvedTtl, options);
347
+ return fresh;
348
+ } finally {
349
+ this.inflight.delete(nsKey);
350
+ }
351
+ })();
352
+ this.inflight.set(nsKey, inflightPromise);
353
+ }
354
+
355
+ span.setAttribute('cache.hit', coalesced);
356
+ span.setAttribute('cache.hit_tier', coalesced ? 'l1' : 'miss');
357
+ span.setAttribute('cache.stampede_coalesced', coalesced);
358
+
359
+ const result = await inflightPromise;
360
+ return result;
361
+ } catch (err) {
362
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
363
+ span.recordException?.(err);
364
+ throw err;
365
+ } finally {
366
+ span.end();
367
+ }
368
+ }
369
+
370
+ private async _revalidate<T>(
371
+ key: string,
372
+ fetchFn: () => Promise<T>,
373
+ ttl: number,
374
+ options?: EdgeGetOptions,
375
+ ): Promise<void> {
376
+ const nsKey = this.nk(key);
377
+ if (this.inflight.has(nsKey)) return;
378
+
379
+ const task = (async () => {
380
+ try {
381
+ const fresh = await fetchFn();
382
+ await this.set(key, fresh, ttl, options);
383
+ } catch {
384
+ // Suppress background revalidation error to prevent unhandled rejection
385
+ } finally {
386
+ this.inflight.delete(nsKey);
387
+ }
388
+ })();
389
+
390
+ this.inflight.set(nsKey, task);
391
+ await task;
392
+ }
393
+
394
+ /**
395
+ * Sets a value in the cache with an optional TTL and tags.
396
+ */
397
+ async set<T>(
398
+ key: string,
399
+ value: T,
400
+ ttlSeconds?: number,
401
+ options?: { tags?: string[]; swr?: number },
402
+ ): Promise<void> {
403
+ const span = this._startSpan('tricache.set');
404
+ span.setAttribute('cache.key', key);
405
+ const nsKey = this.nk(key);
406
+ const resolvedTtl = ttlSeconds ?? this.defaultTtl;
407
+ const now = Date.now();
408
+ const swrSeconds = options?.swr ?? 0;
409
+
410
+ try {
411
+ let activeTagVersions: Record<string, number> | undefined;
412
+ if (options?.tags?.length) {
413
+ activeTagVersions = await this._batchGetTagVersions(options.tags);
414
+ }
415
+
416
+ const serialized = JSON.stringify(value);
417
+ const bytes = this._estimateBytes(nsKey, serialized);
418
+
419
+ // Clean old entry if updating
420
+ this._deleteL1(nsKey);
421
+ this._evictIfNeeded(bytes);
422
+
423
+ const entry: EdgeL1Entry<T> = {
424
+ value,
425
+ serialized,
426
+ bytes,
427
+ expiresAt: now + resolvedTtl * 1000,
428
+ staleUntil: now + (resolvedTtl + swrSeconds) * 1000,
429
+ tags: options?.tags,
430
+ tagVersions: activeTagVersions,
431
+ };
432
+
433
+ this.l1.set(nsKey, entry);
434
+ this.currentBytes += bytes;
435
+
436
+ // Index tags
437
+ if (options?.tags) {
438
+ for (const tag of options.tags) {
439
+ let s = this.tagIndex.get(tag);
440
+ if (!s) {
441
+ s = new Set<string>();
442
+ this.tagIndex.set(tag, s);
443
+ }
444
+ s.add(nsKey);
445
+ }
446
+ }
447
+
448
+ // Write to L2 Remote Storage if configured
449
+ if (this.remoteStorage) {
450
+ const toStoreRaw = activeTagVersions
451
+ ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions })
452
+ : serialized;
453
+ const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
454
+ await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
455
+ }
456
+
457
+ // Register in Bloom filter
458
+ if (this.bloomFilter) {
459
+ this.bloomFilter.add(nsKey);
460
+ }
461
+ } catch (err) {
462
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
463
+ span.recordException?.(err);
464
+ throw err;
465
+ } finally {
466
+ span.end();
467
+ }
468
+ }
469
+
470
+ /**
471
+ * Deletes a key from all tiers.
472
+ */
473
+ async delete(key: string): Promise<void> {
474
+ const span = this._startSpan('tricache.delete');
475
+ span.setAttribute('cache.key', key);
476
+ const nsKey = this.nk(key);
477
+
478
+ try {
479
+ this._deleteL1(nsKey);
480
+ if (this.remoteStorage) {
481
+ await this.remoteStorage.delete(nsKey);
482
+ }
483
+ } catch (err) {
484
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
485
+ span.recordException?.(err);
486
+ throw err;
487
+ } finally {
488
+ span.end();
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Invalidates all cached entries associated with a tag.
494
+ */
495
+ async invalidateTag(tag: string): Promise<void> {
496
+ const span = this._startSpan('tricache.invalidate_tag');
497
+ span.setAttribute('cache.tag', tag);
498
+
499
+ try {
500
+ let newVer = 1;
501
+ if (this.remoteStorage) {
502
+ try {
503
+ if (typeof this.remoteStorage.incrementTagVersion === 'function') {
504
+ newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
505
+ } else {
506
+ const key = this.nk(`tag_ver:${tag}`);
507
+ const current = await this._getTagVersion(tag);
508
+ newVer = Math.max(current + 1, Date.now());
509
+ await this.remoteStorage.set(key, String(newVer));
510
+ }
511
+ } catch {
512
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
513
+ newVer = current + 1;
514
+ }
515
+ } else {
516
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
517
+ newVer = current + 1;
518
+ }
519
+
520
+ // Update in-isolate version cache immediately (with 60s pin)
521
+ this.tagVersionCache.set(tag, { version: newVer, expiresAt: Date.now() + 60_000 });
522
+
523
+ // Invalidate local L1 entries
524
+ const keys = this.tagIndex.get(tag);
525
+ if (keys) {
526
+ const keysArr = Array.from(keys);
527
+ for (const k of keysArr) {
528
+ this._deleteL1(k);
529
+ }
530
+ this.tagIndex.delete(tag);
531
+ }
532
+ } catch (err) {
533
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
534
+ span.recordException?.(err);
535
+ throw err;
536
+ } finally {
537
+ span.end();
538
+ }
539
+ }
540
+
541
+ /**
542
+ * Clears all entries from the edge cache.
543
+ */
544
+ async clear(): Promise<void> {
545
+ const span = this._startSpan('tricache.clear');
546
+ try {
547
+ this.l1.clear();
548
+ this.currentBytes = 0;
549
+ this.tagIndex.clear();
550
+ this.tagVersionCache.clear();
551
+ if (this.bloomFilter) {
552
+ this.bloomFilter.reset();
553
+ }
554
+ if (this.remoteStorage) {
555
+ await this.remoteStorage.clear?.(this.namespace || undefined);
556
+ }
557
+ } catch (err) {
558
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
559
+ span.recordException?.(err);
560
+ throw err;
561
+ } finally {
562
+ span.end();
563
+ }
564
+ }
565
+
566
+ /**
567
+ * Batch get with miss-fetching.
568
+ */
569
+ async mget<T>(
570
+ keys: string[],
571
+ fetchFn?: (missKeys: string[]) => Promise<Record<string, T>>,
572
+ ttlSeconds?: number,
573
+ ): Promise<(T | null)[]> {
574
+ const span = this._startSpan('tricache.mget');
575
+ span.setAttribute('cache.batch.size', keys.length);
576
+
577
+ try {
578
+ const results: (T | null)[] = Array.from({ length: keys.length }, () => null);
579
+ const missIndices: number[] = [];
580
+ const missKeys: string[] = [];
581
+
582
+ for (let i = 0; i < keys.length; i++) {
583
+ const val = await this.get<T>(keys[i]);
584
+ if (val !== null) {
585
+ results[i] = val;
586
+ } else {
587
+ missIndices.push(i);
588
+ missKeys.push(keys[i]);
589
+ }
590
+ }
591
+
592
+ span.setAttribute('cache.hits', keys.length - missKeys.length);
593
+ span.setAttribute('cache.misses', missKeys.length);
594
+
595
+ if (missKeys.length > 0 && fetchFn) {
596
+ const fetchedMap = await fetchFn(missKeys);
597
+ for (let j = 0; j < missKeys.length; j++) {
598
+ const k = missKeys[j];
599
+ const fetchedVal = fetchedMap[k];
600
+ if (fetchedVal !== undefined) {
601
+ results[missIndices[j]] = fetchedVal;
602
+ await this.set(k, fetchedVal, ttlSeconds);
603
+ }
604
+ }
605
+ }
606
+
607
+ return results;
608
+ } catch (err) {
609
+ span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
610
+ span.recordException?.(err);
611
+ throw err;
612
+ } finally {
613
+ span.end();
614
+ }
615
+ }
616
+
617
+ /**
618
+ * Serializes active, unexpired L1 entries into a snapshot string (encrypted if WebCrypto encryption is enabled).
619
+ * Ideal for persisting Edge state to Cloudflare R2 before worker restart.
620
+ */
621
+ async exportSnapshot(options?: EdgeExportSnapshotOptions): Promise<string> {
622
+ const now = Date.now();
623
+ const entries: EdgeSnapshotPayload['entries'] = [];
624
+
625
+ for (const [nsKey, entry] of this.l1.entries()) {
626
+ if (entry.expiresAt > now || entry.staleUntil > now) {
627
+ const cleanKey = this.namespace && nsKey.startsWith(this.namespace + ':')
628
+ ? nsKey.slice(this.namespace.length + 1)
629
+ : nsKey;
630
+
631
+ entries.push({
632
+ key: cleanKey,
633
+ value: entry.value,
634
+ expiresAt: entry.expiresAt,
635
+ staleUntil: entry.staleUntil,
636
+ tags: entry.tags,
637
+ tagVersions: entry.tagVersions,
638
+ });
639
+ }
640
+ }
641
+
642
+ const payload: EdgeSnapshotPayload = {
643
+ version: 1,
644
+ writtenAt: now,
645
+ entries,
646
+ };
647
+
648
+ const jsonStr = JSON.stringify(payload);
649
+ const shouldEncrypt = options?.encrypt ?? this.enc.isEnabled;
650
+ if (shouldEncrypt && this.enc.isEnabled) {
651
+ return await this.enc.encrypt(jsonStr);
652
+ }
653
+ return jsonStr;
654
+ }
655
+
656
+ /**
657
+ * Hydrates L1 memory and primes the Bloom filter directly from Cloudflare R2 or snapshot sources on edge isolate initialization.
658
+ *
659
+ * @param source Cloudflare R2 bucket binding (env.MY_BUCKET), reader object, snapshot string, or ArrayBuffer.
660
+ * @param options Configuration options (key, maxAgeMs, clockSkewToleranceMs).
661
+ * @returns Number of cache entries successfully restored into L1.
662
+ *
663
+ * @example
664
+ * // In Cloudflare Worker:
665
+ * export default {
666
+ * async fetch(request, env, ctx) {
667
+ * await edgeCache.hydrate(env.CACHE_R2_BUCKET);
668
+ * return handleRequest(request);
669
+ * }
670
+ * }
671
+ */
672
+ async hydrate(source: EdgeSnapshotSource, options?: EdgeHydrateOptions): Promise<number> {
673
+ let rawStr: string | null = null;
674
+
675
+ if (source && typeof source === 'object') {
676
+ if ('get' in source && typeof source.get === 'function') {
677
+ const key = options?.key ?? 'tricache-edge.snap';
678
+ const obj = await source.get(key);
679
+ if (!obj) return 0;
680
+
681
+ if (typeof obj === 'string') {
682
+ rawStr = obj;
683
+ } else if (obj instanceof ArrayBuffer || (typeof Uint8Array !== 'undefined' && obj instanceof Uint8Array)) {
684
+ rawStr = new TextDecoder().decode(obj);
685
+ } else if (typeof (obj as CloudflareR2Object).text === 'function') {
686
+ rawStr = await (obj as CloudflareR2Object).text();
687
+ } else if (typeof (obj as CloudflareR2Object).arrayBuffer === 'function') {
688
+ const ab = await (obj as CloudflareR2Object).arrayBuffer();
689
+ rawStr = new TextDecoder().decode(ab);
690
+ }
691
+ } else if (source instanceof ArrayBuffer) {
692
+ rawStr = new TextDecoder().decode(source);
693
+ } else if (typeof Uint8Array !== 'undefined' && source instanceof Uint8Array) {
694
+ rawStr = new TextDecoder().decode(source);
695
+ }
696
+ } else if (typeof source === 'string') {
697
+ rawStr = source;
698
+ }
699
+
700
+ if (!rawStr) return 0;
701
+
702
+ // Decrypt if encrypted envelope
703
+ if (rawStr.startsWith('enc:v1:') || rawStr.startsWith('a128:v1:')) {
704
+ try {
705
+ rawStr = await this.enc.decrypt(rawStr);
706
+ } catch {
707
+ return 0; // Decryption failure -> fallback to cold start
708
+ }
709
+ }
710
+
711
+ let payload: EdgeSnapshotPayload;
712
+ try {
713
+ payload = JSON.parse(rawStr) as EdgeSnapshotPayload;
714
+ } catch {
715
+ return 0; // Malformed JSON -> fallback cold
716
+ }
717
+
718
+ if (!payload || !Array.isArray(payload.entries)) {
719
+ return 0;
720
+ }
721
+
722
+ const now = Date.now();
723
+ const maxAgeMs = options?.maxAgeMs ?? 7_200_000;
724
+ const tolerance = options?.clockSkewToleranceMs ?? 250;
725
+ const writtenAt = payload.writtenAt ?? 0;
726
+
727
+ // Reject future timestamp exceeding clock skew tolerance
728
+ if (writtenAt - now > tolerance) {
729
+ return 0;
730
+ }
731
+
732
+ // Reject stale snapshot
733
+ const ageMs = Math.max(0, now - writtenAt);
734
+ if (ageMs > maxAgeMs) {
735
+ return 0;
736
+ }
737
+
738
+ let imported = 0;
739
+ for (const item of payload.entries) {
740
+ if (!item || typeof item.key !== 'string') continue;
741
+ // Skip if completely expired
742
+ if (item.expiresAt <= now && item.staleUntil <= now) continue;
743
+
744
+ const nsKey = this.nk(item.key);
745
+ const serialized = JSON.stringify(item.value);
746
+ const bytes = this._estimateBytes(nsKey, serialized);
747
+
748
+ this._deleteL1(nsKey);
749
+ this._evictIfNeeded(bytes);
750
+
751
+ const entry: EdgeL1Entry = {
752
+ value: item.value,
753
+ serialized,
754
+ bytes,
755
+ expiresAt: item.expiresAt,
756
+ staleUntil: item.staleUntil,
757
+ tags: item.tags,
758
+ tagVersions: item.tagVersions,
759
+ };
760
+
761
+ this.l1.set(nsKey, entry);
762
+ this.currentBytes += bytes;
763
+
764
+ if (item.tags) {
765
+ for (const tag of item.tags) {
766
+ let s = this.tagIndex.get(tag);
767
+ if (!s) {
768
+ s = new Set<string>();
769
+ this.tagIndex.set(tag, s);
770
+ }
771
+ s.add(nsKey);
772
+ }
773
+ }
774
+
775
+ if (this.bloomFilter) {
776
+ this.bloomFilter.add(item.key);
777
+ }
778
+
779
+ imported++;
780
+ }
781
+
782
+ return imported;
783
+ }
784
+
785
+ /**
786
+ * Diagnostic snapshot of edge cache memory usage.
787
+ */
788
+ stats() {
789
+ return {
790
+ keys: this.l1.size,
791
+ bytes: this.currentBytes,
792
+ maxKeys: this.maxKeys,
793
+ maxBytes: this.maxBytes,
794
+ tags: this.tagIndex.size,
795
+ };
796
+ }
797
+ }