tricache 1.0.0 → 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 (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.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-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  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 +1757 -773
  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 +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  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-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  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 +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  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-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -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 +123 -25
  61. package/src/cache-service.ts +1238 -659
  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 +202 -129
  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 +110 -26
  74. package/src/http/fastify.ts +38 -28
  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 +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
package/src/edge/cache.ts CHANGED
@@ -25,6 +25,8 @@ interface EdgeL1Entry<T = unknown> {
25
25
  tagVersions?: Record<string, number>;
26
26
  }
27
27
 
28
+ const NAMESPACE_TAG = '_tricache_namespace_';
29
+
28
30
  /**
29
31
  * Enterprise-grade cache service designed specifically for pure V8 Edge Isolates
30
32
  * (Cloudflare Workers, Fastly Compute, Vercel Edge, Next.js Edge Runtime, Deno).
@@ -46,6 +48,10 @@ export class EdgeCacheService {
46
48
  private readonly enc: WebCryptoEncryption;
47
49
  private readonly tracer: ICacheTracer | null;
48
50
  private readonly bloomFilter: IEdgeBloomFilter | null;
51
+ private readonly bloomAuthoritative: boolean;
52
+ private globalEpoch = 0;
53
+ private lastGlobalMutationAt = 0;
54
+ private readonly keyEpochs = new Map<string, number>();
49
55
 
50
56
  // L1 Dual-bounded LRU
51
57
  private readonly l1 = new Map<string, EdgeL1Entry>();
@@ -58,6 +64,7 @@ export class EdgeCacheService {
58
64
  private readonly tagIndex = new Map<string, Set<string>>();
59
65
 
60
66
  // Tag version in-isolate cache with 800ms micro-TTL (prevents HTTP fetch amplification on L1 hits)
67
+ private static readonly MAX_TAG_VERSION_CACHE = 10_000;
61
68
  private readonly tagVersionCache = new Map<string, { version: number; expiresAt: number }>();
62
69
  private readonly tagVersionTtlMs = 800;
63
70
 
@@ -69,6 +76,9 @@ export class EdgeCacheService {
69
76
  this.remoteStorage = options?.remoteStorage ?? null;
70
77
  this.tracer = options?.tracer ?? null;
71
78
  this.enc = new WebCryptoEncryption(options?.encryption);
79
+ this.bloomAuthoritative = options?.bloomFilterAuthoritative ?? false;
80
+ if (!Number.isInteger(this.maxKeys) || this.maxKeys < 0 || !Number.isFinite(this.maxBytes) || this.maxBytes < 0 ||
81
+ !Number.isFinite(this.defaultTtl) || this.defaultTtl < 0) throw new Error('Edge cache limits and TTL must be finite non-negative values');
72
82
 
73
83
  if (options?.bloomFilter === true) {
74
84
  try {
@@ -99,6 +109,53 @@ export class EdgeCacheService {
99
109
  return (key.length + serialized.length) * 2 + 64;
100
110
  }
101
111
 
112
+ private fence(key: string): string { return `${this.globalEpoch}:${this.keyEpochs.get(key) ?? 0}`; }
113
+ private mutate(key: string): void {
114
+ this.keyEpochs.set(key, (this.keyEpochs.get(key) ?? 0) + 1);
115
+ this.inflight.delete(key);
116
+ if (this.keyEpochs.size > 50000) { this.globalEpoch++; this.keyEpochs.clear(); }
117
+ }
118
+ private invalidateWork(): void {
119
+ this.globalEpoch++;
120
+ this.lastGlobalMutationAt = Date.now();
121
+ this.inflight.clear();
122
+ }
123
+
124
+ private storeL1(key: string, entry: EdgeL1Entry): boolean {
125
+ this._deleteL1(key);
126
+ if (entry.bytes > this.maxBytes || this.maxKeys === 0 || entry.staleUntil <= Date.now()) return false;
127
+ this._evictIfNeeded(entry.bytes);
128
+ this.l1.set(key, entry);
129
+ this.currentBytes += entry.bytes;
130
+ for (const tag of entry.tags ?? []) {
131
+ const members = this.tagIndex.get(tag) ?? new Set<string>();
132
+ members.add(key);
133
+ this.tagIndex.set(tag, members);
134
+ }
135
+ this.bloomFilter?.add(key);
136
+ return true;
137
+ }
138
+
139
+ private async commit<T>(key: string, value: T, ttl: number, options: EdgeGetOptions | undefined,
140
+ versions: Record<string, number>, epoch: string): Promise<void> {
141
+ const namespaced = this.nk(key);
142
+ if (this.fence(namespaced) !== epoch) return;
143
+ const serialized = JSON.stringify(value);
144
+ if (serialized === undefined) return; // Undefined is not a JSON cache value.
145
+ const now = Date.now();
146
+ const entry: EdgeL1Entry<T> = { value, serialized, bytes: this._estimateBytes(namespaced, serialized),
147
+ expiresAt: now + ttl * 1000, staleUntil: now + (ttl + (options?.swr ?? 0)) * 1000,
148
+ tags: options?.tags ? [...new Set(options.tags)] : undefined, tagVersions: versions };
149
+ this.storeL1(namespaced, entry);
150
+ if (this.remoteStorage) {
151
+ const envelope = JSON.stringify({ __t_edge: 2, __t_val: value, __t_tv: versions, __t_exp: entry.expiresAt,
152
+ __t_stale: entry.staleUntil, __t_tags: entry.tags });
153
+ const payload = this.enc.isEnabled ? await this.enc.encrypt(envelope) : envelope;
154
+ if (this.fence(namespaced) !== epoch) return;
155
+ await this.remoteStorage.set(namespaced, payload, ttl + (options?.swr ?? 0));
156
+ }
157
+ }
158
+
102
159
  private _evictIfNeeded(newBytes: number): void {
103
160
  // 1. Evict based on byte ceiling
104
161
  while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
@@ -147,6 +204,23 @@ export class EdgeCacheService {
147
204
  };
148
205
  }
149
206
 
207
+ private _setTagVersionCache(tag: string, version: number, expiresAt: number): void {
208
+ if (this.tagVersionCache.size >= EdgeCacheService.MAX_TAG_VERSION_CACHE && !this.tagVersionCache.has(tag)) {
209
+ const now = Date.now();
210
+ for (const [k, v] of this.tagVersionCache) {
211
+ if (v.expiresAt <= now) {
212
+ this.tagVersionCache.delete(k);
213
+ }
214
+ }
215
+ if (this.tagVersionCache.size >= EdgeCacheService.MAX_TAG_VERSION_CACHE) {
216
+ const oldestKey = this.tagVersionCache.keys().next().value;
217
+ if (oldestKey !== undefined) this.tagVersionCache.delete(oldestKey);
218
+ }
219
+ }
220
+ const known = this.tagVersionCache.get(tag)?.version ?? 0;
221
+ this.tagVersionCache.set(tag, { version: Math.max(known, version), expiresAt });
222
+ }
223
+
150
224
  private async _getTagVersion(tag: string): Promise<number> {
151
225
  const cached = this.tagVersionCache.get(tag);
152
226
  const now = Date.now();
@@ -168,13 +242,13 @@ export class EdgeCacheService {
168
242
  } else {
169
243
  version = cached?.version ?? 1;
170
244
  }
171
- this.tagVersionCache.set(tag, { version, expiresAt: now + this.tagVersionTtlMs });
172
- return version;
245
+ this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
246
+ return this.tagVersionCache.get(tag)?.version ?? version;
173
247
  }
174
248
 
175
249
  private async _batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
176
250
  const now = Date.now();
177
- const result: Record<string, number> = {};
251
+ const result: Record<string, number> = Object.create(null);
178
252
  const missingTags: string[] = [];
179
253
 
180
254
  for (const t of tags) {
@@ -194,8 +268,8 @@ export class EdgeCacheService {
194
268
  for (let i = 0; i < missingTags.length; i++) {
195
269
  const t = missingTags[i];
196
270
  const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
197
- result[t] = v;
198
- this.tagVersionCache.set(t, { version: v, expiresAt: now + this.tagVersionTtlMs });
271
+ result[t] = Math.max(this.tagVersionCache.get(t)?.version ?? 0, v);
272
+ this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
199
273
  }
200
274
  } else {
201
275
  await Promise.all(missingTags.map(async t => {
@@ -229,7 +303,7 @@ export class EdgeCacheService {
229
303
  const span = this._startSpan('tricache.get');
230
304
  span.setAttribute('cache.key', key);
231
305
  const nsKey = this.nk(key);
232
- const now = Date.now();
306
+ let now = Date.now();
233
307
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
234
308
 
235
309
  try {
@@ -248,6 +322,7 @@ export class EdgeCacheService {
248
322
  }
249
323
  }
250
324
  }
325
+ now = Date.now();
251
326
 
252
327
  if (isTagStale) {
253
328
  this._deleteL1(nsKey);
@@ -264,14 +339,14 @@ export class EdgeCacheService {
264
339
  return l1Entry.value as T;
265
340
  }
266
341
 
267
- if (l1Entry.staleUntil > now && fetchFn) {
342
+ if (l1Entry.staleUntil > now && fetchFn && (options?.swr ?? 0) > 0) {
268
343
  // Stale hit — trigger background revalidation
269
344
  span.setAttribute('cache.hit', true);
270
345
  span.setAttribute('cache.item.tier', 'memory');
271
346
  span.setAttribute('cache.hit_tier', 'l1');
272
347
  span.setAttribute('cache.stale', true);
273
348
 
274
- const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
349
+ const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: options?.tags ?? l1Entry.tags });
275
350
  if (options?.ctx?.waitUntil) {
276
351
  options.ctx.waitUntil(revalPromise);
277
352
  }
@@ -279,13 +354,21 @@ export class EdgeCacheService {
279
354
  }
280
355
 
281
356
  // Hard expired in L1
282
- this._deleteL1(nsKey);
357
+ if (l1Entry.staleUntil <= now) this._deleteL1(nsKey);
283
358
  }
284
359
  }
285
360
 
286
- // 2. Check L2 Remote Storage (defended by Bloom filter against cold-miss penetration)
361
+ const existing = this.inflight.get(nsKey);
362
+ if (existing) {
363
+ span.setAttribute('cache.stampede_coalesced', true);
364
+ return await existing as T;
365
+ }
366
+ const epoch = this.fence(nsKey);
367
+ const execution: Promise<T | null> = Promise.resolve().then(async () => {
368
+ try {
369
+ // A local Bloom filter cannot prove that another isolate's remote key is absent.
287
370
  if (this.remoteStorage) {
288
- if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
371
+ if (this.bloomAuthoritative && this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
289
372
  span.setAttribute('cache.bloom.filtered', true);
290
373
  } else {
291
374
  try {
@@ -300,6 +383,8 @@ export class EdgeCacheService {
300
383
  if (parsedJson && typeof parsedJson === 'object' && '__t_val' in parsedJson && '__t_tv' in parsedJson) {
301
384
  parsed = parsedJson.__t_val as T;
302
385
  activeTagVersions = parsedJson.__t_tv as Record<string, number>;
386
+ if (!activeTagVersions || typeof activeTagVersions !== 'object' || Array.isArray(activeTagVersions) ||
387
+ Object.values(activeTagVersions).some(version => !Number.isSafeInteger(version) || version < 0)) throw new Error('Invalid remote tag versions');
303
388
  const tagNames = Object.keys(activeTagVersions);
304
389
  const currentVers = await this._batchGetTagVersions(tagNames);
305
390
  for (const tag of tagNames) {
@@ -313,13 +398,30 @@ export class EdgeCacheService {
313
398
  }
314
399
 
315
400
  if (!isStaleRemote) {
316
- // Warm L1
317
- await this.set(key, parsed, resolvedTtl, options);
401
+ const freshUntil = Number(parsedJson?.__t_exp);
402
+ const staleUntil = Number(parsedJson?.__t_stale);
403
+ const versioned = parsedJson?.__t_edge === 2 && Number.isFinite(freshUntil) && Number.isFinite(staleUntil) && staleUntil >= freshUntil;
404
+ if (versioned && (staleUntil <= Date.now() || freshUntil <= Date.now() && (!(options?.swr ?? 0) || !fetchFn))) {
405
+ isStaleRemote = true;
406
+ } else {
407
+ // Promote without rewriting Redis/KV, resetting expiry, or discarding tags.
408
+ if (versioned && this.fence(nsKey) === epoch) {
409
+ const serialized = JSON.stringify(parsed);
410
+ const tags = Array.isArray(parsedJson.__t_tags) ? parsedJson.__t_tags : Object.keys(activeTagVersions ?? {}).filter(tag => tag !== NAMESPACE_TAG);
411
+ this.storeL1(nsKey, { value: parsed, serialized, bytes: this._estimateBytes(nsKey, serialized),
412
+ expiresAt: freshUntil, staleUntil, tags, tagVersions: activeTagVersions });
413
+ if (freshUntil <= Date.now() && fetchFn) {
414
+ const refresh = execution.then(() => this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags }));
415
+ options?.ctx?.waitUntil(refresh);
416
+ }
417
+ }
418
+ // Legacy raw JSON has no trustworthy remaining TTL: read it but do not promote it.
318
419
 
319
420
  span.setAttribute('cache.hit', true);
320
421
  span.setAttribute('cache.item.tier', 'remote');
321
422
  span.setAttribute('cache.hit_tier', 'l2');
322
423
  return parsed;
424
+ }
323
425
  }
324
426
  }
325
427
  } catch (remoteErr) {
@@ -335,30 +437,22 @@ export class EdgeCacheService {
335
437
  return null;
336
438
  }
337
439
 
338
- let inflightPromise = this.inflight.get(nsKey) as Promise<T> | undefined;
339
- let coalesced = false;
340
-
341
- if (inflightPromise) {
342
- coalesced = true;
343
- } else {
344
- inflightPromise = (async () => {
345
- try {
346
- const fresh = await fetchFn();
347
- await this.set(key, fresh, resolvedTtl, options);
348
- return fresh;
349
- } finally {
350
- this.inflight.delete(nsKey);
351
- }
352
- })();
353
- this.inflight.set(nsKey, inflightPromise);
440
+ const tags = [...new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
441
+ const versions = await this._batchGetTagVersions(tags);
442
+ const fresh = await fetchFn();
443
+ const current = await this._batchGetTagVersions(tags);
444
+ if (this.fence(nsKey) === epoch && tags.every(tag => current[tag] === versions[tag])) {
445
+ try { await this.commit(key, fresh, resolvedTtl, options, versions, epoch); }
446
+ catch (error) { span.recordException?.(error); } // Origin reads remain available during cache outages.
354
447
  }
355
-
356
- span.setAttribute('cache.hit', coalesced);
357
- span.setAttribute('cache.hit_tier', coalesced ? 'l1' : 'miss');
358
- span.setAttribute('cache.stampede_coalesced', coalesced);
359
-
360
- const result = await inflightPromise;
361
- return result;
448
+ span.setAttribute('cache.hit', false).setAttribute('cache.hit_tier', 'miss');
449
+ return fresh;
450
+ } finally {
451
+ if (this.inflight.get(nsKey) === execution) this.inflight.delete(nsKey);
452
+ }
453
+ });
454
+ this.inflight.set(nsKey, execution);
455
+ return await execution;
362
456
  } catch (err) {
363
457
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
364
458
  span.recordException?.(err);
@@ -377,16 +471,20 @@ export class EdgeCacheService {
377
471
  const nsKey = this.nk(key);
378
472
  if (this.inflight.has(nsKey)) return;
379
473
 
380
- const task = (async () => {
474
+ const epoch = this.fence(nsKey);
475
+ const task = Promise.resolve().then(async () => {
381
476
  try {
477
+ const tags = [...new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
478
+ const versions = await this._batchGetTagVersions(tags);
382
479
  const fresh = await fetchFn();
383
- await this.set(key, fresh, ttl, options);
480
+ const current = await this._batchGetTagVersions(tags);
481
+ if (this.fence(nsKey) === epoch && tags.every(tag => current[tag] === versions[tag])) await this.commit(key, fresh, ttl, options, versions, epoch);
384
482
  } catch {
385
483
  // Suppress background revalidation error to prevent unhandled rejection
386
484
  } finally {
387
- this.inflight.delete(nsKey);
485
+ if (this.inflight.get(nsKey) === task) this.inflight.delete(nsKey);
388
486
  }
389
- })();
487
+ });
390
488
 
391
489
  this.inflight.set(nsKey, task);
392
490
  await task;
@@ -404,62 +502,16 @@ export class EdgeCacheService {
404
502
  const span = this._startSpan('tricache.set');
405
503
  span.setAttribute('cache.key', key);
406
504
  const nsKey = this.nk(key);
505
+ this.mutate(nsKey);
506
+ const epoch = this.fence(nsKey);
407
507
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
408
- const now = Date.now();
409
508
  const optObj = Array.isArray(options) ? { tags: options } : options;
410
509
  const swrSeconds = optObj?.swr ?? 0;
411
510
 
412
511
  try {
413
- let activeTagVersions: Record<string, number> | undefined;
414
- if (optObj?.tags?.length) {
415
- activeTagVersions = await this._batchGetTagVersions(optObj.tags);
416
- }
417
-
418
- const serialized = JSON.stringify(value);
419
- const bytes = this._estimateBytes(nsKey, serialized);
420
-
421
- // Clean old entry if updating
422
- this._deleteL1(nsKey);
423
- this._evictIfNeeded(bytes);
424
-
425
- const entry: EdgeL1Entry<T> = {
426
- value,
427
- serialized,
428
- bytes,
429
- expiresAt: now + resolvedTtl * 1000,
430
- staleUntil: now + (resolvedTtl + swrSeconds) * 1000,
431
- tags: optObj?.tags,
432
- tagVersions: activeTagVersions,
433
- };
434
-
435
- this.l1.set(nsKey, entry);
436
- this.currentBytes += bytes;
437
-
438
- // Index tags
439
- if (optObj?.tags) {
440
- for (const tag of optObj.tags) {
441
- let s = this.tagIndex.get(tag);
442
- if (!s) {
443
- s = new Set<string>();
444
- this.tagIndex.set(tag, s);
445
- }
446
- s.add(nsKey);
447
- }
448
- }
449
-
450
- // Write to L2 Remote Storage if configured
451
- if (this.remoteStorage) {
452
- const toStoreRaw = activeTagVersions
453
- ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions })
454
- : serialized;
455
- const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
456
- await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
457
- }
458
-
459
- // Register in Bloom filter
460
- if (this.bloomFilter) {
461
- this.bloomFilter.add(nsKey);
462
- }
512
+ if (!Number.isFinite(resolvedTtl) || resolvedTtl < 0 || !Number.isFinite(swrSeconds) || swrSeconds < 0) throw new Error('Edge TTL and SWR must be finite non-negative values');
513
+ const versions = await this._batchGetTagVersions([...new Set([NAMESPACE_TAG, ...optObj?.tags ?? []])]);
514
+ await this.commit(key, value, resolvedTtl, optObj, versions, epoch);
463
515
  } catch (err) {
464
516
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
465
517
  span.recordException?.(err);
@@ -478,6 +530,7 @@ export class EdgeCacheService {
478
530
  const nsKey = this.nk(key);
479
531
 
480
532
  try {
533
+ this.mutate(nsKey);
481
534
  this._deleteL1(nsKey);
482
535
  if (this.remoteStorage) {
483
536
  await this.remoteStorage.delete(nsKey);
@@ -491,6 +544,48 @@ export class EdgeCacheService {
491
544
  }
492
545
  }
493
546
 
547
+ /**
548
+ * Executes invalidation for a single already-resolved concrete tag without
549
+ * re-entering wildcard/cascade resolution.
550
+ */
551
+ private async _invalidateConcreteTag(tag: string): Promise<void> {
552
+ this.invalidateWork();
553
+ const previous = this.tagVersionCache.get(tag)?.version ?? 1;
554
+ let newVer = 1;
555
+ if (this.remoteStorage) {
556
+ try {
557
+ if (typeof this.remoteStorage.incrementTagVersion === 'function') {
558
+ newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
559
+ if (newVer <= previous) newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
560
+ newVer = Math.max(previous + 1, newVer);
561
+ } else {
562
+ const key = this.nk(`tag_ver:${tag}`);
563
+ const current = await this._getTagVersion(tag);
564
+ newVer = Math.max(current + 1, Date.now());
565
+ await this.remoteStorage.set(key, String(newVer));
566
+ }
567
+ } catch {
568
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
569
+ newVer = current + 1;
570
+ }
571
+ } else {
572
+ const current = this.tagVersionCache.get(tag)?.version ?? 1;
573
+ newVer = current + 1;
574
+ }
575
+
576
+ this._setTagVersionCache(tag, newVer, Date.now() + this.tagVersionTtlMs);
577
+
578
+ // Invalidate local L1 entries
579
+ const keys = this.tagIndex.get(tag);
580
+ if (keys) {
581
+ const keysArr = Array.from(keys);
582
+ for (const k of keysArr) {
583
+ this._deleteL1(k);
584
+ }
585
+ this.tagIndex.delete(tag);
586
+ }
587
+ }
588
+
494
589
  /**
495
590
  * Invalidates all cached entries associated with a tag.
496
591
  */
@@ -518,43 +613,12 @@ export class EdgeCacheService {
518
613
  }
519
614
  if (shouldCascade && !isPattern) matched.add(tag);
520
615
  for (const t of matched) {
521
- await this.invalidateTag(t);
616
+ await this._invalidateConcreteTag(t);
522
617
  }
523
618
  return;
524
619
  }
