tricache 0.5.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,7 +437,7 @@ var WasmBloomFilter = class {
449
437
  };
450
438
 
451
439
  // src/smart-memory-cache.ts
452
- var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0 };
440
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
453
441
  var EVICTION_BATCH_PERCENT = 0.2;
454
442
  var JsBloomFilter = class {
455
443
  bits;
@@ -528,15 +516,25 @@ var JsBloomFilter = class {
528
516
  return { bitsSet, fillFactor: bitsSet / this.numBits };
529
517
  }
530
518
  };
531
- 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)));
532
523
  try {
533
524
  const wasm = new WasmBloomFilter();
534
- logger.debug("SmartMemoryCache: WASM BloomFilter active");
535
- 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
+ });
536
534
  } catch (err) {
537
535
  logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
538
- return new JsBloomFilter();
539
536
  }
537
+ return new JsBloomFilter(optimalBits, optimalK);
540
538
  }
541
539
  var SKETCH_ROWS = 4;
542
540
  var SKETCH_WIDTH = 512;
@@ -593,6 +591,21 @@ var CountMinSketch = class {
593
591
  this.inserts = 0;
594
592
  }
595
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
+ }
596
609
  var SmartMemoryCache = class {
597
610
  cache = /* @__PURE__ */ new Map();
598
611
  opts;
@@ -615,7 +628,7 @@ var SmartMemoryCache = class {
615
628
  _bloomDirtyCount = 0;
616
629
  constructor(opts, existing) {
617
630
  this.opts = opts;
618
- this.bloom = createBloomFilter(opts.logger);
631
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
619
632
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
620
633
  if (existing) {
621
634
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -675,7 +688,14 @@ var SmartMemoryCache = class {
675
688
  const catSz = this.categorySize.get(category) ?? 0;
676
689
  const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
677
690
  const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
678
- 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
+ }
679
699
  this.smartEvict(category, catOvf);
680
700
  }
681
701
  score(entry, catBonus, now, key) {
@@ -698,7 +718,8 @@ var SmartMemoryCache = class {
698
718
  * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
699
719
  */
700
720
  maybeRebuildBloom() {
701
- 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) {
702
723
  this.bloom.rebuild(this.cache.keys());
703
724
  this._bloomDirtyCount = 0;
704
725
  }
@@ -775,6 +796,7 @@ var SmartMemoryCache = class {
775
796
  _hit.expiresAt = entry.expiresAt;
776
797
  _hit.ttlMs = entry.ttlMs;
777
798
  _hit.delta = entry.delta;
799
+ _hit.fetchedAt = now;
778
800
  return _hit;
779
801
  }
780
802
  set(key, data, ttlMs, priority = 2, staleAt, delta) {
@@ -798,7 +820,7 @@ var SmartMemoryCache = class {
798
820
  this.ensureCapacity(cat, size);
799
821
  const now = Date.now();
800
822
  this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta });
801
- this.bloom.add(key);
823
+ if (!existingEntry) this.bloom.add(key);
802
824
  this.maybeRebuildBloom();
803
825
  this.totalSize += size;
804
826
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
@@ -817,9 +839,27 @@ var SmartMemoryCache = class {
817
839
  }
818
840
  keysMatchingPattern(pattern) {
819
841
  if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
820
- 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];
821
861
  const out = [];
822
- 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);
823
863
  return out;
824
864
  }
825
865
  deletePattern(pattern) {
@@ -976,6 +1016,30 @@ var SmartMemoryCache = class {
976
1016
  if (entry.expiresAt > now) yield [key, entry];
977
1017
  }
978
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
+ }
979
1043
  /**
980
1044
  * Yields only the keys of live entries — no intermediate tuple allocation.
981
1045
  * Use this instead of liveEntries() when you only need keys.
@@ -1113,6 +1177,8 @@ var AES_ALGO = "aes-256-gcm";
1113
1177
  var IV_BYTES2 = 12;
1114
1178
  var TAG_BYTES2 = 16;
1115
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;
1116
1182
  var DISK_TIER_VERSION = 1;
1117
1183
  var DiskTier = class {
1118
1184
  opts;
@@ -1121,6 +1187,8 @@ var DiskTier = class {
1121
1187
  usageCounted = false;
1122
1188
  fileCount = 0;
1123
1189
  // maintained in-memory; avoids walkCacheFiles() in stats
1190
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1191
+ _nextJanitorBucket = 0;
1124
1192
  constructor(opts) {
1125
1193
  this.opts = opts;
1126
1194
  }
@@ -1155,18 +1223,46 @@ var DiskTier = class {
1155
1223
  }
1156
1224
  }
1157
1225
  /**
1158
- * 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.
1159
1237
  *
1160
- * Files are sharded into two-character hex prefix subdirectories to avoid
1161
- * putting thousands of flat files into a single directory node — which
1162
- * degrades EXT4/NTFS performance at scale.
1238
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1239
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1163
1240
  *
1164
- * key → SHA-256 hex e3b0c442...
1165
- * path → {dir}/e3/e3b0c442...
1241
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1242
+ */
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.
1166
1251
  */
1167
- keyToPath(key) {
1168
- const hash = import_crypto2.default.createHash("sha256").update(key, "utf8").digest("hex");
1169
- return import_path.default.join(this.opts.dir, hash.slice(0, 2), hash);
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);
1170
1266
  }
1171
1267
  /**
1172
1268
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -1217,6 +1313,35 @@ var DiskTier = class {
1217
1313
  d.setAuthTag(tag);
1218
1314
  return Buffer.concat([d.update(ct), d.final()]);
1219
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
+ }
1220
1345
  // ── Public API ────────────────────────────────────────────────────────────
1221
1346
  /**
1222
1347
  * Spill an evicted L1 entry to disk.
@@ -1252,12 +1377,16 @@ var DiskTier = class {
1252
1377
  };
1253
1378
  const packed = (0, import_msgpackr2.pack)(payload);
1254
1379
  if (packed.length > this.opts.entryMaxBytes) return;
1255
- 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)]);
1256
1384
  } catch (err) {
1257
1385
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1258
1386
  return;
1259
1387
  }
1260
- const filePath = this.keyToPath(key);
1388
+ const hash = this.keyToHash(key);
1389
+ const filePath = this.hashToWritePath(hash, entry.expiresAt);
1261
1390
  this.diskUsageBytes += final.length;
1262
1391
  this.fileCount++;
1263
1392
  try {
@@ -1275,9 +1404,24 @@ var DiskTier = class {
1275
1404
  if (this.isForbidden(key)) return null;
1276
1405
  this.ensureDir();
1277
1406
  if (!this.dirReady) return null;
1278
- const filePath = this.keyToPath(key);
1407
+ const hash = this.keyToHash(key);
1408
+ const filePath = this.findFilePath(hash);
1409
+ if (!filePath) return null;
1279
1410
  try {
1280
- 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
+ }
1281
1425
  const stat = import_fs.default.statSync(filePath);
1282
1426
  if (stat.size > this.opts.entryMaxBytes) {
1283
1427
  import_fs.default.unlinkSync(filePath);
@@ -1292,10 +1436,20 @@ var DiskTier = class {
1292
1436
  } catch {
1293
1437
  }
1294
1438
  let decrypted;
1295
- try {
1296
- decrypted = this.decrypt(raw);
1297
- } catch {
1298
- 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
+ }
1299
1453
  }
1300
1454
  const payload = (0, import_msgpackr2.unpack)(decrypted);
1301
1455
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
@@ -1311,14 +1465,14 @@ var DiskTier = class {
1311
1465
  }
1312
1466
  /** Explicitly delete a key from disk (cache invalidation). */
1313
1467
  delete(key) {
1314
- const filePath = this.keyToPath(key);
1468
+ const hash = this.keyToHash(key);
1469
+ const filePath = this.findFilePath(hash);
1470
+ if (!filePath) return;
1315
1471
  try {
1316
- if (import_fs.default.existsSync(filePath)) {
1317
- const stat = import_fs.default.statSync(filePath);
1318
- import_fs.default.unlinkSync(filePath);
1319
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1320
- this.fileCount = Math.max(0, this.fileCount - 1);
1321
- }
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);
1322
1476
  } catch {
1323
1477
  }
1324
1478
  }
@@ -1326,9 +1480,45 @@ var DiskTier = class {
1326
1480
  purgeExpired() {
1327
1481
  this.ensureDir();
1328
1482
  if (!this.dirReady) return 0;
1483
+ const now = Date.now();
1329
1484
  let purged = 0;
1485
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1330
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;
1331
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
+ }
1332
1522
  const stat = import_fs.default.statSync(filePath);
1333
1523
  if (stat.size > this.opts.entryMaxBytes) {
1334
1524
  import_fs.default.unlinkSync(filePath);
@@ -1348,13 +1538,116 @@ var DiskTier = class {
1348
1538
  continue;
1349
1539
  }
1350
1540
  const payload = (0, import_msgpackr2.unpack)(dec);
1351
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
1541
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1352
1542
  import_fs.default.unlinkSync(filePath);
1353
1543
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1354
1544
  this.fileCount = Math.max(0, this.fileCount - 1);
1355
1545
  purged++;
1356
1546
  }
1357
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
+ }
1358
1651
  }
