tricache 1.0.1 → 1.0.2

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 (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1370 -624
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +106 -27
  61. package/src/cache-service.ts +802 -502
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +145 -97
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +62 -17
  74. package/src/http/fastify.ts +35 -21
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,127 @@
1
+ import { I as IEdgeRemoteStorage, U as UpstashRedisOptions, a as CloudflareKVNamespace, d as CloudflareDOStorage } from '../hono-C886ok3X.cjs';
2
+ export { C as CachedEdgeHttpResponse, e as CloudflareR2Bucket, f as CloudflareR2Object, E as EdgeCacheOptions, g as EdgeCacheService, i as EdgeExportSnapshotOptions, j as EdgeGetOptions, k as EdgeHydrateOptions, l as EdgeSnapshotPayload, m as EdgeSnapshotSource, H as HonoEdgeCacheOptions, n as IEdgeBloomFilter, b as buildEdgeDeterministicKey, c as computeEdgeETag, h as honoEdgeCache } from '../hono-C886ok3X.cjs';
3
+ export { B as BloomFilterStats, M as Murmur3BloomFilter, W as WasmBloomFilter, m as murmur3_32 } from '../murmur3-CMGw9PbV.cjs';
4
+ import '../types-BA4pz1A0.cjs';
5
+ import 'crypto';
6
+
7
+ type WebCryptoMode = 'aes-256-gcm' | 'aes-128-gcm';
8
+ interface WebCryptoOptions {
9
+ keyBase64: string;
10
+ prevKeyBase64?: string;
11
+ mode?: WebCryptoMode;
12
+ }
13
+ /**
14
+ * Pure Web Crypto API implementation of TriCache AEAD encryption.
15
+ * Compatible with Cloudflare Workers, Fastly Compute, Vercel Edge, Deno, and modern browsers.
16
+ *
17
+ * Interoperates with Node.js `CacheEncryption` by reordering Web Crypto's trailing tag
18
+ * into TriCache's standard wire envelope:
19
+ * Envelope = IV[12] || Tag[16] || Ciphertext[N]
20
+ */
21
+ declare class WebCryptoEncryption {
22
+ readonly isEnabled: boolean;
23
+ private readonly mode;
24
+ private keyPromise;
25
+ private prevKeyPromise;
26
+ constructor(options?: WebCryptoOptions);
27
+ private _importKey;
28
+ /**
29
+ * Encrypts a plaintext string into a TriCache standard wire envelope.
30
+ * Format: `enc:v1:<base64(IV[12] | Tag[16] | Ciphertext)>`
31
+ */
32
+ encrypt(plaintext: string): Promise<string>;
33
+ /**
34
+ * Decrypts a TriCache standard wire envelope into plaintext.
35
+ * Handles envelopes created by both WebCryptoEncryption and Node.js CacheEncryption.
36
+ */
37
+ decrypt(envelopeStr: string): Promise<string>;
38
+ private _decryptWithKey;
39
+ }
40
+
41
+ /**
42
+ * High-performance HTTP-based Redis driver for Upstash.
43
+ * Compatible with pure V8 Edge Isolates (Cloudflare Workers, Vercel Edge, Fastly Compute).
44
+ *
45
+ * Communicates over HTTPS REST with zero native socket dependencies.
46
+ */
47
+ declare class UpstashRedisAdapter implements IEdgeRemoteStorage {
48
+ private readonly baseUrl;
49
+ private readonly token;
50
+ private readonly customFetch;
51
+ constructor(options: UpstashRedisOptions);
52
+ private _executeCommand;
53
+ private _executePipeline;
54
+ get(key: string): Promise<string | null>;
55
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
56
+ delete(key: string): Promise<void>;
57
+ mget(keys: string[]): Promise<(string | null)[]>;
58
+ mset(entries: Record<string, string>, ttlSeconds?: number): Promise<void>;
59
+ clear(prefix?: string): Promise<void>;
60
+ incrementTagVersion(tag: string): Promise<number>;
61
+ getTagVersion(tag: string): Promise<number>;
62
+ batchGetTagVersions(tags: string[]): Promise<Record<string, number>>;
63
+ }
64
+
65
+ /**
66
+ * Storage adapter for Cloudflare Workers KV.
67
+ *
68
+ * Mitigates Cloudflare KV's strict 60-second TTL floor by wrapping sub-minute
69
+ * TTLs in a lightweight timestamp envelope and validating expiry on read.
70
+ */
71
+ declare class CloudflareKVAdapter implements IEdgeRemoteStorage {
72
+ private readonly kv;
73
+ constructor(kv: CloudflareKVNamespace);
74
+ get(key: string): Promise<string | null>;
75
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
76
+ delete(key: string): Promise<void>;
77
+ mget(keys: string[]): Promise<(string | null)[]>;
78
+ mset(entries: Record<string, string>, ttlSeconds?: number): Promise<void>;
79
+ clear(prefix?: string): Promise<void>;
80
+ incrementTagVersion(tag: string): Promise<number>;
81
+ getTagVersion(tag: string): Promise<number>;
82
+ batchGetTagVersions(tags: string[]): Promise<Record<string, number>>;
83
+ }
84
+
85
+ /**
86
+ * Storage adapter for Cloudflare Durable Objects transactional storage (`state.storage`).
87
+ * Enables strongly-consistent edge caching and coordination across edge isolates.
88
+ */
89
+ declare class CloudflareDOStorageAdapter implements IEdgeRemoteStorage {
90
+ private readonly storage;
91
+ constructor(storage: CloudflareDOStorage);
92
+ get(key: string): Promise<string | null>;
93
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
94
+ delete(key: string): Promise<void>;
95
+ mget(keys: string[]): Promise<(string | null)[]>;
96
+ mset(entries: Record<string, string>, ttlSeconds?: number): Promise<void>;
97
+ clear(prefix?: string): Promise<void>;
98
+ incrementTagVersion(tag: string): Promise<number>;
99
+ getTagVersion(tag: string): Promise<number>;
100
+ batchGetTagVersions(tags: string[]): Promise<Record<string, number>>;
101
+ }
102
+
103
+ /**
104
+ * Zero-dependency Base64 <-> Uint8Array utilities designed for pure Edge isolates
105
+ * (Cloudflare Workers without nodejs_compat, Deno, Fastly Compute, browsers).
106
+ *
107
+ * Avoids call stack overflow (RangeError: Maximum call stack size exceeded)
108
+ * on payloads > 64 KB by chunking binary data into safe 8 KB slices.
109
+ */
110
+ /**
111
+ * Converts a Uint8Array to a standard Base64 string safely across all JS runtimes.
112
+ */
113
+ declare function uint8ArrayToBase64(bytes: Uint8Array): string;
114
+ /**
115
+ * Converts a Base64 string to a Uint8Array safely across all JS runtimes.
116
+ */
117
+ declare function base64ToUint8Array(base64: string): Uint8Array;
118
+ /**
119
+ * Encodes a UTF-8 string to a Uint8Array using standard TextEncoder.
120
+ */
121
+ declare function utf8ToUint8Array(str: string): Uint8Array;
122
+ /**
123
+ * Decodes a Uint8Array to a UTF-8 string using standard TextDecoder.
124
+ */
125
+ declare function uint8ArrayToUtf8(bytes: Uint8Array): string;
126
+
127
+ export { CloudflareDOStorage, CloudflareDOStorageAdapter, CloudflareKVAdapter, CloudflareKVNamespace, IEdgeRemoteStorage, UpstashRedisAdapter, UpstashRedisOptions, WebCryptoEncryption, type WebCryptoMode, type WebCryptoOptions, base64ToUint8Array, uint8ArrayToBase64, uint8ArrayToUtf8, utf8ToUint8Array };
@@ -1,7 +1,7 @@
1
- import { I as IEdgeRemoteStorage, U as UpstashRedisOptions, a as CloudflareKVNamespace, d as CloudflareDOStorage } from '../hono-DSV2ve66.js';
2
- export { C as CachedEdgeHttpResponse, e as CloudflareR2Bucket, f as CloudflareR2Object, E as EdgeCacheOptions, g as EdgeCacheService, i as EdgeExportSnapshotOptions, j as EdgeGetOptions, k as EdgeHydrateOptions, l as EdgeSnapshotPayload, m as EdgeSnapshotSource, H as HonoEdgeCacheOptions, n as IEdgeBloomFilter, b as buildEdgeDeterministicKey, c as computeEdgeETag, h as honoEdgeCache } from '../hono-DSV2ve66.js';
1
+ import { I as IEdgeRemoteStorage, U as UpstashRedisOptions, a as CloudflareKVNamespace, d as CloudflareDOStorage } from '../hono-3rDMYVtY.js';
2
+ export { C as CachedEdgeHttpResponse, e as CloudflareR2Bucket, f as CloudflareR2Object, E as EdgeCacheOptions, g as EdgeCacheService, i as EdgeExportSnapshotOptions, j as EdgeGetOptions, k as EdgeHydrateOptions, l as EdgeSnapshotPayload, m as EdgeSnapshotSource, H as HonoEdgeCacheOptions, n as IEdgeBloomFilter, b as buildEdgeDeterministicKey, c as computeEdgeETag, h as honoEdgeCache } from '../hono-3rDMYVtY.js';
3
3
  export { B as BloomFilterStats, M as Murmur3BloomFilter, W as WasmBloomFilter, m as murmur3_32 } from '../murmur3-CMGw9PbV.js';
4
- import '../types-Dyip5wAl.js';
4
+ import '../types-BA4pz1A0.js';
5
5
  import 'crypto';
6
6
 
7
7
  type WebCryptoMode = 'aes-256-gcm' | 'aes-128-gcm';
@@ -11,12 +11,12 @@ import {
11
11
  uint8ArrayToBase64,
12
12
  uint8ArrayToUtf8,
13
13
  utf8ToUint8Array
14
- } from "../chunk-2AJKEQMZ.js";
14
+ } from "../chunk-H4GFLQ26.js";
15
15
  import {
16
16
  buildEdgeDeterministicKey,
17
17
  computeEdgeETag,
18
18
  honoEdgeCache
19
- } from "../chunk-IITRFWHY.js";
19
+ } from "../chunk-EUKB7RKP.js";
20
20
 
