tricache 0.5.0 → 0.6.0

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
@@ -81,8 +81,12 @@ var PREFIX_CTR = "ctr:v1:";
81
81
  var IV_POOL_COUNT = 64;
82
82
  var CacheEncryption = class {
83
83
  _key = null;
84
+ // raw bytes — used only for XOR
85
+ _keyObj = null;
86
+ // parsed KeyObject — used for all AES modes
84
87
  _mode;
85
88
  _prevKey = null;
89
+ _prevKeyObj = null;
86
90
  _prevMode = "aes-256-gcm";
87
91
  // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
88
92
  _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
@@ -167,6 +171,16 @@ var CacheEncryption = class {
167
171
  throw new Error("XOR key must be at least 1 byte");
168
172
  }
169
173
  this._key = buf;
174
+ if (mode !== "xor") {
175
+ this._keyObj = (0, import_crypto.createSecretKey)(buf);
176
+ const _wc = (0, import_crypto.createCipheriv)(
177
+ mode,
178
+ this._keyObj,
179
+ Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
180
+ );
181
+ _wc.update(Buffer.alloc(0));
182
+ _wc.final();
183
+ }
170
184
  if (mode === "xor") {
171
185
  logger.warn(
172
186
  "Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
@@ -181,6 +195,16 @@ var CacheEncryption = class {
181
195
  try {
182
196
  this._prevMode = previousMode ?? mode;
183
197
  this._prevKey = Buffer.from(previousKeyBase64, "base64");
198
+ if (this._prevMode !== "xor") {
199
+ this._prevKeyObj = (0, import_crypto.createSecretKey)(this._prevKey);
200
+ const _wc = (0, import_crypto.createCipheriv)(
201
+ this._prevMode,
202
+ this._prevKeyObj,
203
+ Buffer.alloc(this._prevMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
204
+ );
205
+ _wc.update(Buffer.alloc(0));
206
+ _wc.final();
207
+ }
184
208
  logger.debug("Previous encryption key loaded for key rotation fallback");
185
209
  } catch (err) {
186
210
  logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
@@ -204,18 +228,19 @@ var CacheEncryption = class {
204
228
  }
205
229
  if (this._mode === "aes-128-ctr") {
206
230
  const iv2 = this._nextCtrIV();
207
- const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._key, iv2);
231
+ const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
208
232
  const enc2 = c2.update(plaintext, "utf8");
209
- c2.final();
210
- const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length);
233
+ const fin = c2.final();
234
+ const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
211
235
  iv2.copy(out2, 0);
212
236
  enc2.copy(out2, CTR_IV_BYTES);
237
+ if (fin.length > 0) fin.copy(out2, CTR_IV_BYTES + enc2.length);
213
238
  return PREFIX_CTR + out2.toString("base64");
214
239
  }
215
240
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
216
241
  const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
217
242
  const iv = this._nextIV();
218
- const c = (0, import_crypto.createCipheriv)(algo, this._key, iv);
243
+ const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
219
244
  const enc = c.update(plaintext, "utf8");
220
245
  c.final();
221
246
  const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
@@ -231,18 +256,18 @@ var CacheEncryption = class {
231
256
  */
232
257
  decrypt(value) {
233
258
  try {
234
- return this._decryptWithKey(value, this._key, this._mode);
259
+ return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
235
260
  } catch (primaryErr) {
236
261
  if (this._prevKey) {
237
262
  try {
238
- return this._decryptWithKey(value, this._prevKey, this._prevMode);
263
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
239
264
  } catch {
240
265
  }
241
266
  }
242
267
  throw primaryErr;
243
268
  }
244
269
  }
245
- _decryptWithKey(value, key, mode) {
270
+ _decryptWithKey(value, key, keyObj, mode) {
246
271
  if (value.startsWith(PREFIX_XOR)) {
247
272
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
248
273
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -253,31 +278,32 @@ var CacheEncryption = class {
253
278
  return out.toString("utf8");
254
279
  }
255
280
  if (value.startsWith(PREFIX_CTR)) {
256
- if (!key) throw new Error("Cannot decrypt: encryption key is not set");
281
+ if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
257
282
  const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
258
283
  const iv2 = combined2.subarray(0, CTR_IV_BYTES);
259
284
  const ct2 = combined2.subarray(CTR_IV_BYTES);
260
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
285
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
261
286
  const plain2 = d2.update(ct2);
262
- d2.final();
263
- return plain2.toString("utf8");
287
+ const fin = d2.final();
288
+ return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
264
289
  }
265
290
  const is256 = value.startsWith(PREFIX_256);
266
291
  const is128 = value.startsWith(PREFIX_128);
267
292
  if (!is256 && !is128) return value;
268
- if (!key) throw new Error("Cannot decrypt: encryption key is not set");
293
+ if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
269
294
  const prefix = is128 ? PREFIX_128 : PREFIX_256;
270
295
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
271
296
  const combined = Buffer.from(value.slice(prefix.length), "base64");
272
297
  const iv = combined.subarray(0, IV_BYTES);
273
298
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
274
299
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
275
- const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
300
+ const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
276
301
  d.setAuthTag(tag);
277
302
  const plain = d.update(ct);
278
303
  d.final();
279
304
  return plain.toString("utf8");
280
305
  void mode;
306
+ void key;
281
307
  }
282
308
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
283
309
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
@@ -292,19 +318,20 @@ var CacheEncryption = class {
292
318
  }
293
319
  if (this._mode === "aes-128-ctr") {
294
320
  const iv2 = this._nextCtrIV();
295
- const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._key, iv2);
321
+ const c2 = (0, import_crypto.createCipheriv)("aes-128-ctr", this._keyObj, iv2);
296
322
  const enc2 = c2.update(data);
297
- c2.final();
298
- const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length);
323
+ const fin = c2.final();
324
+ const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
299
325
  MAGIC_CTR.copy(out2, 0);
300
326
  iv2.copy(out2, MAGIC_LEN);
301
327
  enc2.copy(out2, MAGIC_LEN + CTR_IV_BYTES);
328
+ if (fin.length > 0) fin.copy(out2, MAGIC_LEN + CTR_IV_BYTES + enc2.length);
302
329
  return out2;
303
330
  }
304
331
  const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
305
332
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
306
333
  const iv = this._nextIV();
307
- const c = (0, import_crypto.createCipheriv)(algo, this._key, iv);
334
+ const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
308
335
  const enc = c.update(data);
309
336
  c.final();
310
337
  const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
@@ -321,18 +348,18 @@ var CacheEncryption = class {
321
348
  */
322
349
  decryptBuffer(data) {
323
350
  try {
324
- return this._decryptBufferWithKey(data, this._key);
351
+ return this._decryptBufferWithKey(data, this._key, this._keyObj);
325
352
  } catch (primaryErr) {
326
353
  if (this._prevKey) {
327
354
  try {
328
- return this._decryptBufferWithKey(data, this._prevKey);
355
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
329
356
  } catch {
330
357
  }
331
358
  }
332
359
  throw primaryErr;
333
360
  }
334
361
  }
335
- _decryptBufferWithKey(data, key) {
362
+ _decryptBufferWithKey(data, key, keyObj) {
336
363
  if (data.length < MAGIC_LEN) return data;
337
364
  const magic = data.subarray(0, MAGIC_LEN);
338
365
  if (magic.equals(MAGIC_XOR)) {
@@ -344,23 +371,23 @@ var CacheEncryption = class {
344
371
  return out;
345
372
  }
346
373
  if (magic.equals(MAGIC_CTR)) {
347
- if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
374
+ if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
348
375
  const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
349
376
  const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
350
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
377
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
351
378
  const plain2 = d2.update(ct2);
352
- d2.final();
353
- return plain2;
379
+ const fin = d2.final();
380
+ return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
354
381
  }
355
382
  const is256 = magic.equals(MAGIC_256);
356
383
  const is128 = magic.equals(MAGIC_128);
357
384
  if (!is256 && !is128) return data;
358
- if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
385
+ if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
359
386
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
360
387
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
361
388
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
362
389
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
363
- const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
390
+ const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
364
391
  d.setAuthTag(tag);
365
392
  const plain = d.update(ct);
366
393
  d.final();
@@ -375,11 +402,7 @@ var import_msgpackr = require("msgpackr");
375
402
  var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
376
403
  var KEY_STAGING_OFFSET = 2e4;
377
404
  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
- }
405
+ var BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64, "base64"));
383
406
  var WasmBloomFilter = class {
384
407
  exports;
385
408
  mem;
@@ -390,26 +413,16 @@ var WasmBloomFilter = class {
390
413
  /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
391
414
  _insertionCount = 0;
392
415
  constructor() {
393
- const instance = instantiateSync();
416
+ const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
394
417
  this.exports = instance.exports;
395
418
  this.mem = new Uint8Array(this.exports.memory.buffer);
396
419
  const k = 7, p = 0.01;
397
420
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
398
421
  }
399
422
  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;
423
+ if (key.length === 0) return 0;
424
+ const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
425
+ return this.encoder.encodeInto(key, target).written;
413
426
  }
414
427
  add(key) {
415
428
  const len = this.writeKey(key);
@@ -449,8 +462,10 @@ var WasmBloomFilter = class {
449
462
  };
450
463
 
451
464
  // src/smart-memory-cache.ts
452
- var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0 };
465
+ var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
453
466
  var EVICTION_BATCH_PERCENT = 0.2;
467
+ var EVICTION_SAMPLE = 16;
468
+ var EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT));
454
469
  var JsBloomFilter = class {
455
470
  bits;
456
471
  numBits;
@@ -528,15 +543,25 @@ var JsBloomFilter = class {
528
543
  return { bitsSet, fillFactor: bitsSet / this.numBits };
529
544
  }
530
545
  };
531
- function createBloomFilter(logger) {
546
+ function createBloomFilter(logger, maxEntries) {
547
+ const LN2_SQ = Math.LN2 * Math.LN2;
548
+ const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
549
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
532
550
  try {
533
551
  const wasm = new WasmBloomFilter();
534
- logger.debug("SmartMemoryCache: WASM BloomFilter active");
535
- return wasm;
552
+ if (wasm.maxCapacity >= maxEntries) {
553
+ logger.debug("SmartMemoryCache: WASM BloomFilter active");
554
+ return wasm;
555
+ }
556
+ logger.debug("SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter", {
557
+ wasmCapacity: wasm.maxCapacity,
558
+ maxEntries,
559
+ optimalBits
560
+ });
536
561
  } catch (err) {
537
562
  logger.debug("SmartMemoryCache: WASM unavailable \u2014 using pure-JS BloomFilter", { reason: err.message });
538
- return new JsBloomFilter();
539
563
  }
564
+ return new JsBloomFilter(optimalBits, optimalK);
540
565
  }
541
566
  var SKETCH_ROWS = 4;
542
567
  var SKETCH_WIDTH = 512;
@@ -593,6 +618,21 @@ var CountMinSketch = class {
593
618
  this.inserts = 0;
594
619
  }
595
620
  };
621
+ function globMatchParts(parts, first, last, key) {
622
+ if (first.length > 0 && !key.startsWith(first)) return false;
623
+ if (last.length > 0 && !key.endsWith(last)) return false;
624
+ if (first.length + last.length > key.length) return false;
625
+ let pos = first.length;
626
+ const end = key.length - last.length;
627
+ for (let i = 1; i < parts.length - 1; i++) {
628
+ const seg = parts[i];
629
+ if (seg.length === 0) continue;
630
+ const idx = key.indexOf(seg, pos);
631
+ if (idx === -1 || idx + seg.length > end) return false;
632
+ pos = idx + seg.length;
633
+ }
634
+ return true;
635
+ }
596
636
  var SmartMemoryCache = class {
597
637
  cache = /* @__PURE__ */ new Map();
598
638
  opts;
@@ -613,9 +653,18 @@ var SmartMemoryCache = class {
613
653
  categoryHits = /* @__PURE__ */ new Map();
614
654
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
615
655
  _bloomDirtyCount = 0;
656
+ /**
657
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
658
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
659
+ * that is overwritten in-place rather than replaced with a new object literal.
660
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
661
+ * any other code can observe the pool state.
662
+ */
663
+ _evictPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
664
+ _evictGPool = Array.from({ length: EVICTION_SAMPLE }, () => ({ key: "", score: 0 }));
616
665
  constructor(opts, existing) {
617
666
  this.opts = opts;
618
- this.bloom = createBloomFilter(opts.logger);
667
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
619
668
  this.categoryPrefixes = Object.keys(opts.categories).filter((k) => k !== "default");
620
669
  if (existing) {
621
670
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -675,7 +724,15 @@ var SmartMemoryCache = class {
675
724
  const catSz = this.categorySize.get(category) ?? 0;
676
725
  const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
677
726
  const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
678
- if (!catOvf && !glbOvf) return;
727
+ if (!catOvf && !glbOvf) {
728
+ const wm = this.opts.evictionWatermark ?? 0.9;
729
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
730
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
731
+ if (entryWatermark || byteWatermark) {
732
+ this.smartEvict(category, false);
733
+ }
734
+ return;
735
+ }
679
736
  this.smartEvict(category, catOvf);
680
737
  }
681
738
  score(entry, catBonus, now, key) {
@@ -698,16 +755,17 @@ var SmartMemoryCache = class {
698
755
  * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
699
756
  */
700
757
  maybeRebuildBloom() {
701
- if (this._bloomDirtyCount > this.bloom.maxCapacity >>> 2 || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
758
+ const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
759
+ if (this._bloomDirtyCount > dirtyThreshold || this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
702
760
  this.bloom.rebuild(this.cache.keys());
703
761
  this._bloomDirtyCount = 0;
704
762
  }
705
763
  }
706
764
  smartEvict(targetCat, catOvf) {
707
765
  const now = Date.now();
708
- const SAMPLE = 16;
709
- const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT));
710
- const pool = [];
766
+ const pool = this._evictPool;
767
+ const gPool = this._evictGPool;
768
+ let poolLen = 0;
711
769
  if (catOvf) {
712
770
  const catKeySet = this.categoryKeys.get(targetCat);
713
771
  if (catKeySet) {
@@ -717,36 +775,62 @@ var SmartMemoryCache = class {
717
775
  if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
718
776
  catSeen++;
719
777
  const s = this.score(entry, 100, now, key);
720
- if (pool.length < EVICT) {
721
- pool.push({ key, score: s });
778
+ if (poolLen < EVICT_COUNT) {
779
+ pool[poolLen].key = key;
780
+ pool[poolLen].score = s;
781
+ poolLen++;
722
782
  } else {
723
783
  const j = Math.floor(Math.random() * catSeen);
724
- if (j < EVICT) pool[j] = { key, score: s };
784
+ if (j < EVICT_COUNT) {
785
+ pool[j].key = key;
786
+ pool[j].score = s;
787
+ }
725
788
  }
726
789
  }
727
790
  }
728
791
  }
729
- if (pool.length < EVICT) {
730
- const remaining = SAMPLE - pool.length;
792
+ if (poolLen < EVICT_COUNT) {
793
+ const remaining = EVICTION_SAMPLE - poolLen;
731
794
  let globalSeen = 0;
732
- const globalPool = [];
795
+ let gLen = 0;
733
796
  for (const [key, entry] of this.cache) {
734
797
  if (entry.priority === 4 && entry.expiresAt > now) continue;
735
798
  if (catOvf && this.getCategory(key) === targetCat) continue;
736
799
  globalSeen++;
737
800
  const s = this.score(entry, 0, now, key);
738
- if (globalPool.length < remaining) {
739
- globalPool.push({ key, score: s });
801
+ if (gLen < remaining) {
802
+ gPool[gLen].key = key;
803
+ gPool[gLen].score = s;
804
+ gLen++;
740
805
  } else {
741
806
  const j = Math.floor(Math.random() * globalSeen);
742
- if (j < remaining) globalPool[j] = { key, score: s };
807
+ if (j < remaining) {
808
+ gPool[j].key = key;
809
+ gPool[j].score = s;
810
+ }
743
811
  }
744
812
  }
745
- pool.push(...globalPool);
813
+ for (let i = 0; i < gLen; i++) {
814
+ pool[poolLen].key = gPool[i].key;
815
+ pool[poolLen].score = gPool[i].score;
816
+ poolLen++;
817
+ }
818
+ }
819
+ if (poolLen === 0) return;
820
+ for (let i = 1; i < poolLen; i++) {
821
+ const sk = pool[i].key, ss = pool[i].score;
822
+ let j = i - 1;
823
+ while (j >= 0 && pool[j].score > ss) {
824
+ pool[j + 1].key = pool[j].key;
825
+ pool[j + 1].score = pool[j].score;
826
+ j--;
827
+ }
828
+ pool[j + 1].key = sk;
829
+ pool[j + 1].score = ss;
746
830
  }
747
- if (pool.length === 0) return;
748
- pool.sort((a, b) => a.score - b.score);
749
- for (const { key } of pool.slice(0, EVICT)) {
831
+ const toEvict = Math.min(EVICT_COUNT, poolLen);
832
+ for (let i = 0; i < toEvict; i++) {
833
+ const key = pool[i].key;
750
834
  const entry = this.cache.get(key);
751
835
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
752
836
  this._delete(key, "capacity");
@@ -775,6 +859,7 @@ var SmartMemoryCache = class {
775
859
  _hit.expiresAt = entry.expiresAt;
776
860
  _hit.ttlMs = entry.ttlMs;
777
861
  _hit.delta = entry.delta;
862
+ _hit.fetchedAt = now;
778
863
  return _hit;
779
864
  }
780
865
  set(key, data, ttlMs, priority = 2, staleAt, delta) {
@@ -798,7 +883,7 @@ var SmartMemoryCache = class {
798
883
  this.ensureCapacity(cat, size);
799
884
  const now = Date.now();
800
885
  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);
886
+ if (!existingEntry) this.bloom.add(key);
802
887
  this.maybeRebuildBloom();
803
888
  this.totalSize += size;
804
889
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
@@ -817,9 +902,27 @@ var SmartMemoryCache = class {
817
902
  }
818
903
  keysMatchingPattern(pattern) {
819
904
  if (!pattern.includes("*")) return this.cache.has(pattern) ? [pattern] : [];
820
- const re = new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
905
+ if (pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1) {
906
+ const prefix = pattern.slice(0, -1);
907
+ const catKeys = this.categoryKeys.get(prefix);
908
+ if (catKeys !== void 0) return Array.from(catKeys);
909
+ }
910
+ const firstStar = pattern.indexOf("*");
911
+ if (firstStar === pattern.lastIndexOf("*")) {
912
+ const prefix = pattern.slice(0, firstStar);
913
+ const suffix = pattern.slice(firstStar + 1);
914
+ const minLen = prefix.length + suffix.length;
915
+ const out2 = [];
916
+ for (const k of this.cache.keys()) {
917
+ if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out2.push(k);
918
+ }
919
+ return out2;
920
+ }
921
+ const parts = pattern.split("*");
922
+ const first = parts[0];
923
+ const last = parts[parts.length - 1];
821
924
  const out = [];
822
- for (const k of this.cache.keys()) if (re.test(k)) out.push(k);
925
+ for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
823
926
  return out;
824
927
  }
825
928
  deletePattern(pattern) {
@@ -976,6 +1079,30 @@ var SmartMemoryCache = class {
976
1079
  if (entry.expiresAt > now) yield [key, entry];
977
1080
  }
978
1081
  }
1082
+ /**
1083
+ * Non-generator bulk scan over all live entries.
1084
+ *
1085
+ * Faster than the generator-based iterators for bulk operations because:
1086
+ * - No generator state-machine overhead (no yield/resume suspend points).
1087
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
1088
+ * - The same Map call-site is used by a single plain `for` loop instead of being
1089
+ * shared across three competing generator functions, giving V8's IC a cleaner
1090
+ * monomorphic profile for this path.
1091
+ *
1092
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
1093
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
1094
+ * key, avoiding the allocation entirely for callers that don't.
1095
+ *
1096
+ * @param fn Called once per live entry.
1097
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
1098
+ * Pass 0 when no namespace is configured.
1099
+ */
1100
+ scan(fn, prefixLen) {
1101
+ const now = Date.now();
1102
+ for (const [key, entry] of this.cache) {
1103
+ if (entry.expiresAt > now) fn(key, entry, prefixLen);
1104
+ }
1105
+ }
979
1106
  /**
980
1107
  * Yields only the keys of live entries — no intermediate tuple allocation.
981
1108
  * Use this instead of liveEntries() when you only need keys.
@@ -1108,11 +1235,21 @@ var SmartMemoryCache = class {
1108
1235
  var import_fs = __toESM(require("fs"), 1);
1109
1236
  var import_path = __toESM(require("path"), 1);
1110
1237
  var import_crypto2 = __toESM(require("crypto"), 1);
1238
+ var import_module = require("module");
1111
1239
  var import_msgpackr2 = require("msgpackr");
1240
+ var import_meta = {};
1241
+ var _SqliteDB = null;
1242
+ try {
1243
+ const _req = (0, import_module.createRequire)(import_meta.url);
1244
+ _SqliteDB = _req("node:sqlite").DatabaseSync;
1245
+ } catch {
1246
+ }
1112
1247
  var AES_ALGO = "aes-256-gcm";
1113
1248
  var IV_BYTES2 = 12;
1114
1249
  var TAG_BYTES2 = 16;
1115
1250
  var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1251
+ var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1252
+ var V2_HEADER_LEN = 16;
1116
1253
  var DISK_TIER_VERSION = 1;
1117
1254
  var DiskTier = class {
1118
1255
  opts;
@@ -1121,6 +1258,22 @@ var DiskTier = class {
1121
1258
  usageCounted = false;
1122
1259
  fileCount = 0;
1123
1260
  // maintained in-memory; avoids walkCacheFiles() in stats
1261
+ /** Next bucket index (0–255) for the staggered janitor wheel. */
1262
+ _nextJanitorBucket = 0;
1263
+ // ── SQLite metadata index (optional, requires node:sqlite) ───────────────
1264
+ _db = null;
1265
+ _stmtInsert = null;
1266
+ // INSERT OR REPLACE
1267
+ _stmtSelect = null;
1268
+ // SELECT by key_hash
1269
+ _stmtDelete = null;
1270
+ // DELETE by key_hash
1271
+ _stmtExpire = null;
1272
+ // SELECT expired rows
1273
+ _stmtDelExp = null;
1274
+ // DELETE expired rows
1275
+ _stmtStats = null;
1276
+ // COUNT + SUM(size)
1124
1277
  constructor(opts) {
1125
1278
  this.opts = opts;
1126
1279
  }
@@ -1130,13 +1283,70 @@ var DiskTier = class {
1130
1283
  try {
1131
1284
  import_fs.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
1132
1285
  this.dirReady = true;
1286
+ this._initSqlite();
1133
1287
  } catch (err) {
1134
1288
  this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
1135
1289
  }
1136
1290
  }
1291
+ /**
1292
+ * Initialise the SQLite metadata index. Called once after the cache directory
1293
+ * is confirmed to exist. On any failure the instance silently falls back to
1294
+ * file-only mode — all public methods handle `this._db === null`.
1295
+ *
1296
+ * Schema:
1297
+ * meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
1298
+ * idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
1299
+ *
1300
+ * WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
1301
+ * most one WAL frame — acceptable data loss for an L1.5 spill store).
1302
+ */
1303
+ _initSqlite() {
1304
+ if (!_SqliteDB) return;
1305
+ try {
1306
+ const dbPath = import_path.default.join(this.opts.dir, "meta.db");
1307
+ this._db = new _SqliteDB(dbPath);
1308
+ this._db.exec(`
1309
+ PRAGMA journal_mode = WAL;
1310
+ PRAGMA synchronous = NORMAL;
1311
+ PRAGMA temp_store = MEMORY;
1312
+ CREATE TABLE IF NOT EXISTS meta (
1313
+ key_hash TEXT PRIMARY KEY,
1314
+ file_path TEXT NOT NULL,
1315
+ expires_at INTEGER NOT NULL,
1316
+ size INTEGER NOT NULL DEFAULT 0
1317
+ );
1318
+ CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
1319
+ `);
1320
+ this._stmtInsert = this._db.prepare(
1321
+ "INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)"
1322
+ );
1323
+ this._stmtSelect = this._db.prepare(
1324
+ "SELECT file_path, expires_at FROM meta WHERE key_hash = ?"
1325
+ );
1326
+ this._stmtDelete = this._db.prepare("DELETE FROM meta WHERE key_hash = ?");
1327
+ this._stmtExpire = this._db.prepare(
1328
+ "SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?"
1329
+ );
1330
+ this._stmtDelExp = this._db.prepare("DELETE FROM meta WHERE expires_at <= ?");
1331
+ this._stmtStats = this._db.prepare(
1332
+ "SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta"
1333
+ );
1334
+ const row = this._stmtStats.get();
1335
+ this.fileCount = row.cnt;
1336
+ this.diskUsageBytes = row.bytes;
1337
+ this.usageCounted = true;
1338
+ this.opts.logger.debug("DiskTier: SQLite index ready", { entries: row.cnt });
1339
+ } catch (err) {
1340
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1341
+ this.opts.logger.warn("DiskTier: SQLite init failed, using file-only mode", {
1342
+ error: err.message
1343
+ });
1344
+ }
1345
+ }
1137
1346
  ensureUsageCounted() {
1138
1347
  if (this.usageCounted) return;
1139
1348
  this.usageCounted = true;
1349
+ if (this._db) return;
1140
1350
  try {
1141
1351
  this.ensureDir();
1142
1352
  let total = 0;
@@ -1155,18 +1365,46 @@ var DiskTier = class {
1155
1365
  }
1156
1366
  }
1157
1367
  /**
1158
- * Map a cache key to its on-disk path.
1368
+ * SHA-256 hex digest of a key (pure CPU, no I/O).
1369
+ * Kept separate from path construction so callers can find files by prefix
1370
+ * without knowing which filename generation was used when the file was written.
1371
+ */
1372
+ keyToHash(key) {
1373
+ return import_crypto2.default.createHash("sha256").update(key, "utf8").digest("hex");
1374
+ }
1375
+ /**
1376
+ * Build the write path for a NEW file (V3 generation).
1377
+ * Encoding expiresAt in the filename lets purgeNextBucket() skip live entries
1378
+ * with zero file I/O — after readdirSync() it only needs a string parse.
1159
1379
  *
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.
1380
+ * {dir}/{hash[0..1]}/{hash}_{expiresAt-hex-12}
1381
+ * e.g. {dir}/e3/e3b0c442…abcd_018f7c3b5a00
1163
1382
  *
1164
- * key → SHA-256 hex e3b0c442...
1165
- * path → {dir}/e3/e3b0c442...
1383
+ * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
1166
1384
  */
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);
1385
+ hashToWritePath(hash, expiresAt) {
1386
+ return import_path.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
1387
+ }
1388
+ /**
1389
+ * Find the on-disk file for a key hash, handling all filename generations:
1390
+ * V3 (current): "{hash}_{expiresHex12}" — 77 chars
1391
+ * V1/V2 (older): "{hash}" — 64 chars, no suffix
1392
+ * Returns null when the bucket dir does not exist or the key is absent.
1393
+ */
1394
+ findFilePath(hash) {
1395
+ const bucketPath = import_path.default.join(this.opts.dir, hash.slice(0, 2));
1396
+ let files;
1397
+ try {
1398
+ files = import_fs.default.readdirSync(bucketPath);
1399
+ } catch {
1400
+ return null;
1401
+ }
1402
+ let match;
1403
+ for (const f of files) {
1404
+ if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
1405
+ }
1406
+ if (!match) return null;
1407
+ return import_path.default.join(bucketPath, match);
1170
1408
  }
1171
1409
  /**
1172
1410
  * Recursively list all cache file paths across the 2-level sharded subdirs.
@@ -1217,6 +1455,35 @@ var DiskTier = class {
1217
1455
  d.setAuthTag(tag);
1218
1456
  return Buffer.concat([d.update(ct), d.final()]);
1219
1457
  }
1458
+ /**
1459
+ * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1460
+ * the outer 16-byte header alongside the plaintext expiresAt).
1461
+ * Returns the buffer unchanged when no encryption key is configured.
1462
+ */
1463
+ encryptV2(data) {
1464
+ const key = this.opts.encryptionKey;
1465
+ if (!key) return data;
1466
+ const iv = import_crypto2.default.randomBytes(IV_BYTES2);
1467
+ const c = import_crypto2.default.createCipheriv(AES_ALGO, key, iv);
1468
+ const enc = Buffer.concat([c.update(data), c.final()]);
1469
+ const tag = c.getAuthTag();
1470
+ return Buffer.concat([iv, tag, enc]);
1471
+ }
1472
+ /**
1473
+ * V2 decryption — inner payload after stripping the 16-byte header.
1474
+ * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1475
+ * without a key the payload is raw msgpack.
1476
+ */
1477
+ decryptV2(inner) {
1478
+ const key = this.opts.encryptionKey;
1479
+ if (!key) return inner;
1480
+ const iv = inner.subarray(0, IV_BYTES2);
1481
+ const tag = inner.subarray(IV_BYTES2, IV_BYTES2 + TAG_BYTES2);
1482
+ const ct = inner.subarray(IV_BYTES2 + TAG_BYTES2);
1483
+ const d = import_crypto2.default.createDecipheriv(AES_ALGO, key, iv);
1484
+ d.setAuthTag(tag);
1485
+ return Buffer.concat([d.update(ct), d.final()]);
1486
+ }
1220
1487
  // ── Public API ────────────────────────────────────────────────────────────
1221
1488
  /**
1222
1489
  * Spill an evicted L1 entry to disk.
@@ -1252,21 +1519,32 @@ var DiskTier = class {
1252
1519
  };
1253
1520
  const packed = (0, import_msgpackr2.pack)(payload);
1254
1521
  if (packed.length > this.opts.entryMaxBytes) return;
1255
- final = this.encrypt(packed);
1522
+ const header = Buffer.allocUnsafe(V2_HEADER_LEN);
1523
+ DISK_MAGIC_V2.copy(header, 0);
1524
+ header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
1525
+ final = Buffer.concat([header, this.encryptV2(packed)]);
1256
1526
  } catch (err) {
1257
1527
  this.opts.logger.debug("DiskTier: pack/encrypt failed", { key: key.slice(0, 50), error: err.message });
1258
1528
  return;
1259
1529
  }
1260
- const filePath = this.keyToPath(key);
1530
+ const hash = this.keyToHash(key);
1531
+ const filePath = this.hashToWritePath(hash, entry.expiresAt);
1261
1532
  this.diskUsageBytes += final.length;
1262
1533
  this.fileCount++;
1263
1534
  try {
1264
1535
  await import_fs.default.promises.mkdir(import_path.default.dirname(filePath), { recursive: true });
1265
1536
  await import_fs.default.promises.writeFile(filePath, final, { mode: 384 });
1537
+ if (this._db) {
1538
+ this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
1539
+ }
1266
1540
  this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1267
1541
  } catch (err) {
1268
1542
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1269
1543
  this.fileCount = Math.max(0, this.fileCount - 1);
1544
+ if (this._db) try {
1545
+ this._stmtDelete.run(hash);
1546
+ } catch {
1547
+ }
1270
1548
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1271
1549
  }
1272
1550
  }
@@ -1275,13 +1553,49 @@ var DiskTier = class {
1275
1553
  if (this.isForbidden(key)) return null;
1276
1554
  this.ensureDir();
1277
1555
  if (!this.dirReady) return null;
1278
- const filePath = this.keyToPath(key);
1556
+ const hash = this.keyToHash(key);
1557
+ let filePath;
1558
+ if (this._db) {
1559
+ const row = this._stmtSelect.get(hash);
1560
+ if (!row) return null;
1561
+ if (row.expires_at <= Date.now()) {
1562
+ this._stmtDelete.run(hash);
1563
+ try {
1564
+ const sz = import_fs.default.statSync(row.file_path).size;
1565
+ import_fs.default.unlinkSync(row.file_path);
1566
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1567
+ this.fileCount = Math.max(0, this.fileCount - 1);
1568
+ } catch {
1569
+ }
1570
+ return null;
1571
+ }
1572
+ filePath = row.file_path;
1573
+ } else {
1574
+ filePath = this.findFilePath(hash);
1575
+ if (!filePath) return null;
1576
+ }
1279
1577
  try {
1280
- if (!import_fs.default.existsSync(filePath)) return null;
1578
+ if (!this._db) {
1579
+ const filename = import_path.default.basename(filePath);
1580
+ if (filename.length === 77 && filename[64] === "_") {
1581
+ const expiresAt = parseInt(filename.slice(65), 16);
1582
+ if (expiresAt <= Date.now()) {
1583
+ try {
1584
+ const sz = import_fs.default.statSync(filePath).size;
1585
+ import_fs.default.unlinkSync(filePath);
1586
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1587
+ this.fileCount = Math.max(0, this.fileCount - 1);
1588
+ } catch {
1589
+ }
1590
+ return null;
1591
+ }
1592
+ }
1593
+ }
1281
1594
  const stat = import_fs.default.statSync(filePath);
1282
1595
  if (stat.size > this.opts.entryMaxBytes) {
1283
1596
  import_fs.default.unlinkSync(filePath);
1284
1597
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1598
+ if (this._db) this._stmtDelete.run(hash);
1285
1599
  return null;
1286
1600
  }
1287
1601
  const raw = import_fs.default.readFileSync(filePath);
@@ -1291,11 +1605,22 @@ var DiskTier = class {
1291
1605
  this.fileCount = Math.max(0, this.fileCount - 1);
1292
1606
  } catch {
1293
1607
  }
1608
+ if (this._db) this._stmtDelete.run(hash);
1294
1609
  let decrypted;
1295
- try {
1296
- decrypted = this.decrypt(raw);
1297
- } catch {
1298
- return null;
1610
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1611
+ const expiresAt = Number(raw.readBigUInt64LE(8));
1612
+ if (expiresAt <= Date.now()) return null;
1613
+ try {
1614
+ decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN));
1615
+ } catch {
1616
+ return null;
1617
+ }
1618
+ } else {
1619
+ try {
1620
+ decrypted = this.decrypt(raw);
1621
+ } catch {
1622
+ return null;
1623
+ }
1299
1624
  }
1300
1625
  const payload = (0, import_msgpackr2.unpack)(decrypted);
1301
1626
  if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
@@ -1305,20 +1630,31 @@ var DiskTier = class {
1305
1630
  this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1306
1631
  return entry;
1307
1632
  } catch (err) {
1633
+ if (this._db) try {
1634
+ this._stmtDelete.run(hash);
1635
+ } catch {
1636
+ }
1308
1637
  this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
1309
1638
  return null;
1310
1639
  }
1311
1640
  }
1312
1641
  /** Explicitly delete a key from disk (cache invalidation). */
1313
1642
  delete(key) {
1314
- const filePath = this.keyToPath(key);
1643
+ const hash = this.keyToHash(key);
1644
+ let filePath;
1645
+ if (this._db) {
1646
+ const row = this._stmtSelect.get(hash);
1647
+ filePath = row?.file_path ?? null;
1648
+ this._stmtDelete.run(hash);
1649
+ } else {
1650
+ filePath = this.findFilePath(hash);
1651
+ }
1652
+ if (!filePath) return;
1315
1653
  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
- }
1654
+ const stat = import_fs.default.statSync(filePath);
1655
+ import_fs.default.unlinkSync(filePath);
1656
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1657
+ this.fileCount = Math.max(0, this.fileCount - 1);
1322
1658
  } catch {
1323
1659
  }
1324
1660
  }
@@ -1326,9 +1662,199 @@ var DiskTier = class {
1326
1662
  purgeExpired() {
1327
1663
  this.ensureDir();
1328
1664
  if (!this.dirReady) return 0;
1665
+ if (this._db) {
1666
+ const now2 = Date.now();
1667
+ const expired = this._stmtExpire.all(now2);
1668
+ for (const row of expired) {
1669
+ try {
1670
+ import_fs.default.unlinkSync(row.file_path);
1671
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1672
+ this.fileCount = Math.max(0, this.fileCount - 1);
1673
+ } catch {
1674
+ }
1675
+ }
1676
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1677
+ return expired.length;
1678
+ }
1679
+ const now = Date.now();
1329
1680
  let purged = 0;
1681
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1330
1682
  for (const filePath of this.walkCacheFiles()) {
1683
+ const filename = import_path.default.basename(filePath);
1684
+ if (filename.length === 77 && filename[64] === "_") {
1685
+ const expiresAt = parseInt(filename.slice(65), 16);
1686
+ if (expiresAt <= now) {
1687
+ try {
1688
+ const sz = import_fs.default.statSync(filePath).size;
1689
+ import_fs.default.unlinkSync(filePath);
1690
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1691
+ this.fileCount = Math.max(0, this.fileCount - 1);
1692
+ purged++;
1693
+ } catch {
1694
+ }
1695
+ }
1696
+ continue;
1697
+ }
1698
+ let fd = -1;
1699
+ try {
1700
+ fd = import_fs.default.openSync(filePath, "r");
1701
+ const bytesRead = import_fs.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1702
+ import_fs.default.closeSync(fd);
1703
+ fd = -1;
1704
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1705
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1706
+ if (expiresAt <= now) {
1707
+ try {
1708
+ const sz = import_fs.default.statSync(filePath).size;
1709
+ import_fs.default.unlinkSync(filePath);
1710
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1711
+ this.fileCount = Math.max(0, this.fileCount - 1);
1712
+ purged++;
1713
+ } catch {
1714
+ }
1715
+ }
1716
+ continue;
1717
+ }
1718
+ const stat = import_fs.default.statSync(filePath);
1719
+ if (stat.size > this.opts.entryMaxBytes) {
1720
+ import_fs.default.unlinkSync(filePath);
1721
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1722
+ this.fileCount = Math.max(0, this.fileCount - 1);
1723
+ purged++;
1724
+ continue;
1725
+ }
1726
+ const raw = import_fs.default.readFileSync(filePath);
1727
+ let dec;
1728
+ try {
1729
+ dec = this.decrypt(raw);
1730
+ } catch {
1731
+ import_fs.default.unlinkSync(filePath);
1732
+ this.fileCount = Math.max(0, this.fileCount - 1);
1733
+ purged++;
1734
+ continue;
1735
+ }
1736
+ const payload = (0, import_msgpackr2.unpack)(dec);
1737
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1738
+ import_fs.default.unlinkSync(filePath);
1739
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1740
+ this.fileCount = Math.max(0, this.fileCount - 1);
1741
+ purged++;
1742
+ }
1743
+ } catch {
1744
+ } finally {
1745
+ if (fd >= 0) try {
1746
+ import_fs.default.closeSync(fd);
1747
+ } catch {
1748
+ }
1749
+ }
1750
+ }
1751
+ return purged;
1752
+ }
1753
+ /**
1754
+ * Purge expired entries. Two modes depending on availability of SQLite:
1755
+ *
1756
+ * SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
1757
+ * One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
1758
+ * wheel. All expired entries are found and deleted in a single pass — the
1759
+ * 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
1760
+ * incremented so tests that inspect the counter continue to work.
1761
+ *
1762
+ * File-only fallback:
1763
+ * Original staggered bucket wheel — purges exactly one of 256 subdirectory
1764
+ * buckets per call, spreading the O(fileCount) work across 256 ticks.
1765
+ *
1766
+ * Returns the number of entries deleted in this tick.
1767
+ */
1768
+ purgeNextBucket() {
1769
+ this.ensureDir();
1770
+ if (!this.dirReady) return 0;
1771
+ this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
1772
+ if (this._db) {
1773
+ const now2 = Date.now();
1774
+ const expired = this._stmtExpire.all(now2);
1775
+ for (const row of expired) {
1776
+ try {
1777
+ import_fs.default.unlinkSync(row.file_path);
1778
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1779
+ this.fileCount = Math.max(0, this.fileCount - 1);
1780
+ } catch {
1781
+ }
1782
+ }
1783
+ if (expired.length > 0) this._stmtDelExp.run(now2);
1784
+ const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
1785
+ const orphanBucketP = import_path.default.join(this.opts.dir, orphanBucket.toString(16).padStart(2, "0"));
1786
+ let orphanFiles;
1331
1787
  try {
1788
+ orphanFiles = import_fs.default.readdirSync(orphanBucketP);
1789
+ } catch {
1790
+ return expired.length;
1791
+ }
1792
+ for (const file of orphanFiles) {
1793
+ if (file.length === 77 && file[64] === "_") {
1794
+ const expiresAt = parseInt(file.slice(65), 16);
1795
+ if (expiresAt <= now2) {
1796
+ const fp = import_path.default.join(orphanBucketP, file);
1797
+ try {
1798
+ const sz = import_fs.default.statSync(fp).size;
1799
+ import_fs.default.unlinkSync(fp);
1800
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1801
+ this.fileCount = Math.max(0, this.fileCount - 1);
1802
+ } catch {
1803
+ }
1804
+ }
1805
+ }
1806
+ }
1807
+ return expired.length;
1808
+ }
1809
+ const bucket = (this._nextJanitorBucket - 1 + 256) % 256;
1810
+ const bucketHex = bucket.toString(16).padStart(2, "0");
1811
+ const bucketPath = import_path.default.join(this.opts.dir, bucketHex);
1812
+ let files;
1813
+ try {
1814
+ files = import_fs.default.readdirSync(bucketPath);
1815
+ } catch {
1816
+ return 0;
1817
+ }
1818
+ const now = Date.now();
1819
+ let purged = 0;
1820
+ const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
1821
+ for (const file of files) {
1822
+ if (file.length === 77 && file[64] === "_") {
1823
+ const expiresAt = parseInt(file.slice(65), 16);
1824
+ if (expiresAt <= now) {
1825
+ const filePath2 = import_path.default.join(bucketPath, file);
1826
+ try {
1827
+ const sz = import_fs.default.statSync(filePath2).size;
1828
+ import_fs.default.unlinkSync(filePath2);
1829
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1830
+ this.fileCount = Math.max(0, this.fileCount - 1);
1831
+ purged++;
1832
+ } catch {
1833
+ }
1834
+ }
1835
+ continue;
1836
+ }
1837
+ const filePath = import_path.default.join(bucketPath, file);
1838
+ let fd = -1;
1839
+ try {
1840
+ fd = import_fs.default.openSync(filePath, "r");
1841
+ const bytesRead = import_fs.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
1842
+ import_fs.default.closeSync(fd);
1843
+ fd = -1;
1844
+ if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1845
+ const expiresAt = Number(headerBuf.readBigUInt64LE(8));
1846
+ if (expiresAt <= now) {
1847
+ try {
1848
+ const sz = import_fs.default.statSync(filePath).size;
1849
+ import_fs.default.unlinkSync(filePath);
1850
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
1851
+ this.fileCount = Math.max(0, this.fileCount - 1);
1852
+ purged++;
1853
+ } catch {
1854
+ }
1855
+ }
1856
+ continue;
1857
+ }
1332
1858
  const stat = import_fs.default.statSync(filePath);
1333
1859
  if (stat.size > this.opts.entryMaxBytes) {
1334
1860
  import_fs.default.unlinkSync(filePath);
@@ -1348,13 +1874,18 @@ var DiskTier = class {
1348
1874
  continue;
1349
1875
  }
1350
1876
  const payload = (0, import_msgpackr2.unpack)(dec);
1351
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
1877
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
1352
1878
  import_fs.default.unlinkSync(filePath);
1353
1879
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1354
1880
  this.fileCount = Math.max(0, this.fileCount - 1);
1355
1881
  purged++;
1356
1882
  }
1357
1883
  } catch {
1884
+ } finally {
1885
+ if (fd >= 0) try {
1886
+ import_fs.default.closeSync(fd);
1887
+ } catch {
1888
+ }
1358
1889
  }
1359
1890
  }
1360
1891
  return purged;
@@ -1374,11 +1905,35 @@ var DiskTier = class {
1374
1905
  } catch {
1375
1906
  }
1376
1907
  }
1908
+ if (this._db) {
1909
+ this._db.exec("DELETE FROM meta");
1910
+ this.diskUsageBytes = 0;
1911
+ this.fileCount = 0;
1912
+ }
1377
1913
  return cleared;
1378
1914
  }
1379
1915
  get stats() {
1916
+ if (this._db) {
1917
+ const row = this._stmtStats.get();
1918
+ this.fileCount = row.cnt;
1919
+ this.diskUsageBytes = row.bytes;
1920
+ }
1380
1921
  return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1381
1922
  }
1923
+ /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
1924
+ get indexMode() {
1925
+ return this._db ? "sqlite" : "file-only";
1926
+ }
1927
+ /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
1928
+ close() {
1929
+ if (this._db) {
1930
+ try {
1931
+ this._db.close();
1932
+ } catch {
1933
+ }
1934
+ this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete = this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
1935
+ }
1936
+ }
1382
1937
  };
1383
1938
 
1384
1939
  // src/cache-service.ts
@@ -1430,6 +1985,95 @@ var L2CircuitBreaker = class {
1430
1985
  return this.state === 0 /* CLOSED */ ? "closed" : this.state === 1 /* OPEN */ ? "open" : "half_open";
1431
1986
  }
1432
1987
  };
1988
+ function deepFreeze(obj) {
1989
+ if (obj === null || typeof obj !== "object" || Object.isFrozen(obj)) return obj;
1990
+ Object.freeze(obj);
1991
+ for (const v of Object.values(obj)) deepFreeze(v);
1992
+ return obj;
1993
+ }
1994
+ var LatencyTracker = class {
1995
+ samples;
1996
+ maxKeys;
1997
+ bufs = /* @__PURE__ */ new Map();
1998
+ meta = /* @__PURE__ */ new Map();
1999
+ /** Shared sort buffer — safe to reuse because JS is single-threaded. */
2000
+ scratch;
2001
+ constructor(samples, maxKeys) {
2002
+ this.samples = samples;
2003
+ this.maxKeys = maxKeys;
2004
+ this.scratch = new Float64Array(samples);
2005
+ }
2006
+ record(key, deltaMs) {
2007
+ let buf = this.bufs.get(key);
2008
+ let m = this.meta.get(key);
2009
+ if (buf === void 0) {
2010
+ if (this.bufs.size >= this.maxKeys) {
2011
+ const oldest = this.bufs.keys().next().value;
2012
+ this.bufs.delete(oldest);
2013
+ this.meta.delete(oldest);
2014
+ }
2015
+ buf = new Float64Array(this.samples);
2016
+ m = { head: 0, count: 0, p95: 0, dirty: false };
2017
+ this.bufs.set(key, buf);
2018
+ this.meta.set(key, m);
2019
+ }
2020
+ buf[m.head] = deltaMs;
2021
+ m.head = (m.head + 1) % this.samples;
2022
+ if (m.count < this.samples) m.count++;
2023
+ m.dirty = true;
2024
+ }
2025
+ /**
2026
+ * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
2027
+ * Uses the shared scratch buffer — no heap allocation.
2028
+ */
2029
+ _computeP95(buf, m) {
2030
+ const n = m.count;
2031
+ this.scratch.set(buf.subarray(0, n));
2032
+ const view = this.scratch.subarray(0, n);
2033
+ view.sort();
2034
+ m.p95 = view[Math.ceil(n * 0.95) - 1];
2035
+ m.dirty = false;
2036
+ }
2037
+ /**
2038
+ * Returns the p95 fetch latency for `key` in milliseconds, or `null` when
2039
+ * fewer than 5 samples have been collected (not enough data yet).
2040
+ * Uses a dirty-flag cache — sort only runs when a new sample was recorded.
2041
+ */
2042
+ p95(key) {
2043
+ const buf = this.bufs.get(key);
2044
+ const m = this.meta.get(key);
2045
+ if (!buf || !m || m.count < 5) return null;
2046
+ if (m.dirty) this._computeP95(buf, m);
2047
+ return m.p95;
2048
+ }
2049
+ get trackedKeys() {
2050
+ return this.bufs.size;
2051
+ }
2052
+ /**
2053
+ * Top-20 slowest keys by p95, sorted descending.
2054
+ * Keys with < 5 samples are excluded (not enough data for a reliable p95).
2055
+ *
2056
+ * Only dirty keys (those with new samples since the last call) pay the sort
2057
+ * cost. Keys whose p95 is already cached are O(1) reads — so repeated
2058
+ * metrics() calls with no intervening fetches are essentially free.
2059
+ */
2060
+ snapshot(prefixLen, multiplierSec, minMs, maxMs) {
2061
+ const out = [];
2062
+ for (const [key, buf] of this.bufs) {
2063
+ const m = this.meta.get(key);
2064
+ if (m.count < 5) continue;
2065
+ if (m.dirty) this._computeP95(buf, m);
2066
+ const p95 = m.p95;
2067
+ const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1e3)));
2068
+ out.push({
2069
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
2070
+ p95Ms: Math.round(p95),
2071
+ adaptedTtlSec: Math.round(adaptedMs / 1e3)
2072
+ });
2073
+ }
2074
+ return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
2075
+ }
2076
+ };
1433
2077
  function inferPriority(cacheKey) {
1434
2078
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1435
2079
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1463,9 +2107,11 @@ var CacheService = class _CacheService {
1463
2107
  snapshotLoaded = false;
1464
2108
  _readyPromise = Promise.resolve();
1465
2109
  cleanupInterval = null;
2110
+ diskJanitorInterval = null;
1466
2111
  oomInterval = null;
1467
2112
  metricsInterval = null;
1468
2113
  _shutdownHandler = null;
2114
+ latencyTracker = null;
1469
2115
  instanceId;
1470
2116
  backplaneChannel;
1471
2117
  subClient = null;
@@ -1536,14 +2182,27 @@ var CacheService = class _CacheService {
1536
2182
  staleIfError: options.staleIfError ?? 0,
1537
2183
  l2WriteMode: options.l2WriteMode ?? "read-write",
1538
2184
  instanceName: options.instanceName ?? "",
2185
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
1539
2186
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1540
2187
  tracer: options.tracer,
1541
2188
  notFoundTtl: options.notFoundTtl ?? 0,
1542
- warmKeys: options.warmKeys
2189
+ warmKeys: options.warmKeys,
2190
+ onHit: options.onHit,
2191
+ onMiss: options.onMiss,
2192
+ frozen: options.frozen ?? false,
2193
+ adaptiveTtl: options.adaptiveTtl ?? false,
2194
+ adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1e3,
2195
+ adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86400) * 1e3,
2196
+ adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20
1543
2197
  };
1544
2198
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1545
2199
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
1546
2200
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
2201
+ if (this.opts.adaptiveTtl) {
2202
+ const samples = options.adaptiveTtlSamples ?? 32;
2203
+ const maxKeys = options.adaptiveTtlMaxKeys ?? 5e3;
2204
+ this.latencyTracker = new LatencyTracker(samples, maxKeys);
2205
+ }
1547
2206
  this.disk = new DiskTier({
1548
2207
  dir: this.opts.diskCacheDir,
1549
2208
  maxBytes: this.opts.diskMaxBytes,
@@ -1558,8 +2217,11 @@ var CacheService = class _CacheService {
1558
2217
  maxBytes: this.opts.l1MaxBytes,
1559
2218
  maxEntries: this.opts.l1MaxEntries,
1560
2219
  categories: this.opts.categoryLimits,
2220
+ evictionWatermark: this.opts.l1EvictionWatermark,
1561
2221
  diskSpill: (key, entry) => {
1562
- void this.disk.save(key, entry);
2222
+ setImmediate(() => {
2223
+ void this.disk.save(key, entry);
2224
+ });
1563
2225
  },
1564
2226
  onEviction: options.onEviction,
1565
2227
  logger
@@ -1576,12 +2238,14 @@ var CacheService = class _CacheService {
1576
2238
  process.once("SIGINT", this._shutdownHandler);
1577
2239
  this.cleanupInterval = setInterval(() => {
1578
2240
  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
- }
2241
+ if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
1583
2242
  }, 5 * 60 * 1e3);
1584
2243
  if (this.cleanupInterval.unref) this.cleanupInterval.unref();
2244
+ this.diskJanitorInterval = setInterval(() => {
2245
+ const purged = this.disk.purgeNextBucket();
2246
+ if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
2247
+ }, 3e4);
2248
+ if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
1585
2249
  if (this.opts.oomProtection) {
1586
2250
  this.oomInterval = setInterval(() => {
1587
2251
  const mem = process.memoryUsage();
@@ -1673,15 +2337,22 @@ var CacheService = class _CacheService {
1673
2337
  if (j === 0) return ttlMs;
1674
2338
  return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
1675
2339
  }
2340
+ /** Shared no-op span for the common case where no tracer is configured.
2341
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
2342
+ static _nullSpan = {
2343
+ setAttribute() {
2344
+ return this;
2345
+ },
2346
+ setStatus() {
2347
+ return this;
2348
+ },
2349
+ end() {
2350
+ }
2351
+ };
1676
2352
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
1677
2353
  _startSpan(name) {
1678
2354
  if (this.opts.tracer) return this.opts.tracer.startSpan(name);
1679
- return { setAttribute() {
1680
- return this;
1681
- }, setStatus() {
1682
- return this;
1683
- }, end() {
1684
- } };
2355
+ return _CacheService._nullSpan;
1685
2356
  }
1686
2357
  initBackplane() {
1687
2358
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
@@ -1870,15 +2541,21 @@ var CacheService = class _CacheService {
1870
2541
  */
1871
2542
  async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
1872
2543
  const span = this._startSpan("tricache.get");
1873
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2544
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
1874
2545
  const k = this.nk(cacheKey);
1875
2546
  this.counters.gets++;
2547
+ const optSwr = opts.swr ?? 0;
2548
+ const optPriority = opts.priority;
2549
+ const optRefreshAhead = opts.refreshAhead;
2550
+ const optXfetchBeta = opts.xfetchBeta;
2551
+ const optNotFoundTtl = opts.notFoundTtl;
2552
+ const optTags = opts.tags;
1876
2553
  const l1Hit = this.l1.get(k);
1877
2554
  if (l1Hit !== null) {
1878
2555
  if (l1Hit.isStale) {
1879
- const swrGraceMs2 = (opts.swr ?? 0) * 1e3;
2556
+ const swrGraceMs2 = optSwr * 1e3;
1880
2557
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
1881
- const priority2 = opts.priority ?? inferPriority(cacheKey);
2558
+ const priority2 = optPriority ?? inferPriority(cacheKey);
1882
2559
  this.revalidating.add(k);
1883
2560
  void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
1884
2561
  this.counters.swrRevalidations++;
@@ -1888,16 +2565,18 @@ var CacheService = class _CacheService {
1888
2565
  }
1889
2566
  } else {
1890
2567
  this.logger.debug("L1 hit");
1891
- if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
1892
- const now = Date.now();
2568
+ const ra = optRefreshAhead;
2569
+ const xb = optXfetchBeta;
2570
+ if (ra || xb) {
2571
+ const now = l1Hit.fetchedAt ?? Date.now();
1893
2572
  const remaining = l1Hit.expiresAt - now;
1894
2573
  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) {
1898
- const priority2 = opts.priority ?? inferPriority(cacheKey);
2574
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
2575
+ const shouldXFetch = xb && l1Hit.delta != null ? remaining <= l1Hit.delta * xb * -Math.log(Math.random()) : false;
2576
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2577
+ const priority2 = optPriority ?? inferPriority(cacheKey);
1899
2578
  this.revalidating.add(k);
1900
- void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
2579
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
1901
2580
  this.counters.swrRevalidations++;
1902
2581
  this.logger.debug(
1903
2582
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -1907,12 +2586,14 @@ var CacheService = class _CacheService {
1907
2586
  }
1908
2587
  }
1909
2588
  this.counters.l1Hits++;
2589
+ this.opts.onHit?.(cacheKey, "l1");
2590
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
1910
2591
  span.setAttribute("cache.hit", "l1").end();
1911
2592
  return l1Hit.value;
1912
2593
  }
1913
2594
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
1914
- const swrGraceMs = (opts.swr ?? 0) * 1e3;
1915
- const priority = opts.priority ?? inferPriority(cacheKey);
2595
+ const swrGraceMs = optSwr * 1e3;
2596
+ const priority = optPriority ?? inferPriority(cacheKey);
1916
2597
  if (!this._redisDisabled) {
1917
2598
  try {
1918
2599
  const client = await this.getRedis();
@@ -1923,6 +2604,7 @@ var CacheService = class _CacheService {
1923
2604
  const parsed = JSON.parse(decrypted);
1924
2605
  this.l1.set(k, parsed, ttlMs, priority);
1925
2606
  this.counters.l2Hits++;
2607
+ this.opts.onHit?.(cacheKey, "l2");
1926
2608
  this.logger.debug("L2 hit (Redis)", { cacheKey });
1927
2609
  span.setAttribute("cache.hit", "l2").end();
1928
2610
  return parsed;
@@ -1942,6 +2624,7 @@ var CacheService = class _CacheService {
1942
2624
  const l1Check = this.l1.get(k);
1943
2625
  if (l1Check !== null) {
1944
2626
  this.counters.diskHits++;
2627
+ this.opts.onHit?.(cacheKey, "disk");
1945
2628
  this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
1946
2629
  span.setAttribute("cache.hit", "disk").end();
1947
2630
  return l1Check.value;
@@ -1949,6 +2632,7 @@ var CacheService = class _CacheService {
1949
2632
  }
1950
2633
  }
1951
2634
  span.setAttribute("cache.hit", "miss");
2635
+ this.opts.onMiss?.(cacheKey);
1952
2636
  const existing = this.inflight.get(k);
1953
2637
  if (existing) {
1954
2638
  this.counters.stampedes++;
@@ -1962,11 +2646,23 @@ var CacheService = class _CacheService {
1962
2646
  const fetchStart = Date.now();
1963
2647
  const data = await fetchFn();
1964
2648
  const delta = Date.now() - fetchStart;
1965
- const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
1966
- const effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
2649
+ const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1e3;
2650
+ let effectiveTtl = data == null && notFoundTtlMs > 0 ? notFoundTtlMs : ttlMs;
2651
+ if (this.latencyTracker && data != null) {
2652
+ this.latencyTracker.record(k, delta);
2653
+ const p95 = this.latencyTracker.p95(k);
2654
+ if (p95 !== null) {
2655
+ const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1e3);
2656
+ effectiveTtl = Math.max(
2657
+ this.opts.adaptiveTtlMinMs,
2658
+ Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs)
2659
+ );
2660
+ }
2661
+ }
1967
2662
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
1968
2663
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
1969
2664
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
2665
+ if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
1970
2666
  if (!this._redisDisabled) {
1971
2667
  try {
1972
2668
  const client = await this.getRedis();
@@ -1997,6 +2693,7 @@ var CacheService = class _CacheService {
1997
2693
  const data = await fetchFn();
1998
2694
  const delta = Date.now() - fetchStart;
1999
2695
  const staleAt = Date.now() + ttlMs;
2696
+ if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
2000
2697
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
2001
2698
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2002
2699
  try {
@@ -2027,38 +2724,13 @@ var CacheService = class _CacheService {
2027
2724
  /** Explicitly write a value into L1 (+ L2 in production). */
2028
2725
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
2029
2726
  const span = this._startSpan("tricache.set");
2030
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2727
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2031
2728
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2032
2729
  const p = priority ?? inferPriority(cacheKey);
2033
2730
  const k = this.nk(cacheKey);
2034
2731
  this.counters.sets++;
2035
2732
  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
- }
2733
+ if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
2062
2734
  if (opts?.dependsOn?.length) {
2063
2735
  for (const pattern of opts.dependsOn) {
2064
2736
  const nsPattern = this.nk(pattern);
@@ -2085,6 +2757,36 @@ var CacheService = class _CacheService {
2085
2757
  void this.publishInvalidation("del", k);
2086
2758
  span.end();
2087
2759
  }
2760
+ /**
2761
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
2762
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
2763
+ */
2764
+ async _registerTags(k, tags, ttlSeconds) {
2765
+ for (const tag of tags) {
2766
+ const tagKey = this.nk(`_tag_:${tag}`);
2767
+ let members = this.tagIndex.get(tagKey);
2768
+ if (!members) {
2769
+ members = /* @__PURE__ */ new Set();
2770
+ this.tagIndex.set(tagKey, members);
2771
+ }
2772
+ members.add(k);
2773
+ }
2774
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2775
+ try {
2776
+ const client = await this.getRedis();
2777
+ const pl = client.pipeline();
2778
+ for (const tag of tags) {
2779
+ const tagKey = this.nk(`_tag_:${tag}`);
2780
+ pl.sadd(tagKey, k);
2781
+ pl.expire(tagKey, ttlSeconds + 3600);
2782
+ }
2783
+ await pl.exec();
2784
+ this.cb.onSuccess();
2785
+ } catch {
2786
+ this.cb.onFailure();
2787
+ }
2788
+ }
2789
+ }
2088
2790
  /**
2089
2791
  * Delete one key or a glob pattern (supports `*` wildcard).
2090
2792
  *
@@ -2094,7 +2796,7 @@ var CacheService = class _CacheService {
2094
2796
  */
2095
2797
  async delete(cacheKey) {
2096
2798
  const span = this._startSpan("tricache.delete");
2097
- span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2799
+ if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2098
2800
  const isPattern = cacheKey.includes("*");
2099
2801
  const k = this.nk(cacheKey);
2100
2802
  this.counters.deletes++;
@@ -2102,7 +2804,7 @@ var CacheService = class _CacheService {
2102
2804
  this.l1.deletePattern(k);
2103
2805
  } else {
2104
2806
  this.l1.delete(k);
2105
- this.disk.delete(k);
2807
+ setImmediate(() => this.disk.delete(k));
2106
2808
  this._cascadeDependencies(k);
2107
2809
  for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
2108
2810
  }
@@ -2258,6 +2960,33 @@ var CacheService = class _CacheService {
2258
2960
  yield [k, entry.value !== void 0 ? entry.value : entry.data];
2259
2961
  }
2260
2962
  }
2963
+ /**
2964
+ * High-throughput bulk scan over all live L1 entries.
2965
+ *
2966
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
2967
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
2968
+ * caller uses the `offset` parameter instead of pre-slicing.
2969
+ *
2970
+ * ```typescript
2971
+ * // Zero extra string allocations — use rawKey + offset directly:
2972
+ * cache.scan((rawKey, value, offset) => {
2973
+ * const key = rawKey.slice(offset); // allocate only if needed
2974
+ * sync(key, value as User);
2975
+ * });
2976
+ * ```
2977
+ *
2978
+ * @param fn Called once per live L1 entry.
2979
+ * `rawKey` — key with namespace prefix still attached.
2980
+ * `value` — deserialized cached value.
2981
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
2982
+ */
2983
+ scan(fn) {
2984
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2985
+ this.l1.scan((key, entry, pfx) => {
2986
+ const value = entry.value !== void 0 ? entry.value : entry.data;
2987
+ fn(key, value, pfx);
2988
+ }, prefixLen);
2989
+ }
2261
2990
  /**
2262
2991
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
2263
2992
  * Returns `false` if the key is absent or already expired.
@@ -2383,7 +3112,7 @@ var CacheService = class _CacheService {
2383
3112
  * const loaded = await cache.warmFromL2('org:*');
2384
3113
  * console.log(`Warmed ${loaded} keys from Redis`);
2385
3114
  */
2386
- async warmFromL2(pattern) {
3115
+ async warmFromL2(pattern, opts) {
2387
3116
  if (this._redisDisabled) return 0;
2388
3117
  try {
2389
3118
  const client = await this.getRedis();
@@ -2412,8 +3141,9 @@ var CacheService = class _CacheService {
2412
3141
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
2413
3142
  const parsed = JSON.parse(decrypted);
2414
3143
  const remainingMs = 10 * 60 * 1e3;
2415
- this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
3144
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
2416
3145
  loaded++;
3146
+ ;
2417
3147
  } catch {
2418
3148
  }
2419
3149
  }
@@ -2461,6 +3191,58 @@ var CacheService = class _CacheService {
2461
3191
  }
2462
3192
  }
2463
3193
  }
3194
+ /**
3195
+ * Invalidate all keys associated with any of the given tags in a single operation.
3196
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
3197
+ * reducing latency when invalidating several related tags together.
3198
+ *
3199
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
3200
+ * synchronously before the Redis round-trip.
3201
+ *
3202
+ * @example
3203
+ * // Instead of three serial round-trips:
3204
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
3205
+ */
3206
+ async invalidateTags(tags) {
3207
+ if (tags.length === 0) return;
3208
+ if (tags.length === 1) {
3209
+ await this.invalidateTag(tags[0]);
3210
+ return;
3211
+ }
3212
+ const tagKeys = [];
3213
+ const allMembers = /* @__PURE__ */ new Set();
3214
+ for (const tag of tags) {
3215
+ const tagKey = this.nk(`_tag_:${tag}`);
3216
+ tagKeys.push(tagKey);
3217
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
3218
+ for (const k of members) allMembers.add(k);
3219
+ this.tagIndex.delete(tagKey);
3220
+ }
3221
+ for (const k of allMembers) {
3222
+ this.l1.delete(k);
3223
+ this.disk.delete(k);
3224
+ }
3225
+ if (!this._redisDisabled) {
3226
+ try {
3227
+ const client = await this.getRedis();
3228
+ const pl = client.pipeline();
3229
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
3230
+ const smResults = await pl.exec();
3231
+ const toDelete = [...allMembers];
3232
+ for (const [err, redisMembers] of smResults) {
3233
+ if (!err && redisMembers) {
3234
+ for (const k of redisMembers) {
3235
+ if (!allMembers.has(k)) toDelete.push(k);
3236
+ }
3237
+ }
3238
+ }
3239
+ const keysToRemove = [...toDelete, ...tagKeys];
3240
+ if (keysToRemove.length > 0) await client.del(...keysToRemove);
3241
+ } catch (err) {
3242
+ this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
3243
+ }
3244
+ }
3245
+ }
2464
3246
  /**
2465
3247
  * Measure L1 / disk / Redis latency.
2466
3248
  * Useful for health checks and dashboards.
@@ -2664,7 +3446,20 @@ var CacheService = class _CacheService {
2664
3446
  sizeBytes: this.l1.memoryUsage,
2665
3447
  maxBytes: this.opts.l1MaxBytes
2666
3448
  },
2667
- disk: this.disk.stats
3449
+ disk: this.disk.stats,
3450
+ ...this.latencyTracker && {
3451
+ adaptiveTtl: {
3452
+ enabled: true,
3453
+ trackedKeys: this.latencyTracker.trackedKeys,
3454
+ slowestKeys: this.latencyTracker.snapshot(
3455
+ this._namespace ? this._namespace.length + 1 : 0,
3456
+ // strip "namespace:" prefix
3457
+ this.opts.adaptiveTtlMultiplier,
3458
+ this.opts.adaptiveTtlMinMs,
3459
+ this.opts.adaptiveTtlMaxMs
3460
+ )
3461
+ }
3462
+ }
2668
3463
  };
2669
3464
  }
2670
3465
  /**
@@ -2733,6 +3528,7 @@ var CacheService = class _CacheService {
2733
3528
  /** Close Redis connections and stop all background timers. */
2734
3529
  async destroy() {
2735
3530
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
3531
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
2736
3532
  if (this.oomInterval) clearInterval(this.oomInterval);
2737
3533
  if (this.metricsInterval) clearInterval(this.metricsInterval);
2738
3534
  if (this._shutdownHandler) {
@@ -2754,6 +3550,7 @@ var CacheService = class _CacheService {
2754
3550
  }
2755
3551
  this.redis = null;
2756
3552
  }
3553
+ this.disk.close();
2757
3554
  }
2758
3555
  };
2759
3556
  // Annotate the CommonJS export names for ESM import in node: