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,46 @@
1
+ import { C as CacheService } from '../cache-service-CWI4jkS7.cjs';
2
+ import { W as WrapOptions } from '../types-BA4pz1A0.cjs';
3
+ import 'crypto';
4
+
5
+ /**
6
+ * tricache/drizzle — First-class Drizzle ORM query caching wrapper for TriCache.
7
+ *
8
+ * Usage:
9
+ * import { withCache } from 'tricache/drizzle';
10
+ *
11
+ * const activeUsers = await withCache(
12
+ * db.select().from(users).where(eq(users.active, true)),
13
+ * { cache, ttl: 300, tags: ['users'] }
14
+ * );
15
+ */
16
+
17
+ interface DrizzleCacheOptions extends WrapOptions {
18
+ /** TriCache instance to use. If omitted, uses process-level singleton `CacheService.create()`. */
19
+ cache?: CacheService;
20
+ /** Explicit cache key. If omitted, automatically derived from SHA-256 hash of `{ sql, params }`. */
21
+ key?: string;
22
+ }
23
+ interface DrizzleExecutableQuery<T> {
24
+ toSQL(): {
25
+ sql: string;
26
+ params: unknown[];
27
+ };
28
+ execute?(): Promise<T>;
29
+ then?: (onfulfilled?: (value: T) => unknown, onrejected?: (reason: unknown) => unknown) => Promise<unknown>;
30
+ }
31
+ /**
32
+ * Generate a deterministic SHA-256 hash key for a Drizzle query based on its compiled SQL and parameters.
33
+ */
34
+ declare function generateDrizzleCacheKey(sqlInfo: {
35
+ sql: string;
36
+ params: unknown[];
37
+ }): string;
38
+ /**
39
+ * Wraps a Drizzle ORM query with TriCache caching.
40
+ *
41
+ * @param query Drizzle query builder or executable query instance.
42
+ * @param options Cache options including TTL, tags, SWR, priority, and optional key.
43
+ */
44
+ declare function withCache<T>(query: DrizzleExecutableQuery<T>, options?: DrizzleCacheOptions): Promise<T>;
45
+
46
+ export { type DrizzleCacheOptions, type DrizzleExecutableQuery, generateDrizzleCacheKey, withCache };
@@ -1,5 +1,5 @@
1
- import { C as CacheService } from '../cache-service-CREOp7MM.js';
2
- import { W as WrapOptions } from '../types-Dyip5wAl.js';
1
+ import { C as CacheService } from '../cache-service-B108FzER.js';
2
+ import { W as WrapOptions } from '../types-BA4pz1A0.js';
3
3
  import 'crypto';
4
4
 
5
5
  /**
@@ -9,7 +9,7 @@ async function withCache(query, options = {}) {
9
9
  const { cache, key, ttl = 300, swr, priority, tags, dependsOn, refreshAhead, xfetchBeta, notFoundTtl } = options;
10
10
  let activeCache = cache;
11
11
  if (!activeCache) {
12
- const { CacheService } = await import("../cache-service-MG7PN6MX.js");
12
+ const { CacheService } = await import("../cache-service-GYPZFB7O.js");
13
13
  activeCache = CacheService.create();
14
14
  }
15
15
  let cacheKey = key;
@@ -210,9 +210,12 @@ var WebCryptoEncryption = class {
210
210
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
211
211
  var KEY_STAGING_OFFSET = 2e4;
212
212
  var MAX_KEY_BYTES = 512;
213
- var BLOOM_WASM_MODULE = new WebAssembly.Module(
214
- base64ToUint8Array(BLOOM_WASM_BASE64)
215
- );
213
+ var bloomWasmModule;
214
+ function getBloomWasmModule() {
215
+ return bloomWasmModule ??= new WebAssembly.Module(
216
+ base64ToUint8Array(BLOOM_WASM_BASE64)
217
+ );
218
+ }
216
219
  var WasmBloomFilter = class {
217
220
  exports;
218
221
  mem;
@@ -224,7 +227,7 @@ var WasmBloomFilter = class {
224
227
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
225
228
  _insertionCount = 0;
226
229
  constructor() {
227
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
230
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
228
231
  this.exports = instance.exports;
229
232
  this.mem = new Uint8Array(this.exports.memory.buffer);
230
233
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
@@ -438,6 +441,7 @@ function isChildTag(parentTag, candidateTag, delimiter = ":") {
438
441
  }
439
442
 
440
443
  // src/edge/cache.ts
444
+ var NAMESPACE_TAG = "_tricache_namespace_";
441
445
  var EdgeCacheService = class _EdgeCacheService {
442
446
  maxKeys;
443
447
  maxBytes;
@@ -447,6 +451,10 @@ var EdgeCacheService = class _EdgeCacheService {
447
451
  enc;
448
452
  tracer;
449
453
  bloomFilter;
454
+ bloomAuthoritative;
455
+ globalEpoch = 0;
456
+ lastGlobalMutationAt = 0;
457
+ keyEpochs = /* @__PURE__ */ new Map();
450
458
  // L1 Dual-bounded LRU
451
459
  l1 = /* @__PURE__ */ new Map();
452
460
  currentBytes = 0;
@@ -466,6 +474,8 @@ var EdgeCacheService = class _EdgeCacheService {
466
474
  this.remoteStorage = options?.remoteStorage ?? null;
467
475
  this.tracer = options?.tracer ?? null;
468
476
  this.enc = new WebCryptoEncryption(options?.encryption);
477
+ this.bloomAuthoritative = options?.bloomFilterAuthoritative ?? false;
478
+ 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");
469
479
  if (options?.bloomFilter === true) {
470
480
  try {
471
481
  this.bloomFilter = new WasmBloomFilter();
@@ -490,6 +500,66 @@ var EdgeCacheService = class _EdgeCacheService {
490
500
  _estimateBytes(key, serialized) {
491
501
  return (key.length + serialized.length) * 2 + 64;
492
502
  }
503
+ fence(key) {
504
+ return `${this.globalEpoch}:${this.keyEpochs.get(key) ?? 0}`;
505
+ }
506
+ mutate(key) {
507
+ this.keyEpochs.set(key, (this.keyEpochs.get(key) ?? 0) + 1);
508
+ this.inflight.delete(key);
509
+ if (this.keyEpochs.size > 5e4) {
510
+ this.globalEpoch++;
511
+ this.keyEpochs.clear();
512
+ }
513
+ }
514
+ invalidateWork() {
515
+ this.globalEpoch++;
516
+ this.lastGlobalMutationAt = Date.now();
517
+ this.inflight.clear();
518
+ }
519
+ storeL1(key, entry) {
520
+ this._deleteL1(key);
521
+ if (entry.bytes > this.maxBytes || this.maxKeys === 0 || entry.staleUntil <= Date.now()) return false;
522
+ this._evictIfNeeded(entry.bytes);
523
+ this.l1.set(key, entry);
524
+ this.currentBytes += entry.bytes;
525
+ for (const tag of entry.tags ?? []) {
526
+ const members = this.tagIndex.get(tag) ?? /* @__PURE__ */ new Set();
527
+ members.add(key);
528
+ this.tagIndex.set(tag, members);
529
+ }
530
+ this.bloomFilter?.add(key);
531
+ return true;
532
+ }
533
+ async commit(key, value, ttl, options, versions, epoch) {
534
+ const namespaced = this.nk(key);
535
+ if (this.fence(namespaced) !== epoch) return;
536
+ const serialized = JSON.stringify(value);
537
+ if (serialized === void 0) return;
538
+ const now = Date.now();
539
+ const entry = {
540
+ value,
541
+ serialized,
542
+ bytes: this._estimateBytes(namespaced, serialized),
543
+ expiresAt: now + ttl * 1e3,
544
+ staleUntil: now + (ttl + (options?.swr ?? 0)) * 1e3,
545
+ tags: options?.tags ? [...new Set(options.tags)] : void 0,
546
+ tagVersions: versions
547
+ };
548
+ this.storeL1(namespaced, entry);
549
+ if (this.remoteStorage) {
550
+ const envelope = JSON.stringify({
551
+ __t_edge: 2,
552
+ __t_val: value,
553
+ __t_tv: versions,
554
+ __t_exp: entry.expiresAt,
555
+ __t_stale: entry.staleUntil,
556
+ __t_tags: entry.tags
557
+ });
558
+ const payload = this.enc.isEnabled ? await this.enc.encrypt(envelope) : envelope;
559
+ if (this.fence(namespaced) !== epoch) return;
560
+ await this.remoteStorage.set(namespaced, payload, ttl + (options?.swr ?? 0));
561
+ }
562
+ }
493
563
  _evictIfNeeded(newBytes) {
494
564
  while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
495
565
  const oldestKey = this.l1.keys().next().value;
@@ -551,7 +621,8 @@ var EdgeCacheService = class _EdgeCacheService {
551
621
  if (oldestKey !== void 0) this.tagVersionCache.delete(oldestKey);
552
622
  }
553
623
  }
554
- this.tagVersionCache.set(tag, { version, expiresAt });
624
+ const known = this.tagVersionCache.get(tag)?.version ?? 0;
625
+ this.tagVersionCache.set(tag, { version: Math.max(known, version), expiresAt });
555
626
  }
556
627
  async _getTagVersion(tag) {
557
628
  const cached = this.tagVersionCache.get(tag);
@@ -575,11 +646,11 @@ var EdgeCacheService = class _EdgeCacheService {
575
646
  version = cached?.version ?? 1;
576
647
  }
577
648
  this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
578
- return version;
649
+ return this.tagVersionCache.get(tag)?.version ?? version;
579
650
  }
580
651
  async _batchGetTagVersions(tags) {
581
652
  const now = Date.now();
582
- const result = {};
653
+ const result = /* @__PURE__ */ Object.create(null);
583
654
  const missingTags = [];
584
655
  for (const t of tags) {
585
656
  const c = this.tagVersionCache.get(t);
@@ -597,7 +668,7 @@ var EdgeCacheService = class _EdgeCacheService {
597
668
  for (let i = 0; i < missingTags.length; i++) {
598
669
  const t = missingTags[i];
599
670
  const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
600
- result[t] = v;
671
+ result[t] = Math.max(this.tagVersionCache.get(t)?.version ?? 0, v);
601
672
  this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
602
673
  }
603
674
  } else {
@@ -625,7 +696,7 @@ var EdgeCacheService = class _EdgeCacheService {
625
696
  const span = this._startSpan("tricache.get");
626
697
  span.setAttribute("cache.key", key);
627
698
  const nsKey = this.nk(key);
628
- const now = Date.now();
699
+ let now = Date.now();
629
700
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
630
701
  try {
631
702
  const l1Entry = this.l1.get(nsKey);
@@ -641,6 +712,7 @@ var EdgeCacheService = class _EdgeCacheService {
641
712
  }
642
713
  }
643
714
  }
715
+ now = Date.now();
644
716
  if (isTagStale) {
645
717
  this._deleteL1(nsKey);
646
718
  } else {
@@ -652,85 +724,115 @@ var EdgeCacheService = class _EdgeCacheService {
652
724
  span.setAttribute("cache.hit_tier", "l1");
653
725
  return l1Entry.value;
654
726
  }
655
- if (l1Entry.staleUntil > now && fetchFn) {
727
+ if (l1Entry.staleUntil > now && fetchFn && (options?.swr ?? 0) > 0) {
656
728
  span.setAttribute("cache.hit", true);
657
729
  span.setAttribute("cache.item.tier", "memory");
658
730
  span.setAttribute("cache.hit_tier", "l1");
659
731
  span.setAttribute("cache.stale", true);
660
- const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
732
+ const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: options?.tags ?? l1Entry.tags });
661
733
  if (options?.ctx?.waitUntil) {
662
734
  options.ctx.waitUntil(revalPromise);
663
735
  }
664
736
  return l1Entry.value;
665
737
  }
666
- this._deleteL1(nsKey);
738
+ if (l1Entry.staleUntil <= now) this._deleteL1(nsKey);
667
739
  }
668
740
  }
669
- if (this.remoteStorage) {
670
- if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
671
- span.setAttribute("cache.bloom.filtered", true);
672
- } else {
673
- try {
674
- const rawRemote = await this.remoteStorage.get(nsKey);
675
- if (rawRemote !== null) {
676
- const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
677
- const parsedJson = JSON.parse(plain);
678
- let parsed;
679
- let activeTagVersions;
680
- let isStaleRemote = false;
681
- if (parsedJson && typeof parsedJson === "object" && "__t_val" in parsedJson && "__t_tv" in parsedJson) {
682
- parsed = parsedJson.__t_val;
683
- activeTagVersions = parsedJson.__t_tv;
684
- const tagNames = Object.keys(activeTagVersions);
685
- const currentVers = await this._batchGetTagVersions(tagNames);
686
- for (const tag of tagNames) {
687
- if (currentVers[tag] > activeTagVersions[tag]) {
688
- isStaleRemote = true;
689
- break;
741
+ const existing = this.inflight.get(nsKey);
742
+ if (existing) {
743
+ span.setAttribute("cache.stampede_coalesced", true);
744
+ return await existing;
745
+ }
746
+ const epoch = this.fence(nsKey);
747
+ const execution = Promise.resolve().then(async () => {
748
+ try {
749
+ if (this.remoteStorage) {
750
+ if (this.bloomAuthoritative && this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
751
+ span.setAttribute("cache.bloom.filtered", true);
752
+ } else {
753
+ try {
754
+ const rawRemote = await this.remoteStorage.get(nsKey);
755
+ if (rawRemote !== null) {
756
+ const plain = this.enc.isEnabled ? await this.enc.decrypt(rawRemote) : rawRemote;
757
+ const parsedJson = JSON.parse(plain);
758
+ let parsed;
759
+ let activeTagVersions;
760
+ let isStaleRemote = false;
761
+ if (parsedJson && typeof parsedJson === "object" && "__t_val" in parsedJson && "__t_tv" in parsedJson) {
762
+ parsed = parsedJson.__t_val;
763
+ activeTagVersions = parsedJson.__t_tv;
764
+ 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");
765
+ const tagNames = Object.keys(activeTagVersions);
766
+ const currentVers = await this._batchGetTagVersions(tagNames);
767
+ for (const tag of tagNames) {
768
+ if (currentVers[tag] > activeTagVersions[tag]) {
769
+ isStaleRemote = true;
770
+ break;
771
+ }
772
+ }
773
+ } else {
774
+ parsed = parsedJson;
775
+ }
776
+ if (!isStaleRemote) {
777
+ const freshUntil = Number(parsedJson?.__t_exp);
778
+ const staleUntil = Number(parsedJson?.__t_stale);
779
+ const versioned = parsedJson?.__t_edge === 2 && Number.isFinite(freshUntil) && Number.isFinite(staleUntil) && staleUntil >= freshUntil;
780
+ if (versioned && (staleUntil <= Date.now() || freshUntil <= Date.now() && (!(options?.swr ?? 0) || !fetchFn))) {
781
+ isStaleRemote = true;
782
+ } else {
783
+ if (versioned && this.fence(nsKey) === epoch) {
784
+ const serialized = JSON.stringify(parsed);
785
+ const tags2 = Array.isArray(parsedJson.__t_tags) ? parsedJson.__t_tags : Object.keys(activeTagVersions ?? {}).filter((tag) => tag !== NAMESPACE_TAG);
786
+ this.storeL1(nsKey, {
787
+ value: parsed,
788
+ serialized,
789
+ bytes: this._estimateBytes(nsKey, serialized),
790
+ expiresAt: freshUntil,
791
+ staleUntil,
792
+ tags: tags2,
793
+ tagVersions: activeTagVersions
794
+ });
795
+ if (freshUntil <= Date.now() && fetchFn) {
796
+ const refresh = execution.then(() => this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: tags2 }));
797
+ options?.ctx?.waitUntil(refresh);
798
+ }
799
+ }
800
+ span.setAttribute("cache.hit", true);
801
+ span.setAttribute("cache.item.tier", "remote");
802
+ span.setAttribute("cache.hit_tier", "l2");
803
+ return parsed;
804
+ }
690
805
  }
691
806
  }
692
- } else {
693
- parsed = parsedJson;
694
- }
695
- if (!isStaleRemote) {
696
- await this.set(key, parsed, resolvedTtl, options);
697
- span.setAttribute("cache.hit", true);
698
- span.setAttribute("cache.item.tier", "remote");
699
- span.setAttribute("cache.hit_tier", "l2");
700
- return parsed;
807
+ } catch (remoteErr) {
808
+ span.recordException?.(remoteErr);
701
809
  }
702
810
  }
703
- } catch (remoteErr) {
704
- span.recordException?.(remoteErr);
705
811
  }
706
- }
707
- }
708
- if (!fetchFn) {
709
- span.setAttribute("cache.hit", false);
710
- span.setAttribute("cache.hit_tier", "miss");
711
- return null;
712
- }
713
- let inflightPromise = this.inflight.get(nsKey);
714
- let coalesced = false;
715
- if (inflightPromise) {
716
- coalesced = true;
717
- } else {
718
- inflightPromise = (async () => {
719
- try {
720
- const fresh = await fetchFn();
721
- await this.set(key, fresh, resolvedTtl, options);
722
- return fresh;
723
- } finally {
724
- this.inflight.delete(nsKey);
812
+ if (!fetchFn) {
813
+ span.setAttribute("cache.hit", false);
814
+ span.setAttribute("cache.hit_tier", "miss");
815
+ return null;
725
816
  }
726
- })();
727
- this.inflight.set(nsKey, inflightPromise);
728
- }
729
- span.setAttribute("cache.hit", coalesced);
730
- span.setAttribute("cache.hit_tier", coalesced ? "l1" : "miss");
731
- span.setAttribute("cache.stampede_coalesced", coalesced);
732
- const result = await inflightPromise;
733
- return result;
817
+ const tags = [.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
818
+ const versions = await this._batchGetTagVersions(tags);
819
+ const fresh = await fetchFn();
820
+ const current = await this._batchGetTagVersions(tags);
821
+ if (this.fence(nsKey) === epoch && tags.every((tag) => current[tag] === versions[tag])) {
822
+ try {
823
+ await this.commit(key, fresh, resolvedTtl, options, versions, epoch);
824
+ } catch (error) {
825
+ span.recordException?.(error);
826
+ }
827
+ }
828
+ span.setAttribute("cache.hit", false).setAttribute("cache.hit_tier", "miss");
829
+ return fresh;
830
+ } finally {
831
+ if (this.inflight.get(nsKey) === execution) this.inflight.delete(nsKey);
832
+ }
833
+ });
834
+ this.inflight.set(nsKey, execution);
835
+ return await execution;
734
836
  } catch (err) {
735
837
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
736
838
  span.recordException?.(err);
@@ -742,15 +844,19 @@ var EdgeCacheService = class _EdgeCacheService {
742
844
  async _revalidate(key, fetchFn, ttl, options) {
743
845
  const nsKey = this.nk(key);
744
846
  if (this.inflight.has(nsKey)) return;
745
- const task = (async () => {
847
+ const epoch = this.fence(nsKey);
848
+ const task = Promise.resolve().then(async () => {
746
849
  try {
850
+ const tags = [.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
851
+ const versions = await this._batchGetTagVersions(tags);
747
852
  const fresh = await fetchFn();
748
- await this.set(key, fresh, ttl, options);
853
+ const current = await this._batchGetTagVersions(tags);
854
+ if (this.fence(nsKey) === epoch && tags.every((tag) => current[tag] === versions[tag])) await this.commit(key, fresh, ttl, options, versions, epoch);
749
855
  } catch {
750
856
  } finally {
751
- this.inflight.delete(nsKey);
857
+ if (this.inflight.get(nsKey) === task) this.inflight.delete(nsKey);
752
858
  }
753
- })();
859
+ });
754
860
  this.inflight.set(nsKey, task);
755
861
  await task;
756
862
  }
@@ -761,48 +867,15 @@ var EdgeCacheService = class _EdgeCacheService {
761
867
  const span = this._startSpan("tricache.set");
762
868
  span.setAttribute("cache.key", key);
763
869
  const nsKey = this.nk(key);
870
+ this.mutate(nsKey);
871
+ const epoch = this.fence(nsKey);
764
872
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
765
- const now = Date.now();
766
873
  const optObj = Array.isArray(options) ? { tags: options } : options;
767
874
  const swrSeconds = optObj?.swr ?? 0;
768
875
  try {
769
- let activeTagVersions;
770
- if (optObj?.tags?.length) {
771
- activeTagVersions = await this._batchGetTagVersions(optObj.tags);
772
- }
773
- const serialized = JSON.stringify(value);
774
- const bytes = this._estimateBytes(nsKey, serialized);
775
- this._deleteL1(nsKey);
776
- this._evictIfNeeded(bytes);
777
- const entry = {
778
- value,
779
- serialized,
780
- bytes,
781
- expiresAt: now + resolvedTtl * 1e3,
782
- staleUntil: now + (resolvedTtl + swrSeconds) * 1e3,
783
- tags: optObj?.tags,
784
- tagVersions: activeTagVersions
785
- };
786
- this.l1.set(nsKey, entry);
787
- this.currentBytes += bytes;
788
- if (optObj?.tags) {
789
- for (const tag of optObj.tags) {
790
- let s = this.tagIndex.get(tag);
791
- if (!s) {
792
- s = /* @__PURE__ */ new Set();
793
- this.tagIndex.set(tag, s);
794
- }
795
- s.add(nsKey);
796
- }
797
- }
798
- if (this.remoteStorage) {
799
- const toStoreRaw = activeTagVersions ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions }) : serialized;
800
- const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
801
- await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
802
- }
803
- if (this.bloomFilter) {
804
- this.bloomFilter.add(nsKey);
805
- }
876
+ if (!Number.isFinite(resolvedTtl) || resolvedTtl < 0 || !Number.isFinite(swrSeconds) || swrSeconds < 0) throw new Error("Edge TTL and SWR must be finite non-negative values");
877
+ const versions = await this._batchGetTagVersions([.../* @__PURE__ */ new Set([NAMESPACE_TAG, ...optObj?.tags ?? []])]);
878
+ await this.commit(key, value, resolvedTtl, optObj, versions, epoch);
806
879
  } catch (err) {
807
880
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
808
881
  span.recordException?.(err);
@@ -819,6 +892,7 @@ var EdgeCacheService = class _EdgeCacheService {
819
892
  span.setAttribute("cache.key", key);
820
893
  const nsKey = this.nk(key);
821
894
  try {
895
+ this.mutate(nsKey);
822
896
  this._deleteL1(nsKey);
823
897
  if (this.remoteStorage) {
824
898
  await this.remoteStorage.delete(nsKey);
@@ -836,11 +910,15 @@ var EdgeCacheService = class _EdgeCacheService {
836
910
  * re-entering wildcard/cascade resolution.
837
911
  */
838
912
  async _invalidateConcreteTag(tag) {
913
+ this.invalidateWork();
914
+ const previous = this.tagVersionCache.get(tag)?.version ?? 1;
839
915
  let newVer = 1;
840
916
  if (this.remoteStorage) {
841
917
  try {
842
918
  if (typeof this.remoteStorage.incrementTagVersion === "function") {
843
919
  newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
920
+ if (newVer <= previous) newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
921
+ newVer = Math.max(previous + 1, newVer);
844
922
  } else {
845
923
  const key = this.nk(`tag_ver:${tag}`);
846
924
  const current = await this._getTagVersion(tag);
@@ -855,7 +933,7 @@ var EdgeCacheService = class _EdgeCacheService {
855
933
  const current = this.tagVersionCache.get(tag)?.version ?? 1;
856
934
  newVer = current + 1;
857
935
  }
858
- this._setTagVersionCache(tag, newVer, Date.now() + 6e4);
936
+ this._setTagVersionCache(tag, newVer, Date.now() + this.tagVersionTtlMs);
859
937
  const keys = this.tagIndex.get(tag);
860
938
  if (keys) {
861
939
  const keysArr = Array.from(keys);
@@ -910,6 +988,8 @@ var EdgeCacheService = class _EdgeCacheService {
910
988
  async clear() {
911
989
  const span = this._startSpan("tricache.clear");
912
990
  try {
991
+ const previousNamespace = await this._getTagVersion(NAMESPACE_TAG);
992
+ this.invalidateWork();
913
993
  this.l1.clear();
914
994
  this.currentBytes = 0;
915
995
  this.tagIndex.clear();
@@ -918,8 +998,10 @@ var EdgeCacheService = class _EdgeCacheService {
918
998
  this.bloomFilter.reset();
919
999
  }
920
1000
  if (this.remoteStorage) {
921
- await this.remoteStorage.clear?.(this.namespace || void 0);
1001
+ await this.remoteStorage.clear?.(this.namespace ? this.namespace + ":" : void 0);
922
1002
  }
1003
+ this._setTagVersionCache(NAMESPACE_TAG, previousNamespace, Date.now() + this.tagVersionTtlMs);
1004
+ await this._invalidateConcreteTag(NAMESPACE_TAG);
923
1005
  } catch (err) {
924
1006
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
925
1007
  span.recordException?.(err);
@@ -933,6 +1015,7 @@ var EdgeCacheService = class _EdgeCacheService {
933
1015
  */
934
1016
  async mget(keys, fetchFn, ttlSeconds) {
935
1017
  const span = this._startSpan("tricache.mget");
1018
+ const epochs = new Map(keys.map((key) => [key, this.fence(this.nk(key))]));
936
1019
  span.setAttribute("cache.batch.size", keys.length);
937
1020
  try {
938
1021
  const results = Array.from({ length: keys.length }, () => null);
@@ -954,10 +1037,10 @@ var EdgeCacheService = class _EdgeCacheService {
954
1037
  const isMap = fetchedMap instanceof Map;
955
1038
  for (let j = 0; j < missKeys.length; j++) {
956
1039
  const k = missKeys[j];
957
- const fetchedVal = isMap ? fetchedMap.get(k) : fetchedMap[k];
1040
+ const fetchedVal = isMap ? fetchedMap.get(k) : Object.hasOwn(fetchedMap, k) ? fetchedMap[k] : void 0;
958
1041
  if (fetchedVal !== void 0) {
959
1042
  results[missIndices[j]] = fetchedVal;
960
- await this.set(k, fetchedVal, ttlSeconds);
1043
+ if (this.fence(this.nk(k)) === epochs.get(k)) await this.set(k, fetchedVal, ttlSeconds);
961
1044
  }
962
1045
  }
963
1046
  }
@@ -1019,6 +1102,7 @@ var EdgeCacheService = class _EdgeCacheService {
1019
1102
  * }
1020
1103
  */
1021
1104
  async hydrate(source, options) {
1105
+ const epoch = this.globalEpoch;
1022
1106
  let rawStr = null;
1023
1107
  if (source && typeof source === "object") {
1024
1108
  if ("get" in source && typeof source.get === "function") {
@@ -1057,13 +1141,14 @@ var EdgeCacheService = class _EdgeCacheService {
1057
1141
  } catch {
1058
1142
  return 0;
1059
1143
  }
1060
- if (!payload || !Array.isArray(payload.entries)) {
1144
+ if (!payload || payload.version !== 1 || !Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
1061
1145
  return 0;
1062
1146
  }
1063
1147
  const now = Date.now();
1064
1148
  const maxAgeMs = options?.maxAgeMs ?? 72e5;
1065
1149
  const tolerance = options?.clockSkewToleranceMs ?? 250;
1066
1150
  const writtenAt = payload.writtenAt ?? 0;
1151
+ if (!Number.isFinite(writtenAt) || writtenAt < this.lastGlobalMutationAt) return 0;
1067
1152
  if (writtenAt - now > tolerance) {
1068
1153
  return 0;
1069
1154
  }
@@ -1076,8 +1161,10 @@ var EdgeCacheService = class _EdgeCacheService {
1076
1161
  if (!item || typeof item.key !== "string") continue;
1077
1162
  if (item.expiresAt <= now && item.staleUntil <= now) continue;
1078
1163
  const nsKey = this.nk(item.key);
1164
+ if (this.l1.has(nsKey) || this.keyEpochs.has(nsKey) || !Number.isFinite(item.expiresAt) || !Number.isFinite(item.staleUntil)) continue;
1079
1165
  const serialized = JSON.stringify(item.value);
1080
1166
  const bytes = this._estimateBytes(nsKey, serialized);
1167
+ if (bytes > this.maxBytes || this.maxKeys === 0) continue;
1081
1168
  this._deleteL1(nsKey);
1082
1169
  this._evictIfNeeded(bytes);
1083
1170
  const entry = {
@@ -1102,7 +1189,7 @@ var EdgeCacheService = class _EdgeCacheService {
1102
1189
  }
1103
1190
  }
1104
1191
  if (this.bloomFilter) {
1105
- this.bloomFilter.add(item.key);
1192
+ this.bloomFilter.add(nsKey);
1106
1193
  }
1107
1194
  imported++;
1108
1195
  }
@@ -1496,7 +1583,6 @@ function honoEdgeCache(options = {}) {
1496
1583
  cache,
1497
1584
  etag = true,
1498
1585
  ttl = 300,
1499
- swr,
1500
1586
  tags,
1501
1587
  skipCache,
1502
1588
  keyGenerator,
@@ -1510,6 +1596,8 @@ function honoEdgeCache(options = {}) {
1510
1596
  if (skipCache && skipCache(c)) {
1511
1597
  return await next();
1512
1598
  }
1599
+ const credentials = ["authorization", "cookie", "x-api-key", "x-auth-token"].filter((name) => c.req.header?.(name));
1600
+ if (c.req.header?.("range") || credentials.length > 0 && (!options.cacheAuthenticated || !keyGenerator && !credentials.every((name) => headerWhitelist?.some((header) => header.toLowerCase() === name)))) return await next();
1513
1601
  const cc = c.req.header?.("cache-control") || c.req.header?.("Cache-Control");
1514
1602
  if (typeof cc === "string") {
1515
1603
  const lower = cc.toLowerCase();
@@ -1520,7 +1608,12 @@ function honoEdgeCache(options = {}) {
1520
1608
  if (!cache) {
1521
1609
  return await next();
1522
1610
  }
1523
- const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
1611
+ let key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
1612
+ if (credentials.length) {
1613
+ if (!globalThis.crypto?.subtle) return await next();
1614
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
1615
+ key = `edge:http:identity:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
1616
+ }
1524
1617
  const ifNoneMatch = c.req.header?.("if-none-match") || c.req.header?.("If-None-Match");
1525
1618
  const resolvedTags = typeof tags === "function" ? tags(c) : tags;
1526
1619
  let ranNext = false;
@@ -1543,6 +1636,10 @@ function honoEdgeCache(options = {}) {
1543
1636
  });
1544
1637
  }
1545
1638
  const cc2 = res.headers?.get?.("cache-control");
1639
+ const vary = String(res.headers?.get?.("vary") ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
1640
+ if (res.headers?.get?.("set-cookie") || vary.includes("*") || !keyGenerator && vary.some((name) => !headerWhitelist?.some((header) => header.toLowerCase() === name))) {
1641
+ throw new NonCacheableEdgeResponseError({ body: "", contentType, status: 0 });
1642
+ }
1546
1643
  if (cc2) {
1547
1644
  const lowerCc = cc2.toLowerCase();
1548
1645
  if (lowerCc.includes("no-store") || lowerCc.includes("no-cache") || lowerCc.includes("private")) {
@@ -1584,9 +1681,9 @@ function honoEdgeCache(options = {}) {
1584
1681
  },
1585
1682
  ttl,
1586
1683
  {
1587
- swr,
1684
+ swr: 0,
1588
1685
  tags: resolvedTags,
1589
- ctx: c.executionCtx
1686
+ ctx: readExecutionContext(c)
1590
1687
  }
1591
1688
  );
1592
1689
  if (!cached) {
@@ -1613,6 +1710,13 @@ function honoEdgeCache(options = {}) {
1613
1710
  }
1614
1711
  };
1615
1712
  }
1713
+ function readExecutionContext(c) {
1714
+ try {
1715
+ return c.executionCtx;
1716
+ } catch {
1717
+ return void 0;
1718
+ }
1719
+ }
1616
1720
  function applyEdgeResponse(c, body, status, headers) {
1617
1721
  const response = c.body(body, status, headers);
1618
1722
  c.res = response;