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.cjs CHANGED
@@ -206,10 +206,11 @@ var CacheEncryption = class {
206
206
  const iv2 = this._nextCtrIV();
207
207
  const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._key, iv2);
208
208
  const enc2 = c2.update(plaintext, "utf8");
209
- c2.final();
210
- const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length);
209
+ const fin = c2.final();
210
+ const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
211
211
  iv2.copy(out2, 0);
212
212
  enc2.copy(out2, CTR_IV_BYTES);
213
+ if (fin.length > 0) fin.copy(out2, CTR_IV_BYTES + enc2.length);
213
214
  return PREFIX_CTR + out2.toString("base64");
214
215
  }
215
216
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
@@ -259,8 +260,8 @@ var CacheEncryption = class {
259
260
  const ct2 = combined2.subarray(CTR_IV_BYTES);
260
261
  const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
261
262
  const plain2 = d2.update(ct2);
262
- d2.final();
263
- return plain2.toString("utf8");
263
+ const fin = d2.final();
264
+ return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
264
265
  }
265
266
  const is256 = value.startsWith(PREFIX_256);
266
267
  const is128 = value.startsWith(PREFIX_128);
@@ -294,11 +295,12 @@ var CacheEncryption = class {
294
295
  const iv2 = this._nextCtrIV();
295
296
  const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._key, iv2);
296
297
  const enc2 = c2.update(data);
297
- c2.final();
298
- const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length);
298
+ const fin = c2.final();
299
+ const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
299
300
  MAGIC_CTR.copy(out2, 0);
300
301
  iv2.copy(out2, MAGIC_LEN);
301
302
  enc2.copy(out2, MAGIC_LEN + CTR_IV_BYTES);
303
+ if (fin.length > 0) fin.copy(out2, MAGIC_LEN + CTR_IV_BYTES + enc2.length);
302
304
  return out2;
303
305
  }
304
306
  const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
@@ -349,8 +351,8 @@ var CacheEncryption = class {
349
351
  const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
350
352
  const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
351
353
  const plain2 = d2.update(ct2);
352
- d2.final();
353
- return plain2;
354
+ const fin = d2.final();
355
+ return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
354
356
  }
355
357
  const is256 = magic.equals(MAGIC_256);
356
358
  const is128 = magic.equals(MAGIC_128);
@@ -375,11 +377,7 @@ var import_msgpackr = require("msgpackr");
375
377
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
376
378
  var KEY_STAGING_OFFSET = 2e4;
377
379
  var MAX_KEY_BYTES = 512;