1359
1652
  }
1360
1653
  return purged;
@@ -1430,6 +1723,12 @@ var L2CircuitBreaker = class {
1430
1723
  return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1431
1724
  }
1432
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
+ }
1433
1732
  function inferPriority(cacheKey) {
1434
1733
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1435
1734
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1463,6 +1762,7 @@ var CacheService = class _CacheService {
1463
1762
  snapshotLoaded = false;
1464
1763
  _readyPromise = Promise.resolve();
1465
1764
  cleanupInterval = null;
1765
+ diskJanitorInterval = null;
1466
1766
  oomInterval = null;
1467
1767
  metricsInterval = null;
1468
1768
  _shutdownHandler = null;
@@ -1539,7 +1839,10 @@ var CacheService = class _CacheService {
1539
1839
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1540
1840
  tracer: options.tracer,
1541
1841
  notFoundTtl: options.notFoundTtl ?? 0,
1542
- warmKeys: options.warmKeys
1842
+ warmKeys: options.warmKeys,
1843
+ onHit: options.onHit,
1844
+ onMiss: options.onMiss,
1845
+ frozen: options.frozen ?? false
1543
1846
  };
1544
1847
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1545
1848
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -1559,7 +1862,9 @@ var CacheService = class _CacheService {
1559
1862
  maxEntries: this.opts.l1MaxEntries,
1560
1863
  categories: this.opts.categoryLimits,
1561
1864
  diskSpill: (key, entry) => {
1562
- void this.disk.save(key, entry);
1865
+ setImmediate(() => {
1866
+ void this.disk.save(key, entry);
1867
+ });
1563
1868
  },
1564
1869
  onEviction: options.onEviction,
1565
1870
  logger
@@ -1576,12 +1881,14 @@ var CacheService = class _CacheService {
1576
1881
  process.once("SIGINT", this._shutdownHandler);
1577
1882
  this.cleanupInterval = setInterval(() => {
1578
1883
  const cleaned = this.l1.cleanup();
1579
- const diskPurged = this.disk.purgeExpired();
1580
- if (cleaned > 0 || diskPurged > 0) {
1581
- this.logger.debug("Periodic cache cleanup", { cleaned, diskPurged });
1582
- }
1884
+ if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
1583
1885
  }, 5 * 60 * 1e3);
1584
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();
1585
1892
  if (this.opts.oomProtection) {
1586
1893
  this.oomInterval = setInterval(() => {
1587
1894
  const mem = process.memoryUsage();
@@ -1673,15 +1980,22 @@ var CacheService = class _CacheService {
1673
1980
  if (j === 0) return ttlMs;
1674
1981
  return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
1675
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
+ };
1676
1995
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1677
1996
  _startSpan(name) {
1678
1997
  if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1679
- return { setAttribute() {
1680
- return this;
1681
- }, setStatus() {
1682
- return this;
1683
- }, end() {
1684
- } };
1998
+ return _CacheService._nullSpan;
1685
1999
  }
1686
2000
  initBackplane() {
1687
2001
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -1870,7 +2184,7 @@ var CacheService = class _CacheService {
1870
2184
  */
1871
2185
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1872
2186
  const span = this._startSpan("tricache.get");
1873
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2187
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1874
2188
  const k = this.nk(cacheKey);
1875
2189
  this.counters.gets++;
1876
2190
  const l1Hit = this.l1.get(k);
@@ -1888,13 +2202,13 @@ var CacheService = class _CacheService {
1888
2202
  }
1889
2203
  } else {
1890
2204
  this.logger.debug("L1 hit");
1891
- if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
1892
- const now = Date.now();
2205
+ if (opts.refreshAhead || opts.xfetchBeta) {
2206
+ const now = l1Hit.fetchedAt ?? Date.now();
1893
2207
  const remaining = l1Hit.expiresAt - now;
1894
2208
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
1895
- const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0 ? remaining <= entryTtl * (1 - opts.refreshAhead) : false;
1896
- const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random()) : false;
1897
- 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)) {
1898
2212
  const priority2 = opts.priority ?? inferPriority(cacheKey);
1899
2213
  this.revalidating.add(k);
1900
2214
  void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
@@ -1907,6 +2221,8 @@ var CacheService = class _CacheService {
1907
2221
  }
1908
2222
  }
1909
2223
  this.counters.l1Hits++;
2224
+ this.opts.onHit?.(cacheKey, "l1");
2225
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
1910
2226
  span.setAttribute("cache.hit", "l1").end();
1911
2227
  return l1Hit.value;
1912
2228
  }
@@ -1923,6 +2239,7 @@ var CacheService = class _CacheService {
1923
2239
  const parsed = JSON.parse(decrypted);
1924
2240
  this.l1.set(k, parsed, ttlMs, priority);
1925
2241
  this.counters.l2Hits++;
2242
+ this.opts.onHit?.(cacheKey, "l2");
1926
2243
  this.logger.debug("L2 hit (Redis)", { cacheKey });
1927
2244
  span.setAttribute("cache.hit", "l2").end();
1928
2245
  return parsed;
@@ -1942,6 +2259,7 @@ var CacheService = class _CacheService {
1942
2259
  const l1Check = this.l1.get(k);
1943
2260
  if (l1Check !== null) {
1944
2261
  this.counters.diskHits++;
2262
+ this.opts.onHit?.(cacheKey, "disk");
1945
2263
  this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1946
2264
  span.setAttribute("cache.hit", "disk").end();
1947
2265
  return l1Check.value;
@@ -1949,6 +2267,7 @@ var CacheService = class _CacheService {
1949
2267
  }
1950
2268
  }
1951
2269
  span.setAttribute("cache.hit", "miss");
2270
+ this.opts.onMiss?.(cacheKey);
1952
2271
  const existing = this.inflight.get(k);
1953
2272
  if (existing) {
1954
2273
  this.counters.stampedes++;
@@ -1967,6 +2286,7 @@ var CacheService = class _CacheService {
1967
2286
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
1968
2287
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1969
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));
1970
2290
  if (!this._redisDisabled) {
1971
2291
  try {
1972
2292
  const client = await this.getRedis();
@@ -2027,38 +2347,13 @@ var CacheService = class _CacheService {
2027
2347
  /** Explicitly write a value into L1 (+ L2 in production). */
2028
2348
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
2029
2349
  const span = this._startSpan("tricache.set");
2030
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2350
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2031
2351
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2032
2352
  const p = priority ?? inferPriority(cacheKey);
2033
2353
  const k = this.nk(cacheKey);
2034
2354
  this.counters.sets++;
2035
2355
  this.l1.set(k, data, ttlMs, p);
2036
- if (opts?.tags?.length) {
2037
- for (const tag of opts.tags) {
2038
- const tagKey = this.nk(`_tag_:${tag}`);
2039
- let members = this.tagIndex.get(tagKey);
2040
- if (!members) {
2041
- members = /* @__PURE__ */ new Set();
2042
- this.tagIndex.set(tagKey, members);
2043
- }
2044
- members.add(k);
2045
- }
2046
- if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2047
- try {
2048
- const client = await this.getRedis();
2049
- const pl = client.pipeline();
2050
- for (const tag of opts.tags) {
2051
- const tagKey = this.nk(`_tag_:${tag}`);
2052
- pl.sadd(tagKey, k);
2053
- pl.expire(tagKey, ttlSeconds + 3600);
2054
- }
2055
- await pl.exec();
2056
- this.cb.onSuccess();
2057
- } catch {
2058
- this.cb.onFailure();
2059
- }
2060
- }
2061
- }
2356
+ if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
2062
2357
  if (opts?.dependsOn?.length) {
2063
2358
  for (const pattern of opts.dependsOn) {
2064
2359
  const nsPattern = this.nk(pattern);
@@ -2085,6 +2380,36 @@ var CacheService = class _CacheService {
2085
2380
  void this.publishInvalidation("del", k);
2086
2381
  span.end();
2087
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
+ }
2088
2413
  /**
2089
2414
  * Delete one key or a glob pattern (supports `*` wildcard).
2090
2415
  *
@@ -2094,7 +2419,7 @@ var CacheService = class _CacheService {
2094
2419
  */
2095
2420
  async delete(cacheKey) {
2096
2421
  const span = this._startSpan("tricache.delete");
2097
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2422
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2098
2423
  const isPattern = cacheKey.includes("*");
2099
2424
  const k = this.nk(cacheKey);
2100
2425
  this.counters.deletes++;
@@ -2102,7 +2427,7 @@ var CacheService = class _CacheService {
2102
2427
  this.l1.deletePattern(k);
2103
2428
  } else {
2104
2429
  this.l1.delete(k);
2105
- this.disk.delete(k);
2430
+ setImmediate(() => this.disk.delete(k));
2106
2431
  this._cascadeDependencies(k);
2107
2432
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2108
2433
  }
@@ -2258,6 +2583,33 @@ var CacheService = class _CacheService {
2258
2583
  yield [k, entry.value !== void 0 ? entry.value : entry.data];
2259
2584
  }
2260
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
+ }
2261
2613
  /**
2262
2614
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
2263
2615
  * Returns `false` if the key is absent or already expired.
@@ -2383,7 +2735,7 @@ var CacheService = class _CacheService {
2383
2735
  * const loaded = await cache.warmFromL2('org:*');
2384
2736
  * console.log(`Warmed ${loaded} keys from Redis`);
2385
2737
  */
2386
- async warmFromL2(pattern) {
2738
+ async warmFromL2(pattern, opts) {
2387
2739
  if (this._redisDisabled) return 0;
2388
2740
  try {
2389
2741
  const client = await this.getRedis();
@@ -2412,8 +2764,9 @@ var CacheService = class _CacheService {
2412
2764
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2413
2765
  const parsed = JSON.parse(decrypted);
2414
2766
  const remainingMs = 10 * 60 * 1e3;
2415
- this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
2767
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
2416
2768
  loaded++;
2769
+ ;
2417
2770
  } catch {
2418
2771
  }
2419
2772
  }
@@ -2461,6 +2814,58 @@ var CacheService = class _CacheService {
2461
2814
  }
2462
2815
  }
2463
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
+ }
2464
2869
  /**
2465
2870
  * Measure L1 / disk / Redis latency.
2466
2871
  * Useful for health checks and dashboards.
@@ -2733,6 +3138,7 @@ var CacheService = class _CacheService {
2733
3138
  /** Close Redis connections and stop all background timers. */
2734
3139
  async destroy() {
2735
3140
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
3141
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
2736
3142
  if (this.oomInterval) clearInterval(this.oomInterval);
2737
3143
  if (this.metricsInterval) clearInterval(this.metricsInterval);
2738
3144
  if (this._shutdownHandler) {