525
620
 
526
- let newVer = 1;
527
- if (this.remoteStorage) {
528
- try {
529
- if (typeof this.remoteStorage.incrementTagVersion === 'function') {
530
- newVer = await this.remoteStorage.incrementTagVersion(this.nk(tag));
531
- } else {
532
- const key = this.nk(`tag_ver:${tag}`);
533
- const current = await this._getTagVersion(tag);
534
- newVer = Math.max(current + 1, Date.now());
535
- await this.remoteStorage.set(key, String(newVer));
536
- }
537
- } catch {
538
- const current = this.tagVersionCache.get(tag)?.version ?? 1;
539
- newVer = current + 1;
540
- }
541
- } else {
542
- const current = this.tagVersionCache.get(tag)?.version ?? 1;
543
- newVer = current + 1;
544
- }
545
-
546
- // Update in-isolate version cache immediately (with 60s pin)
547
- this.tagVersionCache.set(tag, { version: newVer, expiresAt: Date.now() + 60_000 });
548
-
549
- // Invalidate local L1 entries
550
- const keys = this.tagIndex.get(tag);
551
- if (keys) {
552
- const keysArr = Array.from(keys);
553
- for (const k of keysArr) {
554
- this._deleteL1(k);
555
- }
556
- this.tagIndex.delete(tag);
557
- }
621
+ await this._invalidateConcreteTag(tag);
558
622
  } catch (err) {
559
623
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
560
624
  span.recordException?.(err);
@@ -570,6 +634,8 @@ export class EdgeCacheService {
570
634
  async clear(): Promise<void> {
571
635
  const span = this._startSpan('tricache.clear');
572
636
  try {
637
+ const previousNamespace = await this._getTagVersion(NAMESPACE_TAG);
638
+ this.invalidateWork();
573
639
  this.l1.clear();
574
640
  this.currentBytes = 0;
575
641
  this.tagIndex.clear();
@@ -578,8 +644,10 @@ export class EdgeCacheService {
578
644
  this.bloomFilter.reset();
579
645
  }
580
646
  if (this.remoteStorage) {
581
- await this.remoteStorage.clear?.(this.namespace || undefined);
647
+ await this.remoteStorage.clear?.(this.namespace ? this.namespace + ':' : undefined);
582
648
  }
649
+ this._setTagVersionCache(NAMESPACE_TAG, previousNamespace, Date.now() + this.tagVersionTtlMs);
650
+ await this._invalidateConcreteTag(NAMESPACE_TAG);
583
651
  } catch (err) {
584
652
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
585
653
  span.recordException?.(err);
@@ -598,6 +666,7 @@ export class EdgeCacheService {
598
666
  ttlSeconds?: number,
599
667
  ): Promise<(T | null)[]> {
600
668
  const span = this._startSpan('tricache.mget');
669
+ const epochs = new Map(keys.map(key => [key, this.fence(this.nk(key))]));
601
670
  span.setAttribute('cache.batch.size', keys.length);
602
671
 
603
672
  try {
@@ -623,10 +692,10 @@ export class EdgeCacheService {
623
692
  const isMap = fetchedMap instanceof Map;
624
693
  for (let j = 0; j < missKeys.length; j++) {
625
694
  const k = missKeys[j];
626
- const fetchedVal = isMap ? (fetchedMap as Map<string, T>).get(k) : (fetchedMap as Record<string, T>)[k];
695
+ const fetchedVal = isMap ? (fetchedMap as Map<string, T>).get(k) : Object.hasOwn(fetchedMap, k) ? (fetchedMap as Record<string, T>)[k] : undefined;
627
696
  if (fetchedVal !== undefined) {
628
697
  results[missIndices[j]] = fetchedVal;
629
- await this.set(k, fetchedVal, ttlSeconds);
698
+ if (this.fence(this.nk(k)) === epochs.get(k)) await this.set(k, fetchedVal, ttlSeconds);
630
699
  }
631
700
  }
632
701
  }
@@ -697,6 +766,7 @@ export class EdgeCacheService {
697
766
  * }
698
767
  */
699
768
  async hydrate(source: EdgeSnapshotSource, options?: EdgeHydrateOptions): Promise<number> {
769
+ const epoch = this.globalEpoch;
700
770
  let rawStr: string | null = null;
701
771
 
702
772
  if (source && typeof source === 'object') {
@@ -742,7 +812,7 @@ export class EdgeCacheService {
742
812
  return 0; // Malformed JSON -> fallback cold
743
813
  }
744
814
 
745
- if (!payload || !Array.isArray(payload.entries)) {
815
+ if (!payload || payload.version !== 1 || !Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
746
816
  return 0;
747
817
  }
748
818
 
@@ -750,6 +820,7 @@ export class EdgeCacheService {
750
820
  const maxAgeMs = options?.maxAgeMs ?? 7_200_000;
751
821
  const tolerance = options?.clockSkewToleranceMs ?? 250;
752
822
  const writtenAt = payload.writtenAt ?? 0;
823
+ if (!Number.isFinite(writtenAt) || writtenAt < this.lastGlobalMutationAt) return 0;
753
824
 
754
825
  // Reject future timestamp exceeding clock skew tolerance
755
826
  if (writtenAt - now > tolerance) {
@@ -769,8 +840,10 @@ export class EdgeCacheService {
769
840
  if (item.expiresAt <= now && item.staleUntil <= now) continue;
770
841
 
771
842
  const nsKey = this.nk(item.key);
843
+ if (this.l1.has(nsKey) || this.keyEpochs.has(nsKey) || !Number.isFinite(item.expiresAt) || !Number.isFinite(item.staleUntil)) continue;
772
844
  const serialized = JSON.stringify(item.value);
773
845
  const bytes = this._estimateBytes(nsKey, serialized);
846
+ if (bytes > this.maxBytes || this.maxKeys === 0) continue;
774
847
 
775
848
  this._deleteL1(nsKey);
776
849
  this._evictIfNeeded(bytes);
@@ -800,7 +873,7 @@ export class EdgeCacheService {
800
873
  }
801
874
 
802
875
  if (this.bloomFilter) {
803
- this.bloomFilter.add(item.key);
876
+ this.bloomFilter.add(nsKey);
804
877
  }
805
878
 
806
879
  imported++;
package/src/edge/hono.ts CHANGED
@@ -11,12 +11,14 @@ export interface HonoEdgeCacheOptions {
11
11
  etag?: boolean;
12
12
  /** TTL in seconds. Default: 300. */
13
13
  ttl?: number;
14
- /** Stale-While-Revalidate window in seconds. Default: undefined. */
15
- swr?: number;
16
14
  /** Cache tags for invalidation. */
17
15
  tags?: string[] | ((c: any) => string[]);
18
16
  /** Predicate to skip caching dynamically. */
19
17
  skipCache?: (c: any) => boolean;
18
+ /** Authenticated responses require explicit opt-in and an identity-aware key. */
19
+ cacheAuthenticated?: boolean;
20
+ /** @deprecated Response refreshes run on live requests. Use EdgeCacheService.get() for data-level SWR. */
21
+ swr?: number;
20
22
  }
21
23
 
22
24
  export interface CachedEdgeHttpResponse {
@@ -125,7 +127,6 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
125
127
  cache,
126
128
  etag = true,
127
129
  ttl = 300,
128
- swr,
129
130
  tags,
130
131
  skipCache,
131
132
  keyGenerator,
@@ -141,6 +142,9 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
141
142
  if (skipCache && skipCache(c)) {
142
143
  return await next();
143
144
  }
145
+ const credentials = ['authorization', 'cookie', 'x-api-key', 'x-auth-token'].filter(name => c.req.header?.(name));
146
+ if (c.req.header?.('range') || credentials.length > 0 && (!options.cacheAuthenticated ||
147
+ !keyGenerator && !credentials.every(name => headerWhitelist?.some(header => header.toLowerCase() === name)))) return await next();
144
148
 
145
149
  const cc = c.req.header?.('cache-control') || c.req.header?.('Cache-Control');
146
150
  if (typeof cc === 'string') {
@@ -155,7 +159,12 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
155
159
  return await next();
156
160
  }
157
161
 
158
- const key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
162
+ let key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
163
+ if (credentials.length) {
164
+ if (!globalThis.crypto?.subtle) return await next();
165
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key));
166
+ key = `edge:http:identity:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')}`;
167
+ }
159
168
  const ifNoneMatch = c.req.header?.('if-none-match') || c.req.header?.('If-None-Match');
160
169
  const resolvedTags = typeof tags === 'function' ? tags(c) : tags;
161
170
 
@@ -181,6 +190,10 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
181
190
  }
182
191
 
183
192
  const cc = res.headers?.get?.('cache-control');
193
+ const vary = String(res.headers?.get?.('vary') ?? '').split(',').map(name => name.trim().toLowerCase()).filter(Boolean);
194
+ if (res.headers?.get?.('set-cookie') || vary.includes('*') || !keyGenerator && vary.some(name => !headerWhitelist?.some(header => header.toLowerCase() === name))) {
195
+ throw new NonCacheableEdgeResponseError({ body: '', contentType, status: 0 });
196
+ }
184
197
  if (cc) {
185
198
  const lowerCc = cc.toLowerCase();
186
199
  if (lowerCc.includes('no-store') || lowerCc.includes('no-cache') || lowerCc.includes('private')) {
@@ -233,9 +246,9 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
233
246
  },
234
247
  ttl,
235
248
  {
236
- swr,
249
+ swr: 0,
237
250
  tags: resolvedTags,
238
- ctx: c.executionCtx,
251
+ ctx: readExecutionContext(c),
239
252
  }
240
253
  );
241
254
 
@@ -267,6 +280,10 @@ export function honoEdgeCache(options: HonoEdgeCacheOptions = {}) {
267
280
  };
268
281
  }
269
282
 
283
+ function readExecutionContext(c: any): { waitUntil(promise: Promise<unknown>): void } | undefined {
284
+ try { return c.executionCtx; } catch { return undefined; }
285
+ }
286
+
270
287
  /**
271
288
  * Hono's `compose` ignores a middleware return value once `next()` has set
272
289
  * `c.res` (`finalized === true`). Assigning `c.res` replaces the downstream
package/src/edge/types.ts CHANGED
@@ -96,6 +96,8 @@ export interface EdgeCacheOptions {
96
96
  * - `IEdgeBloomFilter`: a custom or configured `WasmBloomFilter` or `Murmur3BloomFilter` instance.
97
97
  */
98
98
  bloomFilter?: boolean | IEdgeBloomFilter;
99
+ /** Only enable when the filter is an externally maintained, complete remote key set. Default: false. */
100
+ bloomFilterAuthoritative?: boolean;
99
101
  }
100
102
 
101
103
  /**