21
21
  // src/edge/crypto.ts
22
22
  var PREFIX_256 = "enc:v1:";
@@ -152,6 +152,7 @@ var WebCryptoEncryption = class {
152
152
  };
153
153
 
154
154
  // src/edge/cache.ts
155
+ var NAMESPACE_TAG = "_tricache_namespace_";
155
156
  var EdgeCacheService = class _EdgeCacheService {
156
157
  maxKeys;
157
158
  maxBytes;
@@ -161,6 +162,10 @@ var EdgeCacheService = class _EdgeCacheService {
161
162
  enc;
162
163
  tracer;
163
164
  bloomFilter;
165
+ bloomAuthoritative;
166
+ globalEpoch = 0;
167
+ lastGlobalMutationAt = 0;
168
+ keyEpochs = /* @__PURE__ */ new Map();
164
169
  // L1 Dual-bounded LRU
165
170
  l1 = /* @__PURE__ */ new Map();
166
171
  currentBytes = 0;
@@ -180,6 +185,8 @@ var EdgeCacheService = class _EdgeCacheService {
180
185
  this.remoteStorage = options?.remoteStorage ?? null;
181
186
  this.tracer = options?.tracer ?? null;
182
187
  this.enc = new WebCryptoEncryption(options?.encryption);
188
+ this.bloomAuthoritative = options?.bloomFilterAuthoritative ?? false;
189
+ if (!Number.isInteger(this.maxKeys) || this.maxKeys < 0 || !Number.isFinite(this.maxBytes) || this.maxBytes < 0 || !Number.isFinite(this.defaultTtl) || this.defaultTtl < 0) throw new Error("Edge cache limits and TTL must be finite non-negative values");
183
190
  if (options?.bloomFilter === true) {
184
191
  try {
185
192
  this.bloomFilter = new WasmBloomFilter();
@@ -204,6 +211,66 @@ var EdgeCacheService = class _EdgeCacheService {
204
211
  _estimateBytes(key, serialized) {
205
212
  return (key.length + serialized.length) * 2 + 64;
206
213
  }
214
+ fence(key) {
215
+ return `${this.globalEpoch}:${this.keyEpochs.get(key) ?? 0}`;
216
+ }
217
+ mutate(key) {
218
+ this.keyEpochs.set(key, (this.keyEpochs.get(key) ?? 0) + 1);
219
+ this.inflight.delete(key);
220
+ if (this.keyEpochs.size > 5e4) {
221
+ this.globalEpoch++;
222
+ this.keyEpochs.clear();
223
+ }
224
+ }
225
+ invalidateWork() {
226
+ this.globalEpoch++;
227
+ this.lastGlobalMutationAt = Date.now();
228
+ this.inflight.clear();
229
+ }
230
+ storeL1(key, entry) {
231
+ this._deleteL1(key);
232
+ if (entry.bytes > this.maxBytes || this.maxKeys === 0 || entry.staleUntil <= Date.now()) return false;
233
+ this._evictIfNeeded(entry.bytes);
234
+ this.l1.set(key, entry);
235
+ this.currentBytes += entry.bytes;
236
+ for (const tag of entry.tags ?? []) {
237
+ const members = this.tagIndex.get(tag) ?? /* @__PURE__ */ new Set();
238
+ members.add(key);
239
+ this.tagIndex.set(tag, members);
240
+ }
241
+ this.bloomFilter?.add(key);
242
+ return true;
243
+ }
244
+ async commit(key, value, ttl, options, versions, epoch) {
245
+ const namespaced = this.nk(key);
246
+ if (this.fence(namespaced) !== epoch) return;
247
+ const serialized = JSON.stringify(value);
248
+ if (serialized === void 0) return;
249
+ const now = Date.now();
250
+ const entry = {
251
+ value,
252
+ serialized,
253
+ bytes: this._estimateBytes(namespaced, serialized),
254
+ expiresAt: now + ttl * 1e3,
255
+ staleUntil: now + (ttl + (options?.swr ?? 0)) * 1e3,
256
+ tags: options?.tags ? [...new Set(options.tags)] : void 0,
257
+ tagVersions: versions
258
+ };
259
+ this.storeL1(namespaced, entry);
260
+ if (this.remoteStorage) {
261
+ const envelope = JSON.stringify({
262
+ __t_edge: 2,
263
+ __t_val: value,
264
+ __t_tv: versions,
265
+ __t_exp: entry.expiresAt,
266
+ __t_stale: entry.staleUntil,
267
+ __t_tags: entry.tags
268
+ });
269
+ const payload = this.enc.isEnabled ? await this.enc.encrypt(envelope) : envelope;
270
+ if (this.fence(namespaced) !== epoch) return;
271
+ await this.remoteStorage.set(namespaced, payload, ttl + (options?.swr ?? 0));
272
+ }
273
+ }
207
274
  _evictIfNeeded(newBytes) {
208
275
  while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
209
276
  const oldestKey = this.l1.keys().next().value;
@@ -265,7 +332,8 @@ var EdgeCacheService = class _EdgeCacheService {
265
332
  if (oldestKey !== void 0) this.tagVersionCache.delete(oldestKey);
266
333
  }
267
334
  }
268
- this.tagVersionCache.set(tag, { version, expiresAt });
335
+ const known = this.tagVersionCache.get(tag)?.version ?? 0;
336
+ this.tagVersionCache.set(tag, { version: Math.max(known, version), expiresAt });
269
337
  }
270
338
  async _getTagVersion(tag) {
271
339
  const cached = this.tagVersionCache.get(tag);
@@ -289,11 +357,11 @@ var EdgeCacheService = class _EdgeCacheService {
289
357
  version = cached?.version ?? 1;
290
358
  }
291
359
  this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
292
- return version;
360
+ return this.tagVersionCache.get(tag)?.version ?? version;
293
361
  }
294
362
  async _batchGetTagVersions(tags) {
295
363
  const now = Date.now();
296
- const result = {};
364
+ const result = /* @__PURE__ */ Object.create(null);
297
365
  const missingTags = [];
298
366
  for (const t of tags) {
299
367
  const c = this.tagVersionCache.get(t);
@@ -311,7 +379,7 @@ var EdgeCacheService = class _EdgeCacheService {
311
379
  for (let i = 0; i < missingTags.length; i++) {
312
380
  const t = missingTags[i];
313
381
  const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
314
- result[t] = v;
382
+ result[t] = Math.max(this.tagVersionCache.get(t)?.version ?? 0, v);
315
383
  this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
316
384
  }
317
385
  } else {
@@ -339,7 +407,7 @@ var EdgeCacheService = class _EdgeCacheService {
339
407
  const span = this._startSpan("tricache.get");
340
408
  span.setAttribute("cache.key", key);
341
409
  const nsKey = this.nk(key);
342
- const now = Date.now();
410
+ let now = Date.now();
343
411
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
344
412
  try {
345
413
  const l1Entry = this.l1.get(nsKey);
@@ -355,6 +423,7 @@ var EdgeCacheService = class _EdgeCacheService {
355
423
  }
356
424
  }
357
425
  }
426
+ now = Date.now();
358
427
  if (isTagStale) {
359
428
  this._deleteL1(nsKey);
360
429
  } else {
@@ -366,85 +435,115 @@ var EdgeCacheService = class _EdgeCacheService {
366
435
  span.setAttribute("cache.hit_tier", "l1");
367
436
  return l1Entry.value;
368
437
  }
369
- if (l1Entry.staleUntil > now && fetchFn) {
438
+ if (l1Entry.staleUntil > now && fetchFn && (options?.swr ?? 0) > 0) {
370
439
  span.setAttribute("cache.hit", true);
371
440
  span.setAttribute("cache.item.tier", "memory");
372
441
  span.setAttribute("cache.hit_tier", "l1");
373
442
  span.setAttribute("cache.stale", true);
374
- const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
443
+ const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: options?.tags ?? l1Entry.tags });
375
444
  if (options?.ctx?.waitUntil) {
376
445
  options.ctx.waitUntil(revalPromise);
377
446
  }
378
447
  return l1Entry.value;
379
448
  }
380
- this._deleteL1(nsKey);
449
+ if (l1Entry.staleUntil <= now) this._deleteL1(nsKey);
381
450
  }
382
451
  }
383
- if (this.remoteStorage) {
384
- if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
385
- span.setAttribute("cache.bloom.filtered", true);
386
- } else {
387
- try {
388
- const rawRemote = await this.remoteStorage.get(nsKey);
389
- if (rawRemote !== null) {
390
- const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
391
- const parsedJson = JSON.parse(plain);
392
- let parsed;
393
- let activeTagVersions;
394
- let isStaleRemote = false;
395
- if (parsedJson && typeof parsedJson === "object" && "__t_val" in parsedJson && "__t_tv" in parsedJson) {
396
- parsed = parsedJson.__t_val;
397
- activeTagVersions = parsedJson.__t_tv;
398
- const tagNames = Object.keys(activeTagVersions);
399
- const currentVers = await this._batchGetTagVersions(tagNames);
400
- for (const tag of tagNames) {
401
- if (currentVers[tag] > activeTagVersions[tag]) {
402
- isStaleRemote = true;
403
- break;
452
+ const existing = this.inflight.get(nsKey);
453
+ if (existing) {
454
+ span.setAttribute("cache.stampede_coalesced", true);
455
+ return await existing;
456
+ }
457
+ const epoch = this.fence(nsKey);
458
+ const execution = Promise.resolve().then(async () => {
459
+ try {
460
+ if (this.remoteStorage) {
461
+ if (this.bloomAuthoritative && this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
462
+ span.setAttribute("cache.bloom.filtered", true);
463
+ } else {
464
+ try {
465
+ const rawRemote = await this.remoteStorage.get(nsKey);
466
+ if (rawRemote !== null) {
467
+ const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
468
+ const parsedJson = JSON.parse(plain);
469
+ let parsed;
470
+ let activeTagVersions;
471
+ let isStaleRemote = false;
472
+ if (parsedJson && typeof parsedJson === "object" && "__t_val" in parsedJson && "__t_tv" in parsedJson) {
473
+ parsed = parsedJson.__t_val;
474
+ activeTagVersions = parsedJson.__t_tv;
475
+ if (!activeTagVersions || typeof activeTagVersions !== "object" || Array.isArray(activeTagVersions) || Object.values(activeTagVersions).some((version) => !Number.isSafeInteger(version) || version < 0)) throw new Error("Invalid remote tag versions");
476
+ const tagNames = Object.keys(activeTagVersions);
477
+ const currentVers = await this._batchGetTagVersions(tagNames);
478
+ for (const tag of tagNames) {
479
+ if (currentVers[tag] > activeTagVersions[tag]) {
480
+ isStaleRemote = true;
481
+ break;
482
+ }
483
+ }
484
+ } else {
485
+ parsed = parsedJson;
486
+ }
487
+ if (!isStaleRemote) {
488
+ const freshUntil = Number(parsedJson?.__t_exp);
489
+ const staleUntil = Number(parsedJson?.__t_stale);
490
+ const versioned = parsedJson?.__t_edge === 2 && Number.isFinite(freshUntil) && Number.isFinite(staleUntil) && staleUntil >= freshUntil;
491
+ if (versioned && (staleUntil <= Date.now() || freshUntil <= Date.now() && (!(options?.swr ?? 0) || !fetchFn))) {
492
+ isStaleRemote = true;
493
+ } else {
494
+ if (versioned && this.fence(nsKey) === epoch) {
495
+ const serialized = JSON.stringify(parsed);
496
+ const tags2 = Array.isArray(parsedJson.__t_tags) ? parsedJson.__t_tags : Object.keys(activeTagVersions ?? {}).filter((tag) => tag !== NAMESPACE_TAG);
497
+ this.storeL1(nsKey, {
498
+ value: parsed,
499
+ serialized,
500
+ bytes: this._estimateBytes(nsKey, serialized),
501
+ expiresAt: freshUntil,
502
+ staleUntil,
503
+ tags: tags2,
504
+ tagVersions: activeTagVersions
505
+ });
506
+ if (freshUntil <= Date.now() && fetchFn) {
507
+ const refresh = execution.then(() => this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: tags2 }));
508
+ options?.ctx?.waitUntil(refresh);
509
+ }
510
+ }
511
+ span.setAttribute("cache.hit", true);
512
+ span.setAttribute("cache.item.tier", "remote");
513
+ span.setAttribute("cache.hit_tier", "l2");
514
+ return parsed;
515
+ }
404
516
  }
405
517
  }
406
- } else {
407
- parsed = parsedJson;
408
- }
409
- if (!isStaleRemote) {
410
- await this.set(key, parsed, resolvedTtl, options);
411
- span.setAttribute("cache.hit", true);
412
- span.setAttribute("cache.item.tier", "remote");
413
- span.setAttribute("cache.hit_tier", "l2");
414
- return parsed;
518
+ } catch (remoteErr) {
519
+ span.recordException?.(remoteErr);
415
520
  }
416
521
  }
417
- } catch (remoteErr) {
418
- span.recordException?.(remoteErr);
419
522
  }
420
- }
421
- }
422
- if (!fetchFn) {
423
- span.setAttribute("cache.hit", false);
424
- span.setAttribute("cache.hit_tier", "miss");
425
- return null;
426
- }
427
- let inflightPromise = this.inflight.get(nsKey);
428
- let coalesced = false;
429
- if (inflightPromise) {
430
- coalesced = true;
431
- } else {
432
- inflightPromise = (async () => {
433
- try {
434
- const fresh = await fetchFn();
435
- await this.set(key, fresh, resolvedTtl, options);
436
- return fresh;
437
- } finally {
438
- this.inflight.delete(nsKey);
523
+ if (!fetchFn) {
524
+ span.setAttribute("cache.hit", false);
525
+ span.setAttribute("cache.hit_tier", "miss");
526
+ return null;
439
527
  }
440
- })();
441
- this.inflight.set(nsKey, inflightPromise);
442
- }
443
- span.setAttribute("cache.hit", coalesced);
444
- span.setAttribute("cache.hit_tier", coalesced ? "l1" : "miss");
445
- span.setAttribute("cache.stampede_coalesced", coalesced);
446
- const result = await inflightPromise;
447
- return result;
528
+ const tags = [.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
529
+ const versions = await this._batchGetTagVersions(tags);
530
+ const fresh = await fetchFn();
531
+ const current = await this._batchGetTagVersions(tags);
532
+ if (this.fence(nsKey) === epoch && tags.every((tag) => current[tag] === versions[tag])) {
533
+ try {
534
+ await this.commit(key, fresh, resolvedTtl, options, versions, epoch);
535
+ } catch (error) {
536
+ span.recordException?.(error);
537
+ }
538
+ }
539
+ span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
540
+ return fresh;
541
+ } finally {
542
+ if (this.inflight.get(nsKey) === execution) this.inflight.delete(nsKey);
543
+ }
544
+ });
545
+ this.inflight.set(nsKey, execution);
546
+ return await execution;
448
547
  } catch (err) {
449
548
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
450
549
  span.recordException?.(err);
@@ -456,15 +555,19 @@ var EdgeCacheService = class _EdgeCacheService {
456
555
  async _revalidate(key, fetchFn, ttl, options) {
457
556
  const nsKey = this.nk(key);
458
557
  if (this.inflight.has(nsKey)) return;
459
- const task = (async () => {
558
+ const epoch = this.fence(nsKey);
559
+ const task = Promise.resolve().then(async () => {
460
560
  try {
561
+ const tags = [.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
562
+ const versions = await this._batchGetTagVersions(tags);
461
563
  const fresh = await fetchFn();
462
- await this.set(key, fresh, ttl, options);
564
+ const current = await this._batchGetTagVersions(tags);
565
+ if (this.fence(nsKey) === epoch && tags.every((tag) => current[tag] === versions[tag])) await this.commit(key, fresh, ttl, options, versions, epoch);
463
566
  } catch {
464
567
  } finally {
465
- this.inflight.delete(nsKey);
568
+ if (this.inflight.get(nsKey) === task) this.inflight.delete(nsKey);
466
569
  }
467
- })();
570
+ });
468
571
  this.inflight.set(nsKey, task);
469
572
  await task;
470
573
  }
@@ -475,48 +578,15 @@ var EdgeCacheService = class _EdgeCacheService {
475
578
  const span = this._startSpan("tricache.set");
476
579
  span.setAttribute("cache.key", key);
477
580
  const nsKey = this.nk(key);
581
+ this.mutate(nsKey);
582
+ const epoch = this.fence(nsKey);
478
583
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
479
- const now = Date.now();
480
584
  const optObj = Array.isArray(options) ? { tags: options } : options;
481
585
  const swrSeconds = optObj?.swr ?? 0;
482
586
  try {
483
- let activeTagVersions;
484
- if (optObj?.tags?.length) {
485
- activeTagVersions = await this._batchGetTagVersions(optObj.tags);
486
- }
487
- const serialized = JSON.stringify(value);
488
- const bytes = this._estimateBytes(nsKey, serialized);
489
- this._deleteL1(nsKey);
490
- this._evictIfNeeded(bytes);
491
- const entry = {
492
- value,
493
- serialized,
494
- bytes,
495
- expiresAt: now + resolvedTtl * 1e3,
496
- staleUntil: now + (resolvedTtl + swrSeconds) * 1e3,
497
- tags: optObj?.tags,
498
- tagVersions: activeTagVersions
499
- };
500
- this.l1.set(nsKey, entry);
501
- this.currentBytes += bytes;
502
- if (optObj?.tags) {
503
- for (const tag of optObj.tags) {
504
- let s = this.tagIndex.get(tag);
505
- if (!s) {
506
- s = /* @__PURE__ */ new Set();
507
- this.tagIndex.set(tag, s);
508
- }
509
- s.add(nsKey);
510
- }
511
- }
512
- if (this.remoteStorage) {
513
- const toStoreRaw = activeTagVersions ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions }) : serialized;
514
- const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
515
- await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
516
- }
517
- if (this.bloomFilter) {
518
- this.bloomFilter.add(nsKey);
519
- }
587
+ if (!Number.isFinite(resolvedTtl) || resolvedTtl < 0 || !Number.isFinite(swrSeconds) || swrSeconds < 0) throw new Error("Edge TTL and SWR must be finite non-negative values");
588
+ const versions = await this._batchGetTagVersions([.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...optObj?.tags ?? []])]);
589
+ await this.commit(key, value, resolvedTtl, optObj, versions, epoch);
520
590
  } catch (err) {
521
591
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
522
592
  span.recordException?.(err);
@@ -533,6 +603,7 @@ var EdgeCacheService = class _EdgeCacheService {
533
603
  span.setAttribute("cache.key", key);
534
604
  const nsKey = this.nk(key);
535
605
  try {
606
+ this.mutate(nsKey);
536
607
  this._deleteL1(nsKey);
537
608
  if (this.remoteStorage) {
538
609
  await this.remoteStorage.delete(nsKey);
@@ -550,11 +621,15 @@ var EdgeCacheService = class _EdgeCacheService {
550
621
  * re-entering wildcard/cascade resolution.
551
622
  */
552
623
  async _invalidateConcreteTag(tag) {
624
+ this.invalidateWork();
625
+ const previous = this.tagVersionCache.get(tag)?.version ?? 1;
553
626
  let newVer = 1;
554
627
  if (this.remoteStorage) {
555
628
  try {
556
629
  if (typeof this.remoteStorage.incrementTagVersion === "function") {
557
630
  newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
631
+ if (newVer <= previous) newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
632
+ newVer = Math.max(previous + 1, newVer);
558
633
  } else {
559
634
  const key = this.nk(`tag_ver:${tag}`);
560
635
  const current = await this._getTagVersion(tag);
@@ -569,7 +644,7 @@ var EdgeCacheService = class _EdgeCacheService {
569
644
  const current = this.tagVersionCache.get(tag)?.version ?? 1;
570
645
  newVer = current + 1;
571
646
  }
572
- this._setTagVersionCache(tag, newVer, Date.now() + 6e4);
647
+ this._setTagVersionCache(tag, newVer, Date.now() + this.tagVersionTtlMs);
573
648
  const keys = this.tagIndex.get(tag);
574
649
  if (keys) {
575
650
  const keysArr = Array.from(keys);
@@ -624,6 +699,8 @@ var EdgeCacheService = class _EdgeCacheService {
624
699
  async clear() {
625
700
  const span = this._startSpan("tricache.clear");
626
701
  try {
702
+ const previousNamespace = await this._getTagVersion(NAMESPACE_TAG);
703
+ this.invalidateWork();
627
704
  this.l1.clear();
628
705
  this.currentBytes = 0;
629
706
  this.tagIndex.clear();
@@ -632,8 +709,10 @@ var EdgeCacheService = class _EdgeCacheService {
632
709
  this.bloomFilter.reset();
633
710
  }
634
711
  if (this.remoteStorage) {
635
- await this.remoteStorage.clear?.(this.namespace || void 0);
712
+ await this.remoteStorage.clear?.(this.namespace ? this.namespace + ":" : void 0);
636
713
  }
714
+ this._setTagVersionCache(NAMESPACE_TAG, previousNamespace, Date.now() + this.tagVersionTtlMs);
715
+ await this._invalidateConcreteTag(NAMESPACE_TAG);
637
716
  } catch (err) {
638
717
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
639
718
  span.recordException?.(err);
@@ -647,6 +726,7 @@ var EdgeCacheService = class _EdgeCacheService {
647
726
  */
648
727
  async mget(keys, fetchFn, ttlSeconds) {
649
728
  const span = this._startSpan("tricache.mget");
729
+ const epochs = new Map(keys.map((key) => [key, this.fence(this.nk(key))]));
650
730
  span.setAttribute("cache.batch.size", keys.length);
651
731
  try {
652
732
  const results = Array.from({ length: keys.length }, () => null);
@@ -668,10 +748,10 @@ var EdgeCacheService = class _EdgeCacheService {
668
748
  const isMap = fetchedMap instanceof Map;
669
749
  for (let j = 0; j < missKeys.length; j++) {
670
750
  const k = missKeys[j];
671
- const fetchedVal = isMap ? fetchedMap.get(k) : fetchedMap[k];
751
+ const fetchedVal = isMap ? fetchedMap.get(k) : Object.hasOwn(fetchedMap, k) ? fetchedMap[k] : void 0;
672
752
  if (fetchedVal !== void 0) {
673
753
  results[missIndices[j]] = fetchedVal;
674
- await this.set(k, fetchedVal, ttlSeconds);
754
+ if (this.fence(this.nk(k)) === epochs.get(k)) await this.set(k, fetchedVal, ttlSeconds);
675
755
  }
676
756
  }
677
757
  }
@@ -733,6 +813,7 @@ var EdgeCacheService = class _EdgeCacheService {
733
813
  * }
734
814
  */
735
815
  async hydrate(source, options) {
816
+ const epoch = this.globalEpoch;
736
817
  let rawStr = null;
737
818
  if (source && typeof source === "object") {
738
819
  if ("get" in source && typeof source.get === "function") {
@@ -771,13 +852,14 @@ var EdgeCacheService = class _EdgeCacheService {
771
852
  } catch {
772
853
  return 0;
773
854
  }
774
- if (!payload || !Array.isArray(payload.entries)) {
855
+ if (!payload || payload.version !== 1 || !Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
775
856
  return 0;
776
857
  }
777
858
  const now = Date.now();
778
859
  const maxAgeMs = options?.maxAgeMs ?? 72e5;
779
860
  const tolerance = options?.clockSkewToleranceMs ?? 250;
780
861
  const writtenAt = payload.writtenAt ?? 0;
862
+ if (!Number.isFinite(writtenAt) || writtenAt < this.lastGlobalMutationAt) return 0;
781
863
  if (writtenAt - now > tolerance) {
782
864
  return 0;
783
865
  }
@@ -790,8 +872,10 @@ var EdgeCacheService = class _EdgeCacheService {
790
872
  if (!item || typeof item.key !== "string") continue;
791
873
  if (item.expiresAt <= now && item.staleUntil <= now) continue;
792
874
  const nsKey = this.nk(item.key);
875
+ if (this.l1.has(nsKey) || this.keyEpochs.has(nsKey) || !Number.isFinite(item.expiresAt) || !Number.isFinite(item.staleUntil)) continue;
793
876
  const serialized = JSON.stringify(item.value);
794
877
  const bytes = this._estimateBytes(nsKey, serialized);
878
+ if (bytes > this.maxBytes || this.maxKeys === 0) continue;
795
879
  this._deleteL1(nsKey);
796
880
  this._evictIfNeeded(bytes);
797
881
  const entry = {
@@ -816,7 +900,7 @@ var EdgeCacheService = class _EdgeCacheService {
816
900
  }
817
901
  }
818
902
  if (this.bloomFilter) {
819
- this.bloomFilter.add(item.key);
903
+ this.bloomFilter.add(nsKey);
820
904
  }
821
905
  imported++;
822
906
  }