378
- function instantiateSync() {
379
- const wasmBytes = Buffer.from(BLOOM_WASM_BASE64, "base64");
380
- const compiled = new WebAssembly.Module(wasmBytes);
381
- return new WebAssembly.Instance(compiled, {});
382
- }
380
+ var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
383
381
  var WasmBloomFilter = class {
384
382
  exports;
385
383
  mem;
@@ -390,26 +388,16 @@ var WasmBloomFilter = class {
390
388
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
391
389
  _insertionCount = 0;
392
390
  constructor() {
393
- const instance = instantiateSync();
391
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
394
392
  this.exports = instance.exports;
395
393
  this.mem = new Uint8Array(this.exports.memory.buffer);
396
394
  const k = 7, p = 0.01;
397
395
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
398
396
  }
399
397
  writeKey(key) {
400
- const max = Math.min(key.length, MAX_KEY_BYTES);
401
- if (max === 0) return 0;
402
- for (let i = 0; i < max; i++) {
403
- const c = key.charCodeAt(i);
404
- if (c > 127) {
405
- const encoded = this.encoder.encode(key);
406
- const len = Math.min(encoded.length, MAX_KEY_BYTES);
407
- this.mem.set(encoded.subarray(0, len), KEY_STAGING_OFFSET);
408
- return len;
409
- }
410
- this.mem[KEY_STAGING_OFFSET + i] = c;
411
- }
412
- return max;
398
+ if (key.length === 0) return 0;
399
+ const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
400
+ return this.encoder.encodeInto(key, target).written;
413
401
  }
414
402
  add(key) {
415
403
  const len = this.writeKey(key);
@@ -449,6 +437,7 @@ var WasmBloomFilter = class {
449
437
  };
450
438
 
451
439
  // src/smart-memory-cache.ts
440
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
452
441
  var EVICTION_BATCH_PERCENT = 0.2;
453
442
  var JsBloomFilter = class {
454
443
  bits;
@@ -527,15 +516,25 @@ var JsBloomFilter = class {
527
516
  return { bitsSet, fillFactor: bitsSet / this.numBits };
528
517
  }
529
518
  };
530
- function createBloomFilter(logger) {
519
+ function createBloomFilter(logger, maxEntries) {
520
+ const LN2_SQ = Math.LN2 * Math.LN2;
521
+ const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
522
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
531
523
  try {
532
524
  const wasm = new WasmBloomFilter();
533
- logger.debug("SmartMemoryCache: WASM BloomFilter active");
534
- return wasm;
525
+ if (wasm.maxCapacity >= maxEntries) {
526
+ logger.debug("SmartMemoryCache: WASM BloomFilter active");
527
+ return wasm;
528
+ }
529
+ logger.debug("SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter", {
530
+ wasmCapacity: wasm.maxCapacity,
531
+ maxEntries,
532
+ optimalBits
533
+ });
535
534
  } catch (err) {
536
535
  logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
537
- return new JsBloomFilter();
538
536
  }
537
+ return new JsBloomFilter(optimalBits, optimalK);
539
538
  }
540
539
  var SKETCH_ROWS = 4;
541
540
  var SKETCH_WIDTH = 512;
@@ -553,32 +552,35 @@ var CountMinSketch = class {
553
552
  }
554
553
  return h;
555
554
  }
556
- /** Four independent bit-mixes from one FNV-1a seed. */
557
- hashes(key) {
555
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
556
+ increment(key) {
558
557
  const h = this.fnv32(key);
559
558
  const h1 = (h ^ h >>> 16) >>> 0;
560
559
  const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
561
560
  const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
562
561
  const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
563
- return [h1, h2, h3, h4];
564
- }
565
- /** Record one access. Decays all counters when the insertion threshold is crossed. */
566
- increment(key) {
567
- const [h1, h2, h3, h4] = this.hashes(key);
568
562
  const t = this.table;
569
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
570
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
571
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
572
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
563
+ const i0 = h1 & SKETCH_MASK;
564
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
565
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
566
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
567
+ if (t[i0] < 65535) t[i0]++;
568
+ if (t[i1] < 65535) t[i1]++;
569
+ if (t[i2] < 65535) t[i2]++;
570
+ if (t[i3] < 65535) t[i3]++;
573
571
  if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
574
572
  }
575
573
  /** Minimum-across-rows frequency estimate. */
576
574
  estimate(key) {
577
- const [h1, h2, h3, h4] = this.hashes(key);
575
+ const h = this.fnv32(key);
576
+ const h1 = (h ^ h >>> 16) >>> 0;
577
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
578
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
579
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
578
580
  const t = this.table;
579
581
  return Math.min(
580
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
581
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
582
+ t[h1 & SKETCH_MASK],
583
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
582
584
  t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
583
585
  t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
584
586
  );
@@ -589,6 +591,21 @@ var CountMinSketch = class {
589
591
  this.inserts = 0;
590
592
  }
591
593
  };
594
+ function globMatchParts(parts, first, last, key) {
595
+ if (first.length > 0 && !key.startsWith(first)) return false;
596
+ if (last.length > 0 && !key.endsWith(last)) return false;
597
+ if (first.length + last.length > key.length) return false;
598
+ let pos = first.length;
599
+ const end = key.length - last.length;
600
+ for (let i = 1; i < parts.length - 1; i++) {
601
+ const seg = parts[i];
602
+ if (seg.length === 0) continue;
603
+ const idx = key.indexOf(seg, pos);
604
+ if (idx === -1 || idx + seg.length > end) return false;
605
+ pos = idx + seg.length;
606
+ }
607
+ return true;
608
+ }
592
609
  var SmartMemoryCache = class {
593
610
  cache = /* @__PURE__ */ new Map();
594
611
  opts;
@@ -611,7 +628,7 @@ var SmartMemoryCache = class {
611
628
  _bloomDirtyCount = 0;
612
629
  constructor(opts, existing) {
613
630
  this.opts = opts;
614
- this.bloom = createBloomFilter(opts.logger);
631
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
615
632
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
616
633
  if (existing) {
617
634
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -671,7 +688,14 @@ var SmartMemoryCache = class {
671
688
  const catSz = this.categorySize.get(category) ?? 0;
672
689
  const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
673
690
  const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
674
- if (!catOvf && !glbOvf) return;
691
+ if (!catOvf && !glbOvf) {
692
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * 0.9);
693
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * 0.9);
694
+ if (entryWatermark || byteWatermark) {
695
+ this.smartEvict(category, false);
696
+ }
697
+ return;
698
+ }
675
699
  this.smartEvict(category, catOvf);
676
700
  }
677
701
  score(entry, catBonus, now, key) {
@@ -694,7 +718,8 @@ var SmartMemoryCache = class {
694
718
  * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
695
719
  */
696
720
  maybeRebuildBloom() {
697
- if (this._bloomDirtyCount > this.bloom.maxCapacity >>> 2 || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
721
+ const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
722
+ if (this._bloomDirtyCount > dirtyThreshold || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
698
723
  this.bloom.rebuild(this.cache.keys());
699
724
  this._bloomDirtyCount = 0;
700
725
  }
@@ -764,12 +789,15 @@ var SmartMemoryCache = class {
764
789
  }
765
790
  entry.hits++;
766
791
  entry.lastAccess = now;
767
- this.sketch.increment(key);
768
- const cat = this.getCategory(key);
769
- this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
792
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
770
793
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
771
- const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
772
- return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
794
+ _hit.value = value;
795
+ _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
796
+ _hit.expiresAt = entry.expiresAt;
797
+ _hit.ttlMs = entry.ttlMs;
798
+ _hit.delta = entry.delta;
799
+ _hit.fetchedAt = now;
800
+ return _hit;
773
801
  }
774
802
  set(key, data, ttlMs, priority = 2, staleAt, delta) {
775
803
  const packed = (0, import_msgpackr.pack)(data);
@@ -792,7 +820,7 @@ var SmartMemoryCache = class {
792
820
  this.ensureCapacity(cat, size);
793
821
  const now = Date.now();
794
822
  this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
795
- this.bloom.add(key);
823
+ if (!existingEntry) this.bloom.add(key);
796
824
  this.maybeRebuildBloom();
797
825
  this.totalSize += size;
798
826
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
@@ -811,9 +839,27 @@ var SmartMemoryCache = class {
811
839
  }
812
840
  keysMatchingPattern(pattern) {
813
841
  if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
814
- const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
842
+ if (pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1) {
843
+ const prefix = pattern.slice(0, -1);
844
+ const catKeys = this.categoryKeys.get(prefix);
845
+ if (catKeys !== void 0) return Array.from(catKeys);
846
+ }
847
+ const firstStar = pattern.indexOf("*");
848
+ if (firstStar === pattern.lastIndexOf("*")) {
849
+ const prefix = pattern.slice(0, firstStar);
850
+ const suffix = pattern.slice(firstStar + 1);
851
+ const minLen = prefix.length + suffix.length;
852
+ const out2 = [];
853
+ for (const k of this.cache.keys()) {
854
+ if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out2.push(k);
855
+ }
856
+ return out2;
857
+ }
858
+ const parts = pattern.split("*");
859
+ const first = parts[0];
860
+ const last = parts[parts.length - 1];
815
861
  const out = [];
816
- for (const k of this.cache.keys()) if (re.test(k)) out.push(k);
862
+ for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
817
863
  return out;
818
864
  }
819
865
  deletePattern(pattern) {
@@ -970,6 +1016,30 @@ var SmartMemoryCache = class {
970
1016
  if (entry.expiresAt > now) yield [key, entry];
971
1017
  }
972
1018
  }
1019
+ /**
1020
+ * Non-generator bulk scan over all live entries.
1021
+ *
1022
+ * Faster than the generator-based iterators for bulk operations because:
1023
+ * - No generator state-machine overhead (no yield/resume suspend points).
1024
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
1025
+ * - The same Map call-site is used by a single plain `for` loop instead of being
1026
+ * shared across three competing generator functions, giving V8's IC a cleaner
1027
+ * monomorphic profile for this path.
1028
+ *
1029
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
1030
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
1031
+ * key, avoiding the allocation entirely for callers that don't.
1032
+ *
1033
+ * @param fn Called once per live entry.
1034
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
1035
+ * Pass 0 when no namespace is configured.
1036
+ */
1037
+ scan(fn, prefixLen) {
1038
+ const now = Date.now();
1039
+ for (const [key, entry] of this.cache) {
1040
+ if (entry.expiresAt > now) fn(key, entry, prefixLen);
1041
+ }
1042
+ }
973
1043
  /**
974
1044
  * Yields only the keys of live entries — no intermediate tuple allocation.
975
1045
  * Use this instead of liveEntries() when you only need keys.
@@ -1107,6 +1177,8 @@ var AES_ALGO = "aes-256-gcm";
1107
1177
  var IV_BYTES2 = 12;
1108
1178
  var TAG_BYTES2 = 16;
1109
1179
  var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1180
+ var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1181
+ var V2_HEADER_LEN = 16;
1110
1182
  var DISK_TIER_VERSION = 1;
1111
1183
  var DiskTier = class {
1112
1184
  opts;
@@ -1115,6 +1187,8 @@ var DiskTier = class {
1115
1187
  usageCounted = false;
1116
1188
  fileCount = 0;
1117
1189
  // maintained in-memory; avoids walkCacheFiles() in stats
1190
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1191
+ _nextJanitorBucket = 0;
1118
1192
  constructor(opts) {
1119
1193
  this.opts = opts;
1120
1194
  }
@@ -1149,18 +1223,46 @@ var DiskTier = class {
1149
1223
  }
1150
1224
  }
1151
1225
  /**
1152
- * Map a cache key to its on-disk path.
1226
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
1227
+ * Kept separate from path construction so callers can find files by prefix
1228
+ * without knowing which filename generation was used when the file was written.
1229
+ */
1230
+ keyToHash(key) {
1231
+ return import_crypto2.default.createHash("sha256").update(key, "utf8").digest("hex");
1232
+ }
1233
+ /**
1234
+ * Build the write path for a NEW file (V3 generation).
1235
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1236
+ * with zero file I/O — after readdirSync() it only needs a string parse.
1153
1237
  *
1154
- * Files are sharded into two-character hex prefix subdirectories to avoid
1155
- * putting thousands of flat files into a single directory node — which
1156
- * degrades EXT4/NTFS performance at scale.
1238
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1239
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1157
1240
  *
1158
- * key → SHA-256 hex e3b0c442...
1159
- * path → {dir}/e3/e3b0c442...
1241
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1160
1242
  */
1161
- keyToPath(key) {
1162
- const hash = import_crypto2.default.createHash("sha256").update(key, "utf8").digest("hex");
1163
- return import_path.default.join(this.opts.dir, hash.slice(0, 2), hash);
1243
+ hashToWritePath(hash, expiresAt) {
1244
+ return import_path.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
1245
+ }
1246
+ /**
1247
+ * Find the on-disk file for a key hash, handling all filename generations:
1248
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1249
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
1250
+ * Returns null when the bucket dir does not exist or the key is absent.
1251
+ */
1252
+ findFilePath(hash) {
1253
+ const bucketPath = import_path.default.join(this.opts.dir, hash.slice(0, 2));
1254
+ let files;
1255
+ try {
1256
+ files = import_fs.default.readdirSync(bucketPath);
1257
+ } catch {
1258
+ return null;
1259
+ }
1260
+ let match;
1261
+ for (const f of files) {
1262
+ if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
1263
+ }
1264
+ if (!match) return null;
1265
+ return import_path.default.join(bucketPath, match);
1164
1266
  }
1165
1267
  /**
1166
1268
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -1211,6 +1313,35 @@ var DiskTier = class {
1211
1313
  d.setAuthTag(tag);
1212
1314
  return Buffer.concat([d.update(ct), d.final()]);
1213
1315
  }
1316
+ /**
1317
+ * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1318
+ * the outer 16-byte header alongside the plaintext expiresAt).
1319
+ * Returns the buffer unchanged when no encryption key is configured.
1320
+ */
1321
+ encryptV2(data) {
1322
+ const key = this.opts.encryptionKey;
1323
+ if (!key) return data;
1324
+ const iv = import_crypto2.default.randomBytes(IV_BYTES2);
1325
+ const c = import_crypto2.default.createCipheriv(AES_ALGO, key, iv);
1326
+ const enc = Buffer.concat([c.update(data), c.final()]);
1327
+ const tag = c.getAuthTag();
1328
+ return Buffer.concat([iv, tag, enc]);
1329
+ }
1330
+ /**
1331
+ * V2 decryption — inner payload after stripping the 16-byte header.
1332
+ * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1333
+ * without a key the payload is raw msgpack.
1334
+ */
1335
+ decryptV2(inner) {
1336
+ const key = this.opts.encryptionKey;
1337
+ if (!key) return inner;
1338
+ const iv = inner.subarray(0, IV_BYTES2);
1339
+ const tag = inner.subarray(IV_BYTES2, IV_BYTES2 + TAG_BYTES2);
1340
+ const ct = inner.subarray(IV_BYTES2 + TAG_BYTES2);
1341
+ const d = import_crypto2.default.createDecipheriv(AES_ALGO, key, iv);
1342
+ d.setAuthTag(tag);
1343
+ return Buffer.concat([d.update(ct), d.final()]);
1344
+ }
1214
1345
  // ── Public API ────────────────────────────────────────────────────────────
1215
1346
  /**
1216
1347
  * Spill an evicted L1 entry to disk.
@@ -1246,12 +1377,16 @@ var DiskTier = class {
1246
1377
  };
1247
1378
  const packed = (0, import_msgpackr2.pack)(payload);
1248
1379
  if (packed.length > this.opts.entryMaxBytes) return;
1249
- final = this.encrypt(packed);
1380
+ const header = Buffer.allocUnsafe(V2_HEADER_LEN);
1381
+ DISK_MAGIC_V2.copy(header, 0);
1382
+ header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
1383
+ final = Buffer.concat([header, this.encryptV2(packed)]);
1250
1384
  } catch (err) {
1251
1385
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1252
1386
  return;
1253
1387
  }
1254
- const filePath = this.keyToPath(key);
1388
+ const hash = this.keyToHash(key);
1389
+ const filePath = this.hashToWritePath(hash, entry.expiresAt);
1255
1390
  this.diskUsageBytes += final.length;
1256
1391
  this.fileCount++;
1257
1392
  try {
@@ -1269,9 +1404,24 @@ var DiskTier = class {
1269
1404
  if (this.isForbidden(key)) return null;
1270
1405
  this.ensureDir();
1271
1406
  if (!this.dirReady) return null;
1272
- const filePath = this.keyToPath(key);
1407
+ const hash = this.keyToHash(key);
1408
+ const filePath = this.findFilePath(hash);
1409
+ if (!filePath) return null;
1273
1410
  try {
1274
- if (!import_fs.default.existsSync(filePath)) return null;
1411
+ const filename = import_path.default.basename(filePath);
1412
+ if (filename.length === 77 && filename[64] === "_") {
1413
+ const expiresAt = parseInt(filename.slice(65), 16);
1414
+ if (expiresAt <= Date.now()) {
1415
+ try {
1416
+ const sz = import_fs.default.statSync(filePath).size;
1417
+ import_fs.default.unlinkSync(filePath);
1418
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1419
+ this.fileCount = Math.max(0, this.fileCount - 1);
1420
+ } catch {
1421
+ }
1422
+ return null;
1423
+ }
1424
+ }
1275
1425
  const stat = import_fs.default.statSync(filePath);
1276
1426
  if (stat.size > this.opts.entryMaxBytes) {
1277
1427
  import_fs.default.unlinkSync(filePath);
@@ -1286,10 +1436,20 @@ var DiskTier = class {
1286
1436
  } catch {
1287
1437
  }
1288
1438
  let decrypted;
1289
- try {
1290
- decrypted = this.decrypt(raw);
1291
- } catch {
1292
- return null;
1439
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1440
+ const expiresAt = Number(raw.readBigUInt64LE(8));
1441
+ if (expiresAt <= Date.now()) return null;
1442
+ try {
1443
+ decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN));
1444
+ } catch {
1445
+ return null;
1446
+ }
1447
+ } else {
1448
+ try {
1449
+ decrypted = this.decrypt(raw);
1450
+ } catch {
1451
+ return null;
1452
+ }
1293
1453
  }
1294
1454
  const payload = (0, import_msgpackr2.unpack)(decrypted);
1295
1455
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
@@ -1305,14 +1465,14 @@ var DiskTier = class {
1305
1465
  }
1306
1466
  /** Explicitly delete a key from disk (cache invalidation). */
1307
1467
  delete(key) {
1308
- const filePath = this.keyToPath(key);
1468
+ const hash = this.keyToHash(key);
1469
+ const filePath = this.findFilePath(hash);
1470
+ if (!filePath) return;
1309
1471
  try {
1310
- if (import_fs.default.existsSync(filePath)) {
1311
- const stat = import_fs.default.statSync(filePath);
1312
- import_fs.default.unlinkSync(filePath);
1313
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1314
- this.fileCount = Math.max(0, this.fileCount - 1);
1315
- }
1472
+ const stat = import_fs.default.statSync(filePath);
1473
+ import_fs.default.unlinkSync(filePath);
1474
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1475
+ this.fileCount = Math.max(0, this.fileCount - 1);
1316
1476
  } catch {
1317
1477
  }
1318
1478
  }
@@ -1320,9 +1480,45 @@ var DiskTier = class {
1320
1480
  purgeExpired() {
1321
1481
  this.ensureDir();
1322
1482
  if (!this.dirReady) return 0;
1483
+ const now = Date.now();
1323
1484
  let purged = 0;
1485
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1324
1486
  for (const filePath of this.walkCacheFiles()) {
1487
+ const filename = import_path.default.basename(filePath);
1488
+ if (filename.length === 77 && filename[64] === "_") {
1489
+ const expiresAt = parseInt(filename.slice(65), 16);
1490
+ if (expiresAt <= now) {
1491
+ try {
1492
+ const sz = import_fs.default.statSync(filePath).size;
1493
+ import_fs.default.unlinkSync(filePath);
1494
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1495
+ this.fileCount = Math.max(0, this.fileCount - 1);
1496
+ purged++;
1497
+ } catch {
1498
+ }
1499
+ }
1500
+ continue;
1501
+ }
1502
+ let fd = -1;
1325
1503
  try {
1504
+ fd = import_fs.default.openSync(filePath, "r");
1505
+ const bytesRead = import_fs.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1506
+ import_fs.default.closeSync(fd);
1507
+ fd = -1;
1508
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1509
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1510
+ if (expiresAt <= now) {
1511
+ try {
1512
+ const sz = import_fs.default.statSync(filePath).size;
1513
+ import_fs.default.unlinkSync(filePath);
1514
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1515
+ this.fileCount = Math.max(0, this.fileCount - 1);
1516
+ purged++;
1517
+ } catch {
1518
+ }
1519
+ }
1520
+ continue;
1521
+ }
1326
1522
  const stat = import_fs.default.statSync(filePath);
1327
1523
  if (stat.size > this.opts.entryMaxBytes) {
1328
1524
  import_fs.default.unlinkSync(filePath);
@@ -1342,13 +1538,116 @@ var DiskTier = class {
1342
1538
  continue;
1343
1539
  }
1344
1540
  const payload = (0, import_msgpackr2.unpack)(dec);
1345
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
1541
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1346
1542
  import_fs.default.unlinkSync(filePath);
1347
1543
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1348
1544
  this.fileCount = Math.max(0, this.fileCount - 1);
1349
1545
  purged++;
1350
1546
  }
1351
1547
  } catch {
1548
+ } finally {
1549
+ if (fd >= 0) try {
1550
+ import_fs.default.closeSync(fd);
1551
+ } catch {
1552
+ }
1553
+ }
1554
+ }
1555
+ return purged;
1556
+ }
1557
+ /**
1558
+ * Purge expired entries from exactly one of the 256 subdirectory buckets, then
1559
+ * advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
1560
+ * the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
1561
+ * of landing as one large synchronous burst every 5 minutes.
1562
+ *
1563
+ * V3 files: expiresAt is encoded in the filename — live entries skip with zero
1564
+ * file I/O (just readdirSync + string parse). Expired entries: statSync + unlinkSync.
1565
+ *
1566
+ * Returns the number of entries deleted in this tick.
1567
+ */
1568
+ purgeNextBucket() {
1569
+ this.ensureDir();
1570
+ if (!this.dirReady) return 0;
1571
+ const bucket = this._nextJanitorBucket.toString(16).padStart(2, "0");
1572
+ this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
1573
+ const bucketPath = import_path.default.join(this.opts.dir, bucket);
1574
+ let files;
1575
+ try {
1576
+ files = import_fs.default.readdirSync(bucketPath);
1577
+ } catch {
1578
+ return 0;
1579
+ }
1580
+ const now = Date.now();
1581
+ let purged = 0;
1582
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1583
+ for (const file of files) {
1584
+ if (file.length === 77 && file[64] === "_") {
1585
+ const expiresAt = parseInt(file.slice(65), 16);
1586
+ if (expiresAt <= now) {
1587
+ const filePath2 = import_path.default.join(bucketPath, file);
1588
+ try {
1589
+ const sz = import_fs.default.statSync(filePath2).size;
1590
+ import_fs.default.unlinkSync(filePath2);
1591
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1592
+ this.fileCount = Math.max(0, this.fileCount - 1);
1593
+ purged++;
1594
+ } catch {
1595
+ }
1596
+ }
1597
+ continue;
1598
+ }
1599
+ const filePath = import_path.default.join(bucketPath, file);
1600
+ let fd = -1;
1601
+ try {
1602
+ fd = import_fs.default.openSync(filePath, "r");
1603
+ const bytesRead = import_fs.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1604
+ import_fs.default.closeSync(fd);
1605
+ fd = -1;
1606
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1607
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1608
+ if (expiresAt <= now) {
1609
+ try {
1610
+ const sz = import_fs.default.statSync(filePath).size;
1611
+ import_fs.default.unlinkSync(filePath);
1612
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1613
+ this.fileCount = Math.max(0, this.fileCount - 1);
1614
+ purged++;
1615
+ } catch {
1616
+ }
1617
+ }
1618
+ continue;
1619
+ }
1620
+ const stat = import_fs.default.statSync(filePath);
1621
+ if (stat.size > this.opts.entryMaxBytes) {
1622
+ import_fs.default.unlinkSync(filePath);
1623
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1624
+ this.fileCount = Math.max(0, this.fileCount - 1);
1625
+ purged++;
1626
+ continue;
1627
+ }
1628
+ const raw = import_fs.default.readFileSync(filePath);
1629
+ let dec;
1630
+ try {
1631
+ dec = this.decrypt(raw);
1632
+ } catch {
1633
+ import_fs.default.unlinkSync(filePath);
1634
+ this.fileCount = Math.max(0, this.fileCount - 1);
1635
+ purged++;
1636
+ continue;
1637
+ }
1638
+ const payload = (0, import_msgpackr2.unpack)(dec);
1639
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1640
+ import_fs.default.unlinkSync(filePath);
1641
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1642
+ this.fileCount = Math.max(0, this.fileCount - 1);
1643
+ purged++;
1644
+ }
1645
+ } catch {
1646
+ } finally {
1647
+ if (fd >= 0) try {
1648
+ import_fs.default.closeSync(fd);
1649
+ } catch {
1650
+ }
1352
1651
  }
1353
1652
  }
1354
1653
  return purged;
@@ -1424,6 +1723,12 @@ var L2CircuitBreaker = class {
1424
1723
  return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1425
1724
  }
1426
1725
  };
1726
+ function deepFreeze(obj) {
1727
+ if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
1728
+ Object.freeze(obj);
1729
+ for (const v of Object.values(obj)) deepFreeze(v);
1730
+ return obj;
1731
+ }
1427
1732
  function inferPriority(cacheKey) {
1428
1733
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1429
1734
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1455,7 +1760,9 @@ var CacheService = class _CacheService {
1455
1760
  redisConnecting = null;
1456
1761
  cb;
1457
1762
  snapshotLoaded = false;
1763
+ _readyPromise = Promise.resolve();
1458
1764
  cleanupInterval = null;
1765
+ diskJanitorInterval = null;
1459
1766
  oomInterval = null;
1460
1767
  metricsInterval = null;
1461
1768
  _shutdownHandler = null;
@@ -1531,7 +1838,11 @@ var CacheService = class _CacheService {
1531
1838
  instanceName: options.instanceName ?? "",
1532
1839
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1533
1840
  tracer: options.tracer,
1534
- notFoundTtl: options.notFoundTtl ?? 0
1841
+ notFoundTtl: options.notFoundTtl ?? 0,
1842
+ warmKeys: options.warmKeys,
1843
+ onHit: options.onHit,
1844
+ onMiss: options.onMiss,
1845
+ frozen: options.frozen ?? false
1535
1846
  };
1536
1847
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1537
1848
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -1551,7 +1862,9 @@ var CacheService = class _CacheService {
1551
1862
  maxEntries: this.opts.l1MaxEntries,
1552
1863
  categories: this.opts.categoryLimits,
1553
1864
  diskSpill: (key, entry) => {
1554
- void this.disk.save(key, entry);
1865
+ setImmediate(() => {
1866
+ void this.disk.save(key, entry);
1867
+ });
1555
1868
  },
1556
1869
  onEviction: options.onEviction,
1557
1870
  logger
@@ -1568,12 +1881,14 @@ var CacheService = class _CacheService {
1568
1881
  process.once("SIGINT", this._shutdownHandler);
1569
1882
  this.cleanupInterval = setInterval(() => {
1570
1883
  const cleaned = this.l1.cleanup();
1571
- const diskPurged = this.disk.purgeExpired();
1572
- if (cleaned > 0 || diskPurged > 0) {
1573
- this.logger.debug("Periodic cache cleanup", { cleaned, diskPurged });
1574
- }
1884
+ if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
1575
1885
  }, 5 * 60 * 1e3);
1576
1886
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
1887
+ this.diskJanitorInterval = setInterval(() => {
1888
+ const purged = this.disk.purgeNextBucket();
1889
+ if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
1890
+ }, 3e4);
1891
+ if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
1577
1892
  if (this.opts.oomProtection) {
1578
1893
  this.oomInterval = setInterval(() => {
1579
1894
  const mem = process.memoryUsage();
@@ -1603,6 +1918,9 @@ var CacheService = class _CacheService {
1603
1918
  this.instanceId = import_crypto3.default.randomBytes(8).toString("hex");
1604
1919
  this.backplaneChannel = `tricache:inv${ns ? ":" + ns : ""}`;
1605
1920
  this.initBackplane();
1921
+ if (this.opts.warmKeys) {
1922
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => void 0);
1923
+ }
1606
1924
  }
1607
1925
  // ── Singleton factory ─────────────────────────────────────────────────────
1608
1926
  /**
@@ -1662,15 +1980,22 @@ var CacheService = class _CacheService {
1662
1980
  if (j === 0) return ttlMs;
1663
1981
  return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
1664
1982
  }
1983
+ /** Shared no-op span for the common case where no tracer is configured.
1984
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
1985
+ static _nullSpan = {
1986
+ setAttribute() {
1987
+ return this;
1988
+ },
1989
+ setStatus() {
1990
+ return this;
1991
+ },
1992
+ end() {
1993
+ }
1994
+ };
1665
1995
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1666
1996
  _startSpan(name) {
1667
1997
  if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1668
- return { setAttribute() {
1669
- return this;
1670
- }, setStatus() {
1671
- return this;
1672
- }, end() {
1673
- } };
1998
+ return _CacheService._nullSpan;
1674
1999
  }
1675
2000
  initBackplane() {
1676
2001
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -1710,6 +2035,7 @@ var CacheService = class _CacheService {
1710
2035
  if (msg.op === "del") {
1711
2036
  this.l1.delete(msg.key);
1712
2037
  setImmediate(() => this.disk.delete(msg.key));
2038
+ this._cascadeDependencies(msg.key);
1713
2039
  } else if (msg.op === "del-glob") {
1714
2040
  this.l1.deletePattern(msg.key);
1715
2041
  }
@@ -1858,7 +2184,7 @@ var CacheService = class _CacheService {
1858
2184
  */
1859
2185
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1860
2186
  const span = this._startSpan("tricache.get");
1861
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2187
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1862
2188
  const k = this.nk(cacheKey);
1863
2189
  this.counters.gets++;
1864
2190
  const l1Hit = this.l1.get(k);
@@ -1876,14 +2202,14 @@ var CacheService = class _CacheService {
1876
2202
  }
1877
2203
  } else {
1878
2204
  this.logger.debug("L1 hit");
1879
- if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
1880
- const now = Date.now();
2205
+ if (opts.refreshAhead || opts.xfetchBeta) {
2206
+ const now = l1Hit.fetchedAt ?? Date.now();
1881
2207
  const remaining = l1Hit.expiresAt - now;
1882
2208
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
1883
- const priority2 = opts.priority ?? inferPriority(cacheKey);
1884
- const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
1885
- const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
1886
- if (shouldRefreshAhead || shouldXFetch) {
2209
+ const shouldRefreshAhead = !!opts.refreshAhead ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
2210
+ const shouldXFetch = !!opts.xfetchBeta && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
2211
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2212
+ const priority2 = opts.priority ?? inferPriority(cacheKey);
1887
2213
  this.revalidating.add(k);
1888
2214
  void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
1889
2215
  this.counters.swrRevalidations++;
@@ -1895,6 +2221,8 @@ var CacheService = class _CacheService {
1895
2221
  }
1896
2222
  }
1897
2223
  this.counters.l1Hits++;
2224
+ this.opts.onHit?.(cacheKey, "l1");
2225
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
1898
2226
  span.setAttribute("cache.hit", "l1").end();
1899
2227
  return l1Hit.value;
1900
2228
  }
@@ -1911,6 +2239,7 @@ var CacheService = class _CacheService {
1911
2239
  const parsed = JSON.parse(decrypted);
1912
2240
  this.l1.set(k, parsed, ttlMs, priority);
1913
2241
  this.counters.l2Hits++;
2242
+ this.opts.onHit?.(cacheKey, "l2");
1914
2243
  this.logger.debug("L2 hit (Redis)", { cacheKey });
1915
2244
  span.setAttribute("cache.hit", "l2").end();
1916
2245
  return parsed;
@@ -1930,6 +2259,7 @@ var CacheService = class _CacheService {
1930
2259
  const l1Check = this.l1.get(k);
1931
2260
  if (l1Check !== null) {
1932
2261
  this.counters.diskHits++;
2262
+ this.opts.onHit?.(cacheKey, "disk");
1933
2263
  this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1934
2264
  span.setAttribute("cache.hit", "disk").end();
1935
2265
  return l1Check.value;
@@ -1937,6 +2267,7 @@ var CacheService = class _CacheService {
1937
2267
  }
1938
2268
  }
1939
2269
  span.setAttribute("cache.hit", "miss");
2270
+ this.opts.onMiss?.(cacheKey);
1940
2271
  const existing = this.inflight.get(k);
1941
2272
  if (existing) {
1942
2273
  this.counters.stampedes++;
@@ -1955,6 +2286,7 @@ var CacheService = class _CacheService {
1955
2286
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
1956
2287
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1957
2288
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
2289
+ if (opts.tags?.length) await this._registerTags(k, opts.tags, Math.ceil(effectiveTtl / 1e3));
1958
2290
  if (!this._redisDisabled) {
1959
2291
  try {
1960
2292
  const client = await this.getRedis();
@@ -2015,38 +2347,13 @@ var CacheService = class _CacheService {
2015
2347
  /** Explicitly write a value into L1 (+ L2 in production). */
2016
2348
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
2017
2349
  const span = this._startSpan("tricache.set");
2018
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2350
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2019
2351
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2020
2352
  const p = priority ?? inferPriority(cacheKey);
2021
2353
  const k = this.nk(cacheKey);
2022
2354
  this.counters.sets++;
2023
2355
  this.l1.set(k, data, ttlMs, p);
2024
- if (opts?.tags?.length) {
2025
- for (const tag of opts.tags) {
2026
- const tagKey = this.nk(`_tag_:${tag}`);
2027
- let members = this.tagIndex.get(tagKey);
2028
- if (!members) {
2029
- members = /* @__PURE__ */ new Set();
2030
- this.tagIndex.set(tagKey, members);
2031
- }
2032
- members.add(k);
2033
- }
2034
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2035
- try {
2036
- const client = await this.getRedis();
2037
- const pl = client.pipeline();
2038
- for (const tag of opts.tags) {
2039
- const tagKey = this.nk(`_tag_:${tag}`);
2040
- pl.sadd(tagKey, k);
2041
- pl.expire(tagKey, ttlSeconds + 3600);
2042
- }
2043
- await pl.exec();
2044
- this.cb.onSuccess();
2045
- } catch {
2046
- this.cb.onFailure();
2047
- }
2048
- }
2049
- }
2356
+ if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
2050
2357
  if (opts?.dependsOn?.length) {
2051
2358
  for (const pattern of opts.dependsOn) {
2052
2359
  const nsPattern = this.nk(pattern);
@@ -2073,6 +2380,36 @@ var CacheService = class _CacheService {
2073
2380
  void this.publishInvalidation("del", k);
2074
2381
  span.end();
2075
2382
  }
2383
+ /**
2384
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
2385
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
2386
+ */
2387
+ async _registerTags(k, tags, ttlSeconds) {
2388
+ for (const tag of tags) {
2389
+ const tagKey = this.nk(`_tag_:${tag}`);
2390
+ let members = this.tagIndex.get(tagKey);
2391
+ if (!members) {
2392
+ members = /* @__PURE__ */ new Set();
2393
+ this.tagIndex.set(tagKey, members);
2394
+ }
2395
+ members.add(k);
2396
+ }
2397
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2398
+ try {
2399
+ const client = await this.getRedis();
2400
+ const pl = client.pipeline();
2401
+ for (const tag of tags) {
2402
+ const tagKey = this.nk(`_tag_:${tag}`);
2403
+ pl.sadd(tagKey, k);
2404
+ pl.expire(tagKey, ttlSeconds + 3600);
2405
+ }
2406
+ await pl.exec();
2407
+ this.cb.onSuccess();
2408
+ } catch {
2409
+ this.cb.onFailure();
2410
+ }
2411
+ }
2412
+ }
2076
2413
  /**
2077
2414
  * Delete one key or a glob pattern (supports `*` wildcard).
2078
2415
  *
@@ -2082,7 +2419,7 @@ var CacheService = class _CacheService {
2082
2419
  */
2083
2420
  async delete(cacheKey) {
2084
2421
  const span = this._startSpan("tricache.delete");
2085
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2422
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2086
2423
  const isPattern = cacheKey.includes("*");
2087
2424
  const k = this.nk(cacheKey);
2088
2425
  this.counters.deletes++;
@@ -2090,7 +2427,7 @@ var CacheService = class _CacheService {
2090
2427
  this.l1.deletePattern(k);
2091
2428
  } else {
2092
2429
  this.l1.delete(k);
2093
- this.disk.delete(k);
2430
+ setImmediate(() => this.disk.delete(k));
2094
2431
  this._cascadeDependencies(k);
2095
2432
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2096
2433
  }
@@ -2246,6 +2583,33 @@ var CacheService = class _CacheService {
2246
2583
  yield [k, entry.value !== void 0 ? entry.value : entry.data];
2247
2584
  }
2248
2585
  }
2586
+ /**
2587
+ * High-throughput bulk scan over all live L1 entries.
2588
+ *
2589
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
2590
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
2591
+ * caller uses the `offset` parameter instead of pre-slicing.
2592
+ *
2593
+ * ```typescript
2594
+ * // Zero extra string allocations — use rawKey + offset directly:
2595
+ * cache.scan((rawKey, value, offset) => {
2596
+ * const key = rawKey.slice(offset); // allocate only if needed
2597
+ * sync(key, value as User);
2598
+ * });
2599
+ * ```
2600
+ *
2601
+ * @param fn Called once per live L1 entry.
2602
+ * `rawKey` — key with namespace prefix still attached.
2603
+ * `value` — deserialized cached value.
2604
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
2605
+ */
2606
+ scan(fn) {
2607
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2608
+ this.l1.scan((key, entry, pfx) => {
2609
+ const value = entry.value !== void 0 ? entry.value : entry.data;
2610
+ fn(key, value, pfx);
2611
+ }, prefixLen);
2612
+ }
2249
2613
  /**
2250
2614
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
2251
2615
  * Returns `false` if the key is absent or already expired.
@@ -2287,7 +2651,8 @@ var CacheService = class _CacheService {
2287
2651
  *
2288
2652
  * @param keys - Array of cache keys.
2289
2653
  * @param fetchFn - Called with only the keys that missed L1.
2290
- * @param ttl - TTL in seconds for newly fetched values.
2654
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
2655
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
2291
2656
  */
2292
2657
  async mget(keys, fetchFn, ttl = 300, priority) {
2293
2658
  const result = new Array(keys.length);
@@ -2309,12 +2674,27 @@ var CacheService = class _CacheService {
2309
2674
  const v = fetched[missKeys[j]];
2310
2675
  result[missIndexes[j]] = v;
2311
2676
  if (v !== void 0) {
2312
- await this.set(missKeys[j], v, ttl, priority);
2677
+ const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
2678
+ await this.set(missKeys[j], v, resolvedTtl, priority);
2313
2679
  }
2314
2680
  }
2315
2681
  }
2316
2682
  return result;
2317
2683
  }
2684
+ /**
2685
+ * Returns a Promise that resolves once the cache is fully initialised and any
2686
+ * startup warming configured via `warmKeys` has completed.
2687
+ *
2688
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
2689
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
2690
+ *
2691
+ * @example
2692
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
2693
+ * await cache.ready(); // gate traffic until warm
2694
+ */
2695
+ ready() {
2696
+ return this._readyPromise;
2697
+ }
2318
2698
  /**
2319
2699
  * Batch write — set multiple entries in a single call.
2320
2700
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -2355,7 +2735,7 @@ var CacheService = class _CacheService {
2355
2735
  * const loaded = await cache.warmFromL2('org:*');
2356
2736
  * console.log(`Warmed ${loaded} keys from Redis`);
2357
2737
  */
2358
- async warmFromL2(pattern) {
2738
+ async warmFromL2(pattern, opts) {
2359
2739
  if (this._redisDisabled) return 0;
2360
2740
  try {
2361
2741
  const client = await this.getRedis();
@@ -2384,8 +2764,9 @@ var CacheService = class _CacheService {
2384
2764
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2385
2765
  const parsed = JSON.parse(decrypted);
2386
2766
  const remainingMs = 10 * 60 * 1e3;
2387
- this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
2767
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
2388
2768
  loaded++;
2769
+ ;
2389
2770
  } catch {
2390
2771
  }
2391
2772
  }
@@ -2433,6 +2814,58 @@ var CacheService = class _CacheService {
2433
2814
  }
2434
2815
  }
2435
2816
  }
2817
+ /**
2818
+ * Invalidate all keys associated with any of the given tags in a single operation.
2819
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
2820
+ * reducing latency when invalidating several related tags together.
2821
+ *
2822
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
2823
+ * synchronously before the Redis round-trip.
2824
+ *
2825
+ * @example
2826
+ * // Instead of three serial round-trips:
2827
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
2828
+ */
2829
+ async invalidateTags(tags) {
2830
+ if (tags.length === 0) return;
2831
+ if (tags.length === 1) {
2832
+ await this.invalidateTag(tags[0]);
2833
+ return;
2834
+ }
2835
+ const tagKeys = [];
2836
+ const allMembers = /* @__PURE__ */ new Set();
2837
+ for (const tag of tags) {
2838
+ const tagKey = this.nk(`_tag_:${tag}`);
2839
+ tagKeys.push(tagKey);
2840
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
2841
+ for (const k of members) allMembers.add(k);
2842
+ this.tagIndex.delete(tagKey);
2843
+ }
2844
+ for (const k of allMembers) {
2845
+ this.l1.delete(k);
2846
+ this.disk.delete(k);
2847
+ }
2848
+ if (!this._redisDisabled) {
2849
+ try {
2850
+ const client = await this.getRedis();
2851
+ const pl = client.pipeline();
2852
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
2853
+ const smResults = await pl.exec();
2854
+ const toDelete = [...allMembers];
2855
+ for (const [err, redisMembers] of smResults) {
2856
+ if (!err && redisMembers) {
2857
+ for (const k of redisMembers) {
2858
+ if (!allMembers.has(k)) toDelete.push(k);
2859
+ }
2860
+ }
2861
+ }
2862
+ const keysToRemove = [...toDelete, ...tagKeys];
2863
+ if (keysToRemove.length > 0) await client.del(...keysToRemove);
2864
+ } catch (err) {
2865
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
2866
+ }
2867
+ }
2868
+ }
2436
2869
  /**
2437
2870
  * Measure L1 / disk / Redis latency.
2438
2871
  * Useful for health checks and dashboards.
@@ -2705,6 +3138,7 @@ var CacheService = class _CacheService {
2705
3138
  /** Close Redis connections and stop all background timers. */
2706
3139
  async destroy() {
2707
3140
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
3141
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
2708
3142
  if (this.oomInterval) clearInterval(this.oomInterval);
2709
3143
  if (this.metricsInterval) clearInterval(this.metricsInterval);
2710
3144
  if (this._shutdownHandler) {