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
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>();
@@ -70,6 +76,9 @@ export class EdgeCacheService {
70
76
  this.remoteStorage = options?.remoteStorage ?? null;
71
77
  this.tracer = options?.tracer ?? null;
72
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');
73
82
 
74
83
  if (options?.bloomFilter === true) {
75
84
  try {
@@ -100,6 +109,53 @@ export class EdgeCacheService {
100
109
  return (key.length + serialized.length) * 2 + 64;
101
110
  }
102
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
+
103
159
  private _evictIfNeeded(newBytes: number): void {
104
160
  // 1. Evict based on byte ceiling
105
161
  while (this.currentBytes + newBytes > this.maxBytes && this.l1.size > 0) {
@@ -161,7 +217,8 @@ export class EdgeCacheService {
161
217
  if (oldestKey !== undefined) this.tagVersionCache.delete(oldestKey);
162
218
  }
163
219
  }
164
- this.tagVersionCache.set(tag, { version, expiresAt });
220
+ const known = this.tagVersionCache.get(tag)?.version ?? 0;
221
+ this.tagVersionCache.set(tag, { version: Math.max(known, version), expiresAt });
165
222
  }
166
223
 
167
224
  private async _getTagVersion(tag: string): Promise<number> {
@@ -186,12 +243,12 @@ export class EdgeCacheService {
186
243
  version = cached?.version ?? 1;
187
244
  }
188
245
  this._setTagVersionCache(tag, version, now + this.tagVersionTtlMs);
189
- return version;
246
+ return this.tagVersionCache.get(tag)?.version ?? version;
190
247
  }
191
248
 
192
249
  private async _batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
193
250
  const now = Date.now();
194
- const result: Record<string, number> = {};
251
+ const result: Record<string, number> = Object.create(null);
195
252
  const missingTags: string[] = [];
196
253
 
197
254
  for (const t of tags) {
@@ -211,7 +268,7 @@ export class EdgeCacheService {
211
268
  for (let i = 0; i < missingTags.length; i++) {
212
269
  const t = missingTags[i];
213
270
  const v = remoteVersions[this.nk(t)] ?? remoteVersions[t] ?? 1;
214
- result[t] = v;
271
+ result[t] = Math.max(this.tagVersionCache.get(t)?.version ?? 0, v);
215
272
  this._setTagVersionCache(t, v, now + this.tagVersionTtlMs);
216
273
  }
217
274
  } else {
@@ -246,7 +303,7 @@ export class EdgeCacheService {
246
303
  const span = this._startSpan('tricache.get');
247
304
  span.setAttribute('cache.key', key);
248
305
  const nsKey = this.nk(key);
249
- const now = Date.now();
306
+ let now = Date.now();
250
307
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
251
308
 
252
309
  try {
@@ -265,6 +322,7 @@ export class EdgeCacheService {
265
322
  }
266
323
  }
267
324
  }
325
+ now = Date.now();
268
326
 
269
327
  if (isTagStale) {
270
328
  this._deleteL1(nsKey);
@@ -281,14 +339,14 @@ export class EdgeCacheService {
281
339
  return l1Entry.value as T;
282
340
  }
283
341
 
284
- if (l1Entry.staleUntil > now && fetchFn) {
342
+ if (l1Entry.staleUntil > now && fetchFn && (options?.swr ?? 0) > 0) {
285
343
  // Stale hit — trigger background revalidation
286
344
  span.setAttribute('cache.hit', true);
287
345
  span.setAttribute('cache.item.tier', 'memory');
288
346
  span.setAttribute('cache.hit_tier', 'l1');
289
347
  span.setAttribute('cache.stale', true);
290
348
 
291
- const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, options);
349
+ const revalPromise = this._revalidate(key, fetchFn, resolvedTtl, { ...options, tags: options?.tags ?? l1Entry.tags });
292
350
  if (options?.ctx?.waitUntil) {
293
351
  options.ctx.waitUntil(revalPromise);
294
352
  }
@@ -296,13 +354,21 @@ export class EdgeCacheService {
296
354
  }
297
355
 
298
356
  // Hard expired in L1
299
- this._deleteL1(nsKey);
357
+ if (l1Entry.staleUntil <= now) this._deleteL1(nsKey);
300
358
  }
301
359
  }
302
360
 
303
- // 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.
304
370
  if (this.remoteStorage) {
305
- if (this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
371
+ if (this.bloomAuthoritative && this.bloomFilter && !this.bloomFilter.mightContain(nsKey)) {
306
372
  span.setAttribute('cache.bloom.filtered', true);
307
373
  } else {
308
374
  try {
@@ -317,6 +383,8 @@ export class EdgeCacheService {
317
383
  if (parsedJson && typeof parsedJson === 'object' && '__t_val' in parsedJson && '__t_tv' in parsedJson) {
318
384
  parsed = parsedJson.__t_val as T;
319
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');
320
388
  const tagNames = Object.keys(activeTagVersions);
321
389
  const currentVers = await this._batchGetTagVersions(tagNames);
322
390
  for (const tag of tagNames) {
@@ -330,13 +398,30 @@ export class EdgeCacheService {
330
398
  }
331
399
 
332
400
  if (!isStaleRemote) {
333
- // Warm L1
334
- 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.
335
419
 
336
420
  span.setAttribute('cache.hit', true);
337
421
  span.setAttribute('cache.item.tier', 'remote');
338
422
  span.setAttribute('cache.hit_tier', 'l2');
339
423
  return parsed;
424
+ }
340
425
  }
341
426
  }
342
427
  } catch (remoteErr) {
@@ -352,30 +437,22 @@ export class EdgeCacheService {
352
437
  return null;
353
438
  }
354
439
 
355
- let inflightPromise = this.inflight.get(nsKey) as Promise<T> | undefined;
356
- let coalesced = false;
357
-
358
- if (inflightPromise) {
359
- coalesced = true;
360
- } else {
361
- inflightPromise = (async () => {
362
- try {
363
- const fresh = await fetchFn();
364
- await this.set(key, fresh, resolvedTtl, options);
365
- return fresh;
366
- } finally {
367
- this.inflight.delete(nsKey);
368
- }
369
- })();
370
- 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.
371
447
  }
372
-
373
- span.setAttribute('cache.hit', coalesced);
374
- span.setAttribute('cache.hit_tier', coalesced ? 'l1' : 'miss');
375
- span.setAttribute('cache.stampede_coalesced', coalesced);
376
-
377
- const result = await inflightPromise;
378
- 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;
379
456
  } catch (err) {
380
457
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
381
458
  span.recordException?.(err);
@@ -394,16 +471,20 @@ export class EdgeCacheService {
394
471
  const nsKey = this.nk(key);
395
472
  if (this.inflight.has(nsKey)) return;
396
473
 
397
- const task = (async () => {
474
+ const epoch = this.fence(nsKey);
475
+ const task = Promise.resolve().then(async () => {
398
476
  try {
477
+ const tags = [...new Set([NAMESPACE_TAG, ...options?.tags ?? []])];
478
+ const versions = await this._batchGetTagVersions(tags);
399
479
  const fresh = await fetchFn();
400
- 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);
401
482
  } catch {
402
483
  // Suppress background revalidation error to prevent unhandled rejection
403
484
  } finally {
404
- this.inflight.delete(nsKey);
485
+ if (this.inflight.get(nsKey) === task) this.inflight.delete(nsKey);
405
486
  }
406
- })();
487
+ });
407
488
 
408
489
  this.inflight.set(nsKey, task);
409
490
  await task;
@@ -421,62 +502,16 @@ export class EdgeCacheService {
421
502
  const span = this._startSpan('tricache.set');
422
503
  span.setAttribute('cache.key', key);
423
504
  const nsKey = this.nk(key);
505
+ this.mutate(nsKey);
506
+ const epoch = this.fence(nsKey);
424
507
  const resolvedTtl = ttlSeconds ?? this.defaultTtl;
425
- const now = Date.now();
426
508
  const optObj = Array.isArray(options) ? { tags: options } : options;
427
509
  const swrSeconds = optObj?.swr ?? 0;
428
510
 
429
511
  try {
430
- let activeTagVersions: Record<string, number> | undefined;
431
- if (optObj?.tags?.length) {
432
- activeTagVersions = await this._batchGetTagVersions(optObj.tags);
433
- }
434
-
435
- const serialized = JSON.stringify(value);
436
- const bytes = this._estimateBytes(nsKey, serialized);
437
-
438
- // Clean old entry if updating
439
- this._deleteL1(nsKey);
440
- this._evictIfNeeded(bytes);
441
-
442
- const entry: EdgeL1Entry<T> = {
443
- value,
444
- serialized,
445
- bytes,
446
- expiresAt: now + resolvedTtl * 1000,
447
- staleUntil: now + (resolvedTtl + swrSeconds) * 1000,
448
- tags: optObj?.tags,
449
- tagVersions: activeTagVersions,
450
- };
451
-
452
- this.l1.set(nsKey, entry);
453
- this.currentBytes += bytes;
454
-
455
- // Index tags
456
- if (optObj?.tags) {
457
- for (const tag of optObj.tags) {
458
- let s = this.tagIndex.get(tag);
459
- if (!s) {
460
- s = new Set<string>();
461
- this.tagIndex.set(tag, s);
462
- }
463
- s.add(nsKey);
464
- }
465
- }
466
-
467
- // Write to L2 Remote Storage if configured
468
- if (this.remoteStorage) {
469
- const toStoreRaw = activeTagVersions
470
- ? JSON.stringify({ __t_val: value, __t_tv: activeTagVersions })
471
- : serialized;
472
- const payloadToStore = this.enc.isEnabled ? await this.enc.encrypt(toStoreRaw) : toStoreRaw;
473
- await this.remoteStorage.set(nsKey, payloadToStore, resolvedTtl + swrSeconds);
474
- }
475
-
476
- // Register in Bloom filter
477
- if (this.bloomFilter) {
478
- this.bloomFilter.add(nsKey);
479
- }
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);
480
515
  } catch (err) {
481
516
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
482
517
  span.recordException?.(err);
@@ -495,6 +530,7 @@ export class EdgeCacheService {
495
530
  const nsKey = this.nk(key);
496
531
 
497
532
  try {
533
+ this.mutate(nsKey);
498
534
  this._deleteL1(nsKey);
499
535
  if (this.remoteStorage) {
500
536
  await this.remoteStorage.delete(nsKey);
@@ -513,11 +549,15 @@ export class EdgeCacheService {
513
549
  * re-entering wildcard/cascade resolution.
514
550
  */
515
551
  private async _invalidateConcreteTag(tag: string): Promise<void> {
552
+ this.invalidateWork();
553
+ const previous = this.tagVersionCache.get(tag)?.version ?? 1;
516
554
  let newVer = 1;
517
555
  if (this.remoteStorage) {
518
556
  try {
519
557
  if (typeof this.remoteStorage.incrementTagVersion === 'function') {
520
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);
521
561
  } else {
522
562
  const key = this.nk(`tag_ver:${tag}`);
523
563
  const current = await this._getTagVersion(tag);
@@ -533,8 +573,7 @@ export class EdgeCacheService {
533
573
  newVer = current + 1;
534
574
  }
535
575
 
536
- // Update in-isolate version cache immediately (with 60s pin)
537
- this._setTagVersionCache(tag, newVer, Date.now() + 60_000);
576
+ this._setTagVersionCache(tag, newVer, Date.now() + this.tagVersionTtlMs);
538
577
 
539
578
  // Invalidate local L1 entries
540
579
  const keys = this.tagIndex.get(tag);
@@ -595,6 +634,8 @@ export class EdgeCacheService {
595
634
  async clear(): Promise<void> {
596
635
  const span = this._startSpan('tricache.clear');
597
636
  try {
637
+ const previousNamespace = await this._getTagVersion(NAMESPACE_TAG);
638
+ this.invalidateWork();
598
639
  this.l1.clear();
599
640
  this.currentBytes = 0;
600
641
  this.tagIndex.clear();
@@ -603,8 +644,10 @@ export class EdgeCacheService {
603
644
  this.bloomFilter.reset();
604
645
  }
605
646
  if (this.remoteStorage) {
606
- await this.remoteStorage.clear?.(this.namespace || undefined);
647
+ await this.remoteStorage.clear?.(this.namespace ? this.namespace + ':' : undefined);
607
648
  }
649
+ this._setTagVersionCache(NAMESPACE_TAG, previousNamespace, Date.now() + this.tagVersionTtlMs);
650
+ await this._invalidateConcreteTag(NAMESPACE_TAG);
608
651
  } catch (err) {
609
652
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
610
653
  span.recordException?.(err);
@@ -623,6 +666,7 @@ export class EdgeCacheService {
623
666
  ttlSeconds?: number,
624
667
  ): Promise<(T | null)[]> {
625
668
  const span = this._startSpan('tricache.mget');
669
+ const epochs = new Map(keys.map(key => [key, this.fence(this.nk(key))]));
626
670
  span.setAttribute('cache.batch.size', keys.length);
627
671
 
628
672
  try {
@@ -648,10 +692,10 @@ export class EdgeCacheService {
648
692
  const isMap = fetchedMap instanceof Map;
649
693
  for (let j = 0; j < missKeys.length; j++) {
650
694
  const k = missKeys[j];
651
- 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;
652
696
  if (fetchedVal !== undefined) {
653
697
  results[missIndices[j]] = fetchedVal;
654
- await this.set(k, fetchedVal, ttlSeconds);
698
+ if (this.fence(this.nk(k)) === epochs.get(k)) await this.set(k, fetchedVal, ttlSeconds);
655
699
  }
656
700
  }
657
701
  }
@@ -722,6 +766,7 @@ export class EdgeCacheService {
722
766
  * }
723
767
  */
724
768
  async hydrate(source: EdgeSnapshotSource, options?: EdgeHydrateOptions): Promise<number> {
769
+ const epoch = this.globalEpoch;
725
770
  let rawStr: string | null = null;
726
771
 
727
772
  if (source && typeof source === 'object') {
@@ -767,7 +812,7 @@ export class EdgeCacheService {
767
812
  return 0; // Malformed JSON -> fallback cold
768
813
  }
769
814
 
770
- if (!payload || !Array.isArray(payload.entries)) {
815
+ if (!payload || payload.version !== 1 || !Array.isArray(payload.entries) || this.globalEpoch !== epoch) {
771
816
  return 0;
772
817
  }
773
818
 
@@ -775,6 +820,7 @@ export class EdgeCacheService {
775
820
  const maxAgeMs = options?.maxAgeMs ?? 7_200_000;
776
821
  const tolerance = options?.clockSkewToleranceMs ?? 250;
777
822
  const writtenAt = payload.writtenAt ?? 0;
823
+ if (!Number.isFinite(writtenAt) || writtenAt < this.lastGlobalMutationAt) return 0;
778
824
 
779
825
  // Reject future timestamp exceeding clock skew tolerance
780
826
  if (writtenAt - now > tolerance) {
@@ -794,8 +840,10 @@ export class EdgeCacheService {
794
840
  if (item.expiresAt <= now && item.staleUntil <= now) continue;
795
841
 
796
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;
797
844
  const serialized = JSON.stringify(item.value);
798
845
  const bytes = this._estimateBytes(nsKey, serialized);
846
+ if (bytes > this.maxBytes || this.maxKeys === 0) continue;
799
847
 
800
848
  this._deleteL1(nsKey);
801
849
  this._evictIfNeeded(bytes);
@@ -825,7 +873,7 @@ export class EdgeCacheService {
825
873
  }
826
874
 
827
875
  if (this.bloomFilter) {
828
- this.bloomFilter.add(item.key);
876
+ this.bloomFilter.add(nsKey);
829
877
  }
830
878
 
831
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
  /**
package/src/hono/index.ts CHANGED
@@ -20,6 +20,8 @@ import {
20
20
  buildDeterministicKey,
21
21
  generateETag,
22
22
  shouldSkipCache,
23
+ isShareableHttpResponse,
24
+ matchesETag,
23
25
  type KeyDerivationOptions,
24
26
  } from '../http/utils.js';
25
27
 
@@ -40,12 +42,12 @@ export interface HonoCacheContext {
40
42
  clone?: () => { text: () => Promise<string> };
41
43
  body?: unknown;
42
44
  };
43
- body: (data: unknown, status?: number, headers?: Record<string, string>) => unknown;
45
+ body: (...args: any[]) => any;
44
46
  executionCtx?: unknown;
45
47
  }
46
48
 
47
49
  export type HonoNext = () => Promise<void>;
48
- export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<unknown>;
50
+ export type HonoMiddleware = (c: HonoCacheContext, next: HonoNext) => Promise<Response | void>;
49
51
 
50
52
  export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDerivationOptions, 'keyGenerator'> {
51
53
  /** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
@@ -58,6 +60,8 @@ export interface HonoCacheOptions extends Omit<WrapOptions, 'tags'>, Omit<KeyDer
58
60
  skipCache?: (c: HonoCacheContext) => boolean;
59
61
  /** Dynamic tags derivation from the Hono context. */
60
62
  tags?: string[] | ((c: HonoCacheContext) => string[]);
63
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
64
+ swr?: number;
61
65
  }
62
66
 
63
67
  export interface CachedHonoResponse {
@@ -71,7 +75,7 @@ export interface CachedHonoResponse {
71
75
  function readRequestHeader(c: HonoCacheContext, name: string): string | undefined {
72
76
  const headerFn = c.req.header;
73
77
  if (typeof headerFn === 'function') {
74
- const viaFn = headerFn(name) ?? headerFn(name.toLowerCase());
78
+ const viaFn = headerFn.call(c.req, name) ?? headerFn.call(c.req, name.toLowerCase());
75
79
  if (viaFn !== undefined && viaFn !== null && viaFn !== '') {
76
80
  return viaFn;
77
81
  }
@@ -95,6 +99,10 @@ function toRequestLike(c: HonoCacheContext, headerWhitelist?: string[]) {
95
99
  const headers: Record<string, string | undefined> = {};
96
100
  const cacheControl = readRequestHeader(c, 'cache-control');
97
101
  const ifNoneMatch = readRequestHeader(c, 'if-none-match');
102
+ for (const name of ['authorization', 'cookie', 'range', 'x-api-key', 'x-auth-token']) {
103
+ const value = readRequestHeader(c, name);
104
+ if (value) headers[name] = value;
105
+ }
98
106
 
99
107
  if (cacheControl) {
100
108
  headers['cache-control'] = cacheControl;
@@ -133,8 +141,8 @@ function applyHonoCachedResponse(
133
141
  c: HonoCacheContext,
134
142
  cached: CachedHonoResponse,
135
143
  ifNoneMatch: string | undefined,
136
- ): unknown {
137
- if (cached.etag && ifNoneMatch === cached.etag) {
144
+ ): Response | void {
145
+ if (cached.etag && matchesETag(ifNoneMatch, cached.etag)) {
138
146
  const notModifiedHeaders: Record<string, string> = { ETag: cached.etag };
139
147
  if (cached.headers?.['cache-control']) notModifiedHeaders['Cache-Control'] = cached.headers['cache-control'];
140
148
  if (cached.headers?.['vary']) notModifiedHeaders['Vary'] = cached.headers['vary'];
@@ -159,6 +167,7 @@ function applyHonoCachedResponse(
159
167
  async function snapshotHonoResponse(
160
168
  c: HonoCacheContext,
161
169
  etag: boolean,
170
+ options: KeyDerivationOptions,
162
171
  ): Promise<CachedHonoResponse> {
163
172
  const res = c.res;
164
173
  if (!res) {
@@ -178,6 +187,7 @@ async function snapshotHonoResponse(
178
187
  }
179
188
 
180
189
  const status = res.status ?? 200;
190
+ if (!isShareableHttpResponse(status, name => res.headers?.get?.(name), options)) return { body: '', contentType, status: 0 };
181
191
  if (!isCacheableStatus(status)) {
182
192
  return { body: '', contentType, status };
183
193
  }
@@ -249,7 +259,6 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
249
259
  cache,
250
260
  etag = true,
251
261
  ttl = 300,
252
- swr,
253
262
  tags,
254
263
  skipCache,
255
264
  keyGenerator,
@@ -265,7 +274,7 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
265
274
  }
266
275
 
267
276
  const reqLike = toRequestLike(c, headerWhitelist);
268
- if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined)) {
277
+ if (shouldSkipCache(reqLike, skipCache ? () => skipCache(c) : undefined, { ...options, keyGenerator: keyGenerator ? () => keyGenerator(c) : undefined })) {
269
278
  return await next();
270
279
  }
271
280
 
@@ -289,14 +298,15 @@ export function cacheMiddleware(options: HonoCacheOptions = {}): HonoMiddleware
289
298
  async () => {
290
299
  ranNext = true;
291
300
  await next();
292
- const snapshot = await snapshotHonoResponse(c, etag);
301
+ const snapshot = await snapshotHonoResponse(c, etag, { headerWhitelist, keyGenerator: keyGenerator ? () => keyGenerator(c) : undefined });
293
302
  if (!isCacheableStatus(snapshot.status)) {
294
303
  throw new NonCacheableHonoResponseError(snapshot);
295
304
  }
296
305
  return snapshot;
297
306
  },
298
307
  ttl,
299
- { swr, tags: resolvedTags },
308
+ // Never invoke a completed Hono next() chain from background work.
309
+ { swr: 0, tags: resolvedTags },
300
310
  );
301
311
 
302
312
  return applyHonoCachedResponse(c, cached, ifNoneMatch);