tricache 0.4.0 → 0.5.1

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.
package/dist/index.js CHANGED
@@ -164,10 +164,11 @@ var CacheEncryption = class {
164
164
  const iv2 = this._nextCtrIV();
165
165
  const c2 = createCipheriv("aes-128-ctr", this._key, iv2);
166
166
  const enc2 = c2.update(plaintext, "utf8");
167
- c2.final();
168
- const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length);
167
+ const fin = c2.final();
168
+ const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
169
169
  iv2.copy(out2, 0);
170
170
  enc2.copy(out2, CTR_IV_BYTES);
171
+ if (fin.length > 0) fin.copy(out2, CTR_IV_BYTES + enc2.length);
171
172
  return PREFIX_CTR + out2.toString("base64");
172
173
  }
173
174
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
@@ -217,8 +218,8 @@ var CacheEncryption = class {
217
218
  const ct2 = combined2.subarray(CTR_IV_BYTES);
218
219
  const d2 = createDecipheriv("aes-128-ctr", key, iv2);
219
220
  const plain2 = d2.update(ct2);
220
- d2.final();
221
- return plain2.toString("utf8");
221
+ const fin = d2.final();
222
+ return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
222
223
  }
223
224
  const is256 = value.startsWith(PREFIX_256);
224
225
  const is128 = value.startsWith(PREFIX_128);
@@ -252,11 +253,12 @@ var CacheEncryption = class {
252
253
  const iv2 = this._nextCtrIV();
253
254
  const c2 = createCipheriv("aes-128-ctr", this._key, iv2);
254
255
  const enc2 = c2.update(data);
255
- c2.final();
256
- const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length);
256
+ const fin = c2.final();
257
+ const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
257
258
  MAGIC_CTR.copy(out2, 0);
258
259
  iv2.copy(out2, MAGIC_LEN);
259
260
  enc2.copy(out2, MAGIC_LEN + CTR_IV_BYTES);
261
+ if (fin.length > 0) fin.copy(out2, MAGIC_LEN + CTR_IV_BYTES + enc2.length);
260
262
  return out2;
261
263
  }
262
264
  const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
@@ -307,8 +309,8 @@ var CacheEncryption = class {
307
309
  const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
308
310
  const d2 = createDecipheriv("aes-128-ctr", key, iv2);
309
311
  const plain2 = d2.update(ct2);
310
- d2.final();
311
- return plain2;
312
+ const fin = d2.final();
313
+ return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
312
314
  }
313
315
  const is256 = magic.equals(MAGIC_256);
314
316
  const is128 = magic.equals(MAGIC_128);
@@ -333,11 +335,7 @@ import { pack, unpack } from "msgpackr";
333
335
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
334
336
  var KEY_STAGING_OFFSET = 2e4;
335
337
  var MAX_KEY_BYTES = 512;
336
- function instantiateSync() {
337
- const wasmBytes = Buffer.from(BLOOM_WASM_BASE64, "base64");
338
- const compiled = new WebAssembly.Module(wasmBytes);
339
- return new WebAssembly.Instance(compiled, {});
340
- }
338
+ var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
341
339
  var WasmBloomFilter = class {
342
340
  exports;
343
341
  mem;
@@ -348,26 +346,16 @@ var WasmBloomFilter = class {
348
346
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
349
347
  _insertionCount = 0;
350
348
  constructor() {
351
- const instance = instantiateSync();
349
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
352
350
  this.exports = instance.exports;
353
351
  this.mem = new Uint8Array(this.exports.memory.buffer);
354
352
  const k = 7, p = 0.01;
355
353
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
356
354
  }
357
355
  writeKey(key) {
358
- const max = Math.min(key.length, MAX_KEY_BYTES);
359
- if (max === 0) return 0;
360
- for (let i = 0; i < max; i++) {
361
- const c = key.charCodeAt(i);
362
- if (c > 127) {
363
- const encoded = this.encoder.encode(key);
364
- const len = Math.min(encoded.length, MAX_KEY_BYTES);
365
- this.mem.set(encoded.subarray(0, len), KEY_STAGING_OFFSET);
366
- return len;
367
- }
368
- this.mem[KEY_STAGING_OFFSET + i] = c;
369
- }
370
- return max;
356
+ if (key.length === 0) return 0;
357
+ const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
358
+ return this.encoder.encodeInto(key, target).written;
371
359
  }
372
360
  add(key) {
373
361
  const len = this.writeKey(key);
@@ -407,6 +395,7 @@ var WasmBloomFilter = class {
407
395
  };
408
396
 
409
397
  // src/smart-memory-cache.ts
398
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
410
399
  var EVICTION_BATCH_PERCENT = 0.2;
411
400
  var JsBloomFilter = class {
412
401
  bits;
@@ -485,15 +474,25 @@ var JsBloomFilter = class {
485
474
  return { bitsSet, fillFactor: bitsSet / this.numBits };
486
475
  }
487
476
  };
488
- function createBloomFilter(logger) {
477
+ function createBloomFilter(logger, maxEntries) {
478
+ const LN2_SQ = Math.LN2 * Math.LN2;
479
+ const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
480
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
489
481
  try {
490
482
  const wasm = new WasmBloomFilter();
491
- logger.debug("SmartMemoryCache: WASM BloomFilter active");
492
- return wasm;
483
+ if (wasm.maxCapacity >= maxEntries) {
484
+ logger.debug("SmartMemoryCache: WASM BloomFilter active");
485
+ return wasm;
486
+ }
487
+ logger.debug("SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter", {
488
+ wasmCapacity: wasm.maxCapacity,
489
+ maxEntries,
490
+ optimalBits
491
+ });
493
492
  } catch (err) {
494
493
  logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
495
- return new JsBloomFilter();
496
494
  }
495
+ return new JsBloomFilter(optimalBits, optimalK);
497
496
  }
498
497
  var SKETCH_ROWS = 4;
499
498
  var SKETCH_WIDTH = 512;
@@ -511,32 +510,35 @@ var CountMinSketch = class {
511
510
  }
512
511
  return h;
513
512
  }
514
- /** Four independent bit-mixes from one FNV-1a seed. */
515
- hashes(key) {
513
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
514
+ increment(key) {
516
515
  const h = this.fnv32(key);
517
516
  const h1 = (h ^ h >>> 16) >>> 0;
518
517
  const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
519
518
  const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
520
519
  const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
521
- return [h1, h2, h3, h4];
522
- }
523
- /** Record one access. Decays all counters when the insertion threshold is crossed. */
524
- increment(key) {
525
- const [h1, h2, h3, h4] = this.hashes(key);
526
520
  const t = this.table;
527
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
528
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
529
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
530
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
521
+ const i0 = h1 & SKETCH_MASK;
522
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
523
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
524
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
525
+ if (t[i0] < 65535) t[i0]++;
526
+ if (t[i1] < 65535) t[i1]++;
527
+ if (t[i2] < 65535) t[i2]++;
528
+ if (t[i3] < 65535) t[i3]++;
531
529
  if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
532
530
  }
533
531
  /** Minimum-across-rows frequency estimate. */
534
532
  estimate(key) {
535
- const [h1, h2, h3, h4] = this.hashes(key);
533
+ const h = this.fnv32(key);
534
+ const h1 = (h ^ h >>> 16) >>> 0;
535
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
536
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
537
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
536
538
  const t = this.table;
537
539
  return Math.min(
538
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
539
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
540
+ t[h1 & SKETCH_MASK],
541
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
540
542
  t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
541
543
  t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
542
544
  );
@@ -547,6 +549,21 @@ var CountMinSketch = class {
547
549
  this.inserts = 0;
548
550
  }
549
551
  };
552
+ function globMatchParts(parts, first, last, key) {
553
+ if (first.length > 0 && !key.startsWith(first)) return false;
554
+ if (last.length > 0 && !key.endsWith(last)) return false;
555
+ if (first.length + last.length > key.length) return false;
556
+ let pos = first.length;
557
+ const end = key.length - last.length;
558
+ for (let i = 1; i < parts.length - 1; i++) {
559
+ const seg = parts[i];
560
+ if (seg.length === 0) continue;
561
+ const idx = key.indexOf(seg, pos);
562
+ if (idx === -1 || idx + seg.length > end) return false;
563
+ pos = idx + seg.length;
564
+ }
565
+ return true;
566
+ }
550
567
  var SmartMemoryCache = class {
551
568
  cache = /* @__PURE__ */ new Map();
552
569
  opts;
@@ -569,7 +586,7 @@ var SmartMemoryCache = class {
569
586
  _bloomDirtyCount = 0;
570
587
  constructor(opts, existing) {
571
588
  this.opts = opts;
572
- this.bloom = createBloomFilter(opts.logger);
589
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
573
590
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
574
591
  if (existing) {
575
592
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -629,7 +646,14 @@ var SmartMemoryCache = class {
629
646
  const catSz = this.categorySize.get(category) ?? 0;
630
647
  const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
631
648
  const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
632
- if (!catOvf && !glbOvf) return;
649
+ if (!catOvf && !glbOvf) {
650
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * 0.9);
651
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * 0.9);
652
+ if (entryWatermark || byteWatermark) {
653
+ this.smartEvict(category, false);
654
+ }
655
+ return;
656
+ }
633
657
  this.smartEvict(category, catOvf);
634
658
  }
635
659
  score(entry, catBonus, now, key) {
@@ -652,7 +676,8 @@ var SmartMemoryCache = class {
652
676
  * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
653
677
  */
654
678
  maybeRebuildBloom() {
655
- if (this._bloomDirtyCount > this.bloom.maxCapacity >>> 2 || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
679
+ const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
680
+ if (this._bloomDirtyCount > dirtyThreshold || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
656
681
  this.bloom.rebuild(this.cache.keys());
657
682
  this._bloomDirtyCount = 0;
658
683
  }
@@ -722,12 +747,15 @@ var SmartMemoryCache = class {
722
747
  }
723
748
  entry.hits++;
724
749
  entry.lastAccess = now;
725
- this.sketch.increment(key);
726
- const cat = this.getCategory(key);
727
- this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
750
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
728
751
  const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
729
- const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
730
- return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
752
+ _hit.value = value;
753
+ _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
754
+ _hit.expiresAt = entry.expiresAt;
755
+ _hit.ttlMs = entry.ttlMs;
756
+ _hit.delta = entry.delta;
757
+ _hit.fetchedAt = now;
758
+ return _hit;
731
759
  }
732
760
  set(key, data, ttlMs, priority = 2, staleAt, delta) {
733
761
  const packed = pack(data);
@@ -750,7 +778,7 @@ var SmartMemoryCache = class {
750
778
  this.ensureCapacity(cat, size);
751
779
  const now = Date.now();
752
780
  this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
753
- this.bloom.add(key);
781
+ if (!existingEntry) this.bloom.add(key);
754
782
  this.maybeRebuildBloom();
755
783
  this.totalSize += size;
756
784
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
@@ -769,9 +797,27 @@ var SmartMemoryCache = class {
769
797
  }
770
798
  keysMatchingPattern(pattern) {
771
799
  if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
772
- const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
800
+ if (pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1) {
801
+ const prefix = pattern.slice(0, -1);
802
+ const catKeys = this.categoryKeys.get(prefix);
803
+ if (catKeys !== void 0) return Array.from(catKeys);
804
+ }
805
+ const firstStar = pattern.indexOf("*");
806
+ if (firstStar === pattern.lastIndexOf("*")) {
807
+ const prefix = pattern.slice(0, firstStar);
808
+ const suffix = pattern.slice(firstStar + 1);
809
+ const minLen = prefix.length + suffix.length;
810
+ const out2 = [];
811
+ for (const k of this.cache.keys()) {
812
+ if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out2.push(k);
813
+ }
814
+ return out2;
815
+ }
816
+ const parts = pattern.split("*");
817
+ const first = parts[0];
818
+ const last = parts[parts.length - 1];
773
819
  const out = [];
774
- for (const k of this.cache.keys()) if (re.test(k)) out.push(k);
820
+ for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
775
821
  return out;
776
822
  }
777
823
  deletePattern(pattern) {
@@ -928,6 +974,30 @@ var SmartMemoryCache = class {
928
974
  if (entry.expiresAt > now) yield [key, entry];
929
975
  }
930
976
  }
977
+ /**
978
+ * Non-generator bulk scan over all live entries.
979
+ *
980
+ * Faster than the generator-based iterators for bulk operations because:
981
+ * - No generator state-machine overhead (no yield/resume suspend points).
982
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
983
+ * - The same Map call-site is used by a single plain `for` loop instead of being
984
+ * shared across three competing generator functions, giving V8's IC a cleaner
985
+ * monomorphic profile for this path.
986
+ *
987
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
988
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
989
+ * key, avoiding the allocation entirely for callers that don't.
990
+ *
991
+ * @param fn Called once per live entry.
992
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
993
+ * Pass 0 when no namespace is configured.
994
+ */
995
+ scan(fn, prefixLen) {
996
+ const now = Date.now();
997
+ for (const [key, entry] of this.cache) {
998
+ if (entry.expiresAt > now) fn(key, entry, prefixLen);
999
+ }
1000
+ }
931
1001
  /**
932
1002
  * Yields only the keys of live entries — no intermediate tuple allocation.
933
1003
  * Use this instead of liveEntries() when you only need keys.
@@ -1065,6 +1135,8 @@ var AES_ALGO = "aes-256-gcm";
1065
1135
  var IV_BYTES2 = 12;
1066
1136
  var TAG_BYTES2 = 16;
1067
1137
  var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1138
+ var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1139
+ var V2_HEADER_LEN = 16;
1068
1140
  var DISK_TIER_VERSION = 1;
1069
1141
  var DiskTier = class {
1070
1142
  opts;
@@ -1073,6 +1145,8 @@ var DiskTier = class {
1073
1145
  usageCounted = false;
1074
1146
  fileCount = 0;
1075
1147
  // maintained in-memory; avoids walkCacheFiles() in stats
1148
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1149
+ _nextJanitorBucket = 0;
1076
1150
  constructor(opts) {
1077
1151
  this.opts = opts;
1078
1152
  }
@@ -1107,18 +1181,46 @@ var DiskTier = class {
1107
1181
  }
1108
1182
  }
1109
1183
  /**
1110
- * Map a cache key to its on-disk path.
1184
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
1185
+ * Kept separate from path construction so callers can find files by prefix
1186
+ * without knowing which filename generation was used when the file was written.
1187
+ */
1188
+ keyToHash(key) {
1189
+ return crypto.createHash("sha256").update(key, "utf8").digest("hex");
1190
+ }
1191
+ /**
1192
+ * Build the write path for a NEW file (V3 generation).
1193
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1194
+ * with zero file I/O — after readdirSync() it only needs a string parse.
1111
1195
  *
1112
- * Files are sharded into two-character hex prefix subdirectories to avoid
1113
- * putting thousands of flat files into a single directory node — which
1114
- * degrades EXT4/NTFS performance at scale.
1196
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1197
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1115
1198
  *
1116
- * key → SHA-256 hex e3b0c442...
1117
- * path → {dir}/e3/e3b0c442...
1199
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1118
1200
  */
1119
- keyToPath(key) {
1120
- const hash = crypto.createHash("sha256").update(key, "utf8").digest("hex");
1121
- return path.join(this.opts.dir, hash.slice(0, 2), hash);
1201
+ hashToWritePath(hash, expiresAt) {
1202
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
1203
+ }
1204
+ /**
1205
+ * Find the on-disk file for a key hash, handling all filename generations:
1206
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1207
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
1208
+ * Returns null when the bucket dir does not exist or the key is absent.
1209
+ */
1210
+ findFilePath(hash) {
1211
+ const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
1212
+ let files;
1213
+ try {
1214
+ files = fs.readdirSync(bucketPath);
1215
+ } catch {
1216
+ return null;
1217
+ }
1218
+ let match;
1219
+ for (const f of files) {
1220
+ if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
1221
+ }
1222
+ if (!match) return null;
1223
+ return path.join(bucketPath, match);
1122
1224
  }
1123
1225
  /**
1124
1226
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -1169,6 +1271,35 @@ var DiskTier = class {
1169
1271
  d.setAuthTag(tag);
1170
1272
  return Buffer.concat([d.update(ct), d.final()]);
1171
1273
  }
1274
+ /**
1275
+ * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1276
+ * the outer 16-byte header alongside the plaintext expiresAt).
1277
+ * Returns the buffer unchanged when no encryption key is configured.
1278
+ */
1279
+ encryptV2(data) {
1280
+ const key = this.opts.encryptionKey;
1281
+ if (!key) return data;
1282
+ const iv = crypto.randomBytes(IV_BYTES2);
1283
+ const c = crypto.createCipheriv(AES_ALGO, key, iv);
1284
+ const enc = Buffer.concat([c.update(data), c.final()]);
1285
+ const tag = c.getAuthTag();
1286
+ return Buffer.concat([iv, tag, enc]);
1287
+ }
1288
+ /**
1289
+ * V2 decryption — inner payload after stripping the 16-byte header.
1290
+ * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1291
+ * without a key the payload is raw msgpack.
1292
+ */
1293
+ decryptV2(inner) {
1294
+ const key = this.opts.encryptionKey;
1295
+ if (!key) return inner;
1296
+ const iv = inner.subarray(0, IV_BYTES2);
1297
+ const tag = inner.subarray(IV_BYTES2, IV_BYTES2 + TAG_BYTES2);
1298
+ const ct = inner.subarray(IV_BYTES2 + TAG_BYTES2);
1299
+ const d = crypto.createDecipheriv(AES_ALGO, key, iv);
1300
+ d.setAuthTag(tag);
1301
+ return Buffer.concat([d.update(ct), d.final()]);
1302
+ }
1172
1303
  // ── Public API ────────────────────────────────────────────────────────────
1173
1304
  /**
1174
1305
  * Spill an evicted L1 entry to disk.
@@ -1204,12 +1335,16 @@ var DiskTier = class {
1204
1335
  };
1205
1336
  const packed = pack2(payload);
1206
1337
  if (packed.length > this.opts.entryMaxBytes) return;
1207
- final = this.encrypt(packed);
1338
+ const header = Buffer.allocUnsafe(V2_HEADER_LEN);
1339
+ DISK_MAGIC_V2.copy(header, 0);
1340
+ header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
1341
+ final = Buffer.concat([header, this.encryptV2(packed)]);
1208
1342
  } catch (err) {
1209
1343
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1210
1344
  return;
1211
1345
  }
1212
- const filePath = this.keyToPath(key);
1346
+ const hash = this.keyToHash(key);
1347
+ const filePath = this.hashToWritePath(hash, entry.expiresAt);
1213
1348
  this.diskUsageBytes += final.length;
1214
1349
  this.fileCount++;
1215
1350
  try {
@@ -1227,9 +1362,24 @@ var DiskTier = class {
1227
1362
  if (this.isForbidden(key)) return null;
1228
1363
  this.ensureDir();
1229
1364
  if (!this.dirReady) return null;
1230
- const filePath = this.keyToPath(key);
1365
+ const hash = this.keyToHash(key);
1366
+ const filePath = this.findFilePath(hash);
1367
+ if (!filePath) return null;
1231
1368
  try {
1232
- if (!fs.existsSync(filePath)) return null;
1369
+ const filename = path.basename(filePath);
1370
+ if (filename.length === 77 && filename[64] === "_") {
1371
+ const expiresAt = parseInt(filename.slice(65), 16);
1372
+ if (expiresAt <= Date.now()) {
1373
+ try {
1374
+ const sz = fs.statSync(filePath).size;
1375
+ fs.unlinkSync(filePath);
1376
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1377
+ this.fileCount = Math.max(0, this.fileCount - 1);
1378
+ } catch {
1379
+ }
1380
+ return null;
1381
+ }
1382
+ }
1233
1383
  const stat = fs.statSync(filePath);
1234
1384
  if (stat.size > this.opts.entryMaxBytes) {
1235
1385
  fs.unlinkSync(filePath);
@@ -1244,10 +1394,20 @@ var DiskTier = class {
1244
1394
  } catch {
1245
1395
  }
1246
1396
  let decrypted;
1247
- try {
1248
- decrypted = this.decrypt(raw);
1249
- } catch {
1250
- return null;
1397
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1398
+ const expiresAt = Number(raw.readBigUInt64LE(8));
1399
+ if (expiresAt <= Date.now()) return null;
1400
+ try {
1401
+ decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN));
1402
+ } catch {
1403
+ return null;
1404
+ }
1405
+ } else {
1406
+ try {
1407
+ decrypted = this.decrypt(raw);
1408
+ } catch {
1409
+ return null;
1410
+ }
1251
1411
  }
1252
1412
  const payload = unpack2(decrypted);
1253
1413
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
@@ -1263,14 +1423,14 @@ var DiskTier = class {
1263
1423
  }
1264
1424
  /** Explicitly delete a key from disk (cache invalidation). */
1265
1425
  delete(key) {
1266
- const filePath = this.keyToPath(key);
1426
+ const hash = this.keyToHash(key);
1427
+ const filePath = this.findFilePath(hash);
1428
+ if (!filePath) return;
1267
1429
  try {
1268
- if (fs.existsSync(filePath)) {
1269
- const stat = fs.statSync(filePath);
1270
- fs.unlinkSync(filePath);
1271
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1272
- this.fileCount = Math.max(0, this.fileCount - 1);
1273
- }
1430
+ const stat = fs.statSync(filePath);
1431
+ fs.unlinkSync(filePath);
1432
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1433
+ this.fileCount = Math.max(0, this.fileCount - 1);
1274
1434
  } catch {
1275
1435
  }
1276
1436
  }
@@ -1278,9 +1438,45 @@ var DiskTier = class {
1278
1438
  purgeExpired() {
1279
1439
  this.ensureDir();
1280
1440
  if (!this.dirReady) return 0;
1441
+ const now = Date.now();
1281
1442
  let purged = 0;
1443
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1282
1444
  for (const filePath of this.walkCacheFiles()) {
1445
+ const filename = path.basename(filePath);
1446
+ if (filename.length === 77 && filename[64] === "_") {
1447
+ const expiresAt = parseInt(filename.slice(65), 16);
1448
+ if (expiresAt <= now) {
1449
+ try {
1450
+ const sz = fs.statSync(filePath).size;
1451
+ fs.unlinkSync(filePath);
1452
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1453
+ this.fileCount = Math.max(0, this.fileCount - 1);
1454
+ purged++;
1455
+ } catch {
1456
+ }
1457
+ }
1458
+ continue;
1459
+ }
1460
+ let fd = -1;
1283
1461
  try {
1462
+ fd = fs.openSync(filePath, "r");
1463
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1464
+ fs.closeSync(fd);
1465
+ fd = -1;
1466
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1467
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1468
+ if (expiresAt <= now) {
1469
+ try {
1470
+ const sz = fs.statSync(filePath).size;
1471
+ fs.unlinkSync(filePath);
1472
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1473
+ this.fileCount = Math.max(0, this.fileCount - 1);
1474
+ purged++;
1475
+ } catch {
1476
+ }
1477
+ }
1478
+ continue;
1479
+ }
1284
1480
  const stat = fs.statSync(filePath);
1285
1481
  if (stat.size > this.opts.entryMaxBytes) {
1286
1482
  fs.unlinkSync(filePath);
@@ -1300,13 +1496,116 @@ var DiskTier = class {
1300
1496
  continue;
1301
1497
  }
1302
1498
  const payload = unpack2(dec);
1303
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
1499
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1304
1500
  fs.unlinkSync(filePath);
1305
1501
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1306
1502
  this.fileCount = Math.max(0, this.fileCount - 1);
1307
1503
  purged++;
1308
1504
  }
1309
1505
  } catch {
1506
+ } finally {
1507
+ if (fd >= 0) try {
1508
+ fs.closeSync(fd);
1509
+ } catch {
1510
+ }
1511
+ }
1512
+ }
1513
+ return purged;
1514
+ }
1515
+ /**
1516
+ * Purge expired entries from exactly one of the 256 subdirectory buckets, then
1517
+ * advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
1518
+ * the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
1519
+ * of landing as one large synchronous burst every 5 minutes.
1520
+ *
1521
+ * V3 files: expiresAt is encoded in the filename — live entries skip with zero
1522
+ * file I/O (just readdirSync + string parse). Expired entries: statSync + unlinkSync.
1523
+ *
1524
+ * Returns the number of entries deleted in this tick.
1525
+ */
1526
+ purgeNextBucket() {
1527
+ this.ensureDir();
1528
+ if (!this.dirReady) return 0;
1529
+ const bucket = this._nextJanitorBucket.toString(16).padStart(2, "0");
1530
+ this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
1531
+ const bucketPath = path.join(this.opts.dir, bucket);
1532
+ let files;
1533
+ try {
1534
+ files = fs.readdirSync(bucketPath);
1535
+ } catch {
1536
+ return 0;
1537
+ }
1538
+ const now = Date.now();
1539
+ let purged = 0;
1540
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1541
+ for (const file of files) {
1542
+ if (file.length === 77 && file[64] === "_") {
1543
+ const expiresAt = parseInt(file.slice(65), 16);
1544
+ if (expiresAt <= now) {
1545
+ const filePath2 = path.join(bucketPath, file);
1546
+ try {
1547
+ const sz = fs.statSync(filePath2).size;
1548
+ fs.unlinkSync(filePath2);
1549
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1550
+ this.fileCount = Math.max(0, this.fileCount - 1);
1551
+ purged++;
1552
+ } catch {
1553
+ }
1554
+ }
1555
+ continue;
1556
+ }
1557
+ const filePath = path.join(bucketPath, file);
1558
+ let fd = -1;
1559
+ try {
1560
+ fd = fs.openSync(filePath, "r");
1561
+ const bytesRead = fs.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1562
+ fs.closeSync(fd);
1563
+ fd = -1;
1564
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1565
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1566
+ if (expiresAt <= now) {
1567
+ try {
1568
+ const sz = fs.statSync(filePath).size;
1569
+ fs.unlinkSync(filePath);
1570
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1571
+ this.fileCount = Math.max(0, this.fileCount - 1);
1572
+ purged++;
1573
+ } catch {
1574
+ }
1575
+ }
1576
+ continue;
1577
+ }
1578
+ const stat = fs.statSync(filePath);
1579
+ if (stat.size > this.opts.entryMaxBytes) {
1580
+ fs.unlinkSync(filePath);
1581
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1582
+ this.fileCount = Math.max(0, this.fileCount - 1);
1583
+ purged++;
1584
+ continue;
1585
+ }
1586
+ const raw = fs.readFileSync(filePath);
1587
+ let dec;
1588
+ try {
1589
+ dec = this.decrypt(raw);
1590
+ } catch {
1591
+ fs.unlinkSync(filePath);
1592
+ this.fileCount = Math.max(0, this.fileCount - 1);
1593
+ purged++;
1594
+ continue;
1595
+ }
1596
+ const payload = unpack2(dec);
1597
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1598
+ fs.unlinkSync(filePath);
1599
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1600
+ this.fileCount = Math.max(0, this.fileCount - 1);
1601
+ purged++;
1602
+ }
1603
+ } catch {
1604
+ } finally {
1605
+ if (fd >= 0) try {
1606
+ fs.closeSync(fd);
1607
+ } catch {
1608
+ }
1310
1609
  }
1311
1610
  }
1312
1611
  return purged;
@@ -1382,6 +1681,12 @@ var L2CircuitBreaker = class {
1382
1681
  return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1383
1682
  }
1384
1683
  };
1684
+ function deepFreeze(obj) {
1685
+ if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
1686
+ Object.freeze(obj);
1687
+ for (const v of Object.values(obj)) deepFreeze(v);
1688
+ return obj;
1689
+ }
1385
1690
  function inferPriority(cacheKey) {
1386
1691
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1387
1692
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1413,7 +1718,9 @@ var CacheService = class _CacheService {
1413
1718
  redisConnecting = null;
1414
1719
  cb;
1415
1720
  snapshotLoaded = false;
1721
+ _readyPromise = Promise.resolve();
1416
1722
  cleanupInterval = null;
1723
+ diskJanitorInterval = null;
1417
1724
  oomInterval = null;
1418
1725
  metricsInterval = null;
1419
1726
  _shutdownHandler = null;
@@ -1489,7 +1796,11 @@ var CacheService = class _CacheService {
1489
1796
  instanceName: options.instanceName ?? "",
1490
1797
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1491
1798
  tracer: options.tracer,
1492
- notFoundTtl: options.notFoundTtl ?? 0
1799
+ notFoundTtl: options.notFoundTtl ?? 0,
1800
+ warmKeys: options.warmKeys,
1801
+ onHit: options.onHit,
1802
+ onMiss: options.onMiss,
1803
+ frozen: options.frozen ?? false
1493
1804
  };
1494
1805
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1495
1806
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -1509,7 +1820,9 @@ var CacheService = class _CacheService {
1509
1820
  maxEntries: this.opts.l1MaxEntries,
1510
1821
  categories: this.opts.categoryLimits,
1511
1822
  diskSpill: (key, entry) => {
1512
- void this.disk.save(key, entry);
1823
+ setImmediate(() => {
1824
+ void this.disk.save(key, entry);
1825
+ });
1513
1826
  },
1514
1827
  onEviction: options.onEviction,
1515
1828
  logger
@@ -1526,12 +1839,14 @@ var CacheService = class _CacheService {
1526
1839
  process.once("SIGINT", this._shutdownHandler);
1527
1840
  this.cleanupInterval = setInterval(() => {
1528
1841
  const cleaned = this.l1.cleanup();
1529
- const diskPurged = this.disk.purgeExpired();
1530
- if (cleaned > 0 || diskPurged > 0) {
1531
- this.logger.debug("Periodic cache cleanup", { cleaned, diskPurged });
1532
- }
1842
+ if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
1533
1843
  }, 5 * 60 * 1e3);
1534
1844
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
1845
+ this.diskJanitorInterval = setInterval(() => {
1846
+ const purged = this.disk.purgeNextBucket();
1847
+ if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
1848
+ }, 3e4);
1849
+ if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
1535
1850
  if (this.opts.oomProtection) {
1536
1851
  this.oomInterval = setInterval(() => {
1537
1852
  const mem = process.memoryUsage();
@@ -1561,6 +1876,9 @@ var CacheService = class _CacheService {
1561
1876
  this.instanceId = crypto2.randomBytes(8).toString("hex");
1562
1877
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
1563
1878
  this.initBackplane();
1879
+ if (this.opts.warmKeys) {
1880
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
1881
+ }
1564
1882
  }
1565
1883
  // ── Singleton factory ─────────────────────────────────────────────────────
1566
1884
  /**
@@ -1620,15 +1938,22 @@ var CacheService = class _CacheService {
1620
1938
  if (j === 0) return ttlMs;
1621
1939
  return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
1622
1940
  }
1941
+ /** Shared no-op span for the common case where no tracer is configured.
1942
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
1943
+ static _nullSpan = {
1944
+ setAttribute() {
1945
+ return this;
1946
+ },
1947
+ setStatus() {
1948
+ return this;
1949
+ },
1950
+ end() {
1951
+ }
1952
+ };
1623
1953
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1624
1954
  _startSpan(name) {
1625
1955
  if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1626
- return { setAttribute() {
1627
- return this;
1628
- }, setStatus() {
1629
- return this;
1630
- }, end() {
1631
- } };
1956
+ return _CacheService._nullSpan;
1632
1957
  }
1633
1958
  initBackplane() {
1634
1959
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -1668,6 +1993,7 @@ var CacheService = class _CacheService {
1668
1993
  if (msg.op === "del") {
1669
1994
  this.l1.delete(msg.key);
1670
1995
  setImmediate(() => this.disk.delete(msg.key));
1996
+ this._cascadeDependencies(msg.key);
1671
1997
  } else if (msg.op === "del-glob") {
1672
1998
  this.l1.deletePattern(msg.key);
1673
1999
  }
@@ -1816,7 +2142,7 @@ var CacheService = class _CacheService {
1816
2142
  */
1817
2143
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1818
2144
  const span = this._startSpan("tricache.get");
1819
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2145
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1820
2146
  const k = this.nk(cacheKey);
1821
2147
  this.counters.gets++;
1822
2148
  const l1Hit = this.l1.get(k);
@@ -1834,14 +2160,14 @@ var CacheService = class _CacheService {
1834
2160
  }
1835
2161
  } else {
1836
2162
  this.logger.debug("L1 hit");
1837
- if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
1838
- const now = Date.now();
2163
+ if (opts.refreshAhead || opts.xfetchBeta) {
2164
+ const now = l1Hit.fetchedAt ?? Date.now();
1839
2165
  const remaining = l1Hit.expiresAt - now;
1840
2166
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
1841
- const priority2 = opts.priority ?? inferPriority(cacheKey);
1842
- const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
1843
- const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
1844
- if (shouldRefreshAhead || shouldXFetch) {
2167
+ const shouldRefreshAhead = !!opts.refreshAhead ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
2168
+ const shouldXFetch = !!opts.xfetchBeta && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
2169
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2170
+ const priority2 = opts.priority ?? inferPriority(cacheKey);
1845
2171
  this.revalidating.add(k);
1846
2172
  void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
1847
2173
  this.counters.swrRevalidations++;
@@ -1853,6 +2179,8 @@ var CacheService = class _CacheService {
1853
2179
  }
1854
2180
  }
1855
2181
  this.counters.l1Hits++;
2182
+ this.opts.onHit?.(cacheKey, "l1");
2183
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
1856
2184
  span.setAttribute("cache.hit", "l1").end();
1857
2185
  return l1Hit.value;
1858
2186
  }
@@ -1869,6 +2197,7 @@ var CacheService = class _CacheService {
1869
2197
  const parsed = JSON.parse(decrypted);
1870
2198
  this.l1.set(k, parsed, ttlMs, priority);
1871
2199
  this.counters.l2Hits++;
2200
+ this.opts.onHit?.(cacheKey, "l2");
1872
2201
  this.logger.debug("L2 hit (Redis)", { cacheKey });
1873
2202
  span.setAttribute("cache.hit", "l2").end();
1874
2203
  return parsed;
@@ -1888,6 +2217,7 @@ var CacheService = class _CacheService {
1888
2217
  const l1Check = this.l1.get(k);
1889
2218
  if (l1Check !== null) {
1890
2219
  this.counters.diskHits++;
2220
+ this.opts.onHit?.(cacheKey, "disk");
1891
2221
  this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1892
2222
  span.setAttribute("cache.hit", "disk").end();
1893
2223
  return l1Check.value;
@@ -1895,6 +2225,7 @@ var CacheService = class _CacheService {
1895
2225
  }
1896
2226
  }
1897
2227
  span.setAttribute("cache.hit", "miss");
2228
+ this.opts.onMiss?.(cacheKey);
1898
2229
  const existing = this.inflight.get(k);
1899
2230
  if (existing) {
1900
2231
  this.counters.stampedes++;
@@ -1913,6 +2244,7 @@ var CacheService = class _CacheService {
1913
2244
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
1914
2245
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1915
2246
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
2247
+ if (opts.tags?.length) await this._registerTags(k, opts.tags, Math.ceil(effectiveTtl / 1e3));
1916
2248
  if (!this._redisDisabled) {
1917
2249
  try {
1918
2250
  const client = await this.getRedis();
@@ -1973,38 +2305,13 @@ var CacheService = class _CacheService {
1973
2305
  /** Explicitly write a value into L1 (+ L2 in production). */
1974
2306
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
1975
2307
  const span = this._startSpan("tricache.set");
1976
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2308
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1977
2309
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1978
2310
  const p = priority ?? inferPriority(cacheKey);
1979
2311
  const k = this.nk(cacheKey);
1980
2312
  this.counters.sets++;
1981
2313
  this.l1.set(k, data, ttlMs, p);
1982
- if (opts?.tags?.length) {
1983
- for (const tag of opts.tags) {
1984
- const tagKey = this.nk(`_tag_:${tag}`);
1985
- let members = this.tagIndex.get(tagKey);
1986
- if (!members) {
1987
- members = /* @__PURE__ */ new Set();
1988
- this.tagIndex.set(tagKey, members);
1989
- }
1990
- members.add(k);
1991
- }
1992
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1993
- try {
1994
- const client = await this.getRedis();
1995
- const pl = client.pipeline();
1996
- for (const tag of opts.tags) {
1997
- const tagKey = this.nk(`_tag_:${tag}`);
1998
- pl.sadd(tagKey, k);
1999
- pl.expire(tagKey, ttlSeconds + 3600);
2000
- }
2001
- await pl.exec();
2002
- this.cb.onSuccess();
2003
- } catch {
2004
- this.cb.onFailure();
2005
- }
2006
- }
2007
- }
2314
+ if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
2008
2315
  if (opts?.dependsOn?.length) {
2009
2316
  for (const pattern of opts.dependsOn) {
2010
2317
  const nsPattern = this.nk(pattern);
@@ -2031,6 +2338,36 @@ var CacheService = class _CacheService {
2031
2338
  void this.publishInvalidation("del", k);
2032
2339
  span.end();
2033
2340
  }
2341
+ /**
2342
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
2343
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
2344
+ */
2345
+ async _registerTags(k, tags, ttlSeconds) {
2346
+ for (const tag of tags) {
2347
+ const tagKey = this.nk(`_tag_:${tag}`);
2348
+ let members = this.tagIndex.get(tagKey);
2349
+ if (!members) {
2350
+ members = /* @__PURE__ */ new Set();
2351
+ this.tagIndex.set(tagKey, members);
2352
+ }
2353
+ members.add(k);
2354
+ }
2355
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2356
+ try {
2357
+ const client = await this.getRedis();
2358
+ const pl = client.pipeline();
2359
+ for (const tag of tags) {
2360
+ const tagKey = this.nk(`_tag_:${tag}`);
2361
+ pl.sadd(tagKey, k);
2362
+ pl.expire(tagKey, ttlSeconds + 3600);
2363
+ }
2364
+ await pl.exec();
2365
+ this.cb.onSuccess();
2366
+ } catch {
2367
+ this.cb.onFailure();
2368
+ }
2369
+ }
2370
+ }
2034
2371
  /**
2035
2372
  * Delete one key or a glob pattern (supports `*` wildcard).
2036
2373
  *
@@ -2040,7 +2377,7 @@ var CacheService = class _CacheService {
2040
2377
  */
2041
2378
  async delete(cacheKey) {
2042
2379
  const span = this._startSpan("tricache.delete");
2043
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2380
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2044
2381
  const isPattern = cacheKey.includes("*");
2045
2382
  const k = this.nk(cacheKey);
2046
2383
  this.counters.deletes++;
@@ -2048,7 +2385,7 @@ var CacheService = class _CacheService {
2048
2385
  this.l1.deletePattern(k);
2049
2386
  } else {
2050
2387
  this.l1.delete(k);
2051
- this.disk.delete(k);
2388
+ setImmediate(() => this.disk.delete(k));
2052
2389
  this._cascadeDependencies(k);
2053
2390
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2054
2391
  }
@@ -2204,6 +2541,33 @@ var CacheService = class _CacheService {
2204
2541
  yield [k, entry.value !== void 0 ? entry.value : entry.data];
2205
2542
  }
2206
2543
  }
2544
+ /**
2545
+ * High-throughput bulk scan over all live L1 entries.
2546
+ *
2547
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
2548
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
2549
+ * caller uses the `offset` parameter instead of pre-slicing.
2550
+ *
2551
+ * ```typescript
2552
+ * // Zero extra string allocations — use rawKey + offset directly:
2553
+ * cache.scan((rawKey, value, offset) => {
2554
+ * const key = rawKey.slice(offset); // allocate only if needed
2555
+ * sync(key, value as User);
2556
+ * });
2557
+ * ```
2558
+ *
2559
+ * @param fn Called once per live L1 entry.
2560
+ * `rawKey` — key with namespace prefix still attached.
2561
+ * `value` — deserialized cached value.
2562
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
2563
+ */
2564
+ scan(fn) {
2565
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2566
+ this.l1.scan((key, entry, pfx) => {
2567
+ const value = entry.value !== void 0 ? entry.value : entry.data;
2568
+ fn(key, value, pfx);
2569
+ }, prefixLen);
2570
+ }
2207
2571
  /**
2208
2572
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
2209
2573
  * Returns `false` if the key is absent or already expired.
@@ -2245,7 +2609,8 @@ var CacheService = class _CacheService {
2245
2609
  *
2246
2610
  * @param keys - Array of cache keys.
2247
2611
  * @param fetchFn - Called with only the keys that missed L1.
2248
- * @param ttl - TTL in seconds for newly fetched values.
2612
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
2613
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
2249
2614
  */
2250
2615
  async mget(keys, fetchFn, ttl = 300, priority) {
2251
2616
  const result = new Array(keys.length);
@@ -2267,12 +2632,27 @@ var CacheService = class _CacheService {
2267
2632
  const v = fetched[missKeys[j]];
2268
2633
  result[missIndexes[j]] = v;
2269
2634
  if (v !== void 0) {
2270
- await this.set(missKeys[j], v, ttl, priority);
2635
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
2636
+ await this.set(missKeys[j], v, resolvedTtl, priority);
2271
2637
  }
2272
2638
  }
2273
2639
  }
2274
2640
  return result;
2275
2641
  }
2642
+ /**
2643
+ * Returns a Promise that resolves once the cache is fully initialised and any
2644
+ * startup warming configured via `warmKeys` has completed.
2645
+ *
2646
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
2647
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
2648
+ *
2649
+ * @example
2650
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
2651
+ * await cache.ready(); // gate traffic until warm
2652
+ */
2653
+ ready() {
2654
+ return this._readyPromise;
2655
+ }
2276
2656
  /**
2277
2657
  * Batch write — set multiple entries in a single call.
2278
2658
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -2313,7 +2693,7 @@ var CacheService = class _CacheService {
2313
2693
  * const loaded = await cache.warmFromL2('org:*');
2314
2694
  * console.log(`Warmed ${loaded} keys from Redis`);
2315
2695
  */
2316
- async warmFromL2(pattern) {
2696
+ async warmFromL2(pattern, opts) {
2317
2697
  if (this._redisDisabled) return 0;
2318
2698
  try {
2319
2699
  const client = await this.getRedis();
@@ -2342,8 +2722,9 @@ var CacheService = class _CacheService {
2342
2722
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2343
2723
  const parsed = JSON.parse(decrypted);
2344
2724
  const remainingMs = 10 * 60 * 1e3;
2345
- this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
2725
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
2346
2726
  loaded++;
2727
+ ;
2347
2728
  } catch {
2348
2729
  }
2349
2730
  }
@@ -2391,6 +2772,58 @@ var CacheService = class _CacheService {
2391
2772
  }
2392
2773
  }
2393
2774
  }
2775
+ /**
2776
+ * Invalidate all keys associated with any of the given tags in a single operation.
2777
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
2778
+ * reducing latency when invalidating several related tags together.
2779
+ *
2780
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
2781
+ * synchronously before the Redis round-trip.
2782
+ *
2783
+ * @example
2784
+ * // Instead of three serial round-trips:
2785
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
2786
+ */
2787
+ async invalidateTags(tags) {
2788
+ if (tags.length === 0) return;
2789
+ if (tags.length === 1) {
2790
+ await this.invalidateTag(tags[0]);
2791
+ return;
2792
+ }
2793
+ const tagKeys = [];
2794
+ const allMembers = /* @__PURE__ */ new Set();
2795
+ for (const tag of tags) {
2796
+ const tagKey = this.nk(`_tag_:${tag}`);
2797
+ tagKeys.push(tagKey);
2798
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
2799
+ for (const k of members) allMembers.add(k);
2800
+ this.tagIndex.delete(tagKey);
2801
+ }
2802
+ for (const k of allMembers) {
2803
+ this.l1.delete(k);
2804
+ this.disk.delete(k);
2805
+ }
2806
+ if (!this._redisDisabled) {
2807
+ try {
2808
+ const client = await this.getRedis();
2809
+ const pl = client.pipeline();
2810
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
2811
+ const smResults = await pl.exec();
2812
+ const toDelete = [...allMembers];
2813
+ for (const [err, redisMembers] of smResults) {
2814
+ if (!err && redisMembers) {
2815
+ for (const k of redisMembers) {
2816
+ if (!allMembers.has(k)) toDelete.push(k);
2817
+ }
2818
+ }
2819
+ }
2820
+ const keysToRemove = [...toDelete, ...tagKeys];
2821
+ if (keysToRemove.length > 0) await client.del(...keysToRemove);
2822
+ } catch (err) {
2823
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
2824
+ }
2825
+ }
2826
+ }
2394
2827
  /**
2395
2828
  * Measure L1 / disk / Redis latency.
2396
2829
  * Useful for health checks and dashboards.
@@ -2663,6 +3096,7 @@ var CacheService = class _CacheService {
2663
3096
  /** Close Redis connections and stop all background timers. */
2664
3097
  async destroy() {
2665
3098
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
3099
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
2666
3100
  if (this.oomInterval) clearInterval(this.oomInterval);
2667
3101
  if (this.metricsInterval) clearInterval(this.metricsInterval);
2668
3102
  if (this._shutdownHandler) {