tricache 0.5.1 → 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,7 +228,7 @@ 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
233
  const fin = c2.final();
210
234
  const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
@@ -216,7 +240,7 @@ var CacheEncryption = class {
216
240
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
217
241
  const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
218
242
  const iv = this._nextIV();
219
- const c = (0, import_crypto.createCipheriv)(algo, this._key, iv);
243
+ const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
220
244
  const enc = c.update(plaintext, "utf8");
221
245
  c.final();
222
246
  const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
@@ -232,18 +256,18 @@ var CacheEncryption = class {
232
256
  */
233
257
  decrypt(value) {
234
258
  try {
235
- return this._decryptWithKey(value, this._key, this._mode);
259
+ return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
236
260
  } catch (primaryErr) {
237
261
  if (this._prevKey) {
238
262
  try {
239
- return this._decryptWithKey(value, this._prevKey, this._prevMode);
263
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
240
264
  } catch {
241
265
  }
242
266
  }
243
267
  throw primaryErr;
244
268
  }
245
269
  }
246
- _decryptWithKey(value, key, mode) {
270
+ _decryptWithKey(value, key, keyObj, mode) {
247
271
  if (value.startsWith(PREFIX_XOR)) {
248
272
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
249
273
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -254,11 +278,11 @@ var CacheEncryption = class {
254
278
  return out.toString("utf8");
255
279
  }
256
280
  if (value.startsWith(PREFIX_CTR)) {
257
- 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");
258
282
  const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
259
283
  const iv2 = combined2.subarray(0, CTR_IV_BYTES);
260
284
  const ct2 = combined2.subarray(CTR_IV_BYTES);
261
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
285
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
262
286
  const plain2 = d2.update(ct2);
263
287
  const fin = d2.final();
264
288
  return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
@@ -266,19 +290,20 @@ var CacheEncryption = class {
266
290
  const is256 = value.startsWith(PREFIX_256);
267
291
  const is128 = value.startsWith(PREFIX_128);
268
292
  if (!is256 && !is128) return value;
269
- 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");
270
294
  const prefix = is128 ? PREFIX_128 : PREFIX_256;
271
295
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
272
296
  const combined = Buffer.from(value.slice(prefix.length), "base64");
273
297
  const iv = combined.subarray(0, IV_BYTES);
274
298
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
275
299
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
276
- const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
300
+ const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
277
301
  d.setAuthTag(tag);
278
302
  const plain = d.update(ct);
279
303
  d.final();
280
304
  return plain.toString("utf8");
281
305
  void mode;
306
+ void key;
282
307
  }
283
308
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
284
309
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
@@ -293,7 +318,7 @@ var CacheEncryption = class {
293
318
  }
294
319
  if (this._mode === "aes-128-ctr") {
295
320
  const iv2 = this._nextCtrIV();
296
- 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);
297
322
  const enc2 = c2.update(data);
298
323
  const fin = c2.final();
299
324
  const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
@@ -306,7 +331,7 @@ var CacheEncryption = class {
306
331
  const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
307
332
  const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
308
333
  const iv = this._nextIV();
309
- const c = (0, import_crypto.createCipheriv)(algo, this._key, iv);
334
+ const c = (0, import_crypto.createCipheriv)(algo, this._keyObj, iv);
310
335
  const enc = c.update(data);
311
336
  c.final();
312
337
  const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
@@ -323,18 +348,18 @@ var CacheEncryption = class {
323
348
  */
324
349
  decryptBuffer(data) {
325
350
  try {
326
- return this._decryptBufferWithKey(data, this._key);
351
+ return this._decryptBufferWithKey(data, this._key, this._keyObj);
327
352
  } catch (primaryErr) {
328
353
  if (this._prevKey) {
329
354
  try {
330
- return this._decryptBufferWithKey(data, this._prevKey);
355
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
331
356
  } catch {
332
357
  }
333
358
  }
334
359
  throw primaryErr;
335
360
  }
336
361
  }
337
- _decryptBufferWithKey(data, key) {
362
+ _decryptBufferWithKey(data, key, keyObj) {
338
363
  if (data.length < MAGIC_LEN) return data;
339
364
  const magic = data.subarray(0, MAGIC_LEN);
340
365
  if (magic.equals(MAGIC_XOR)) {
@@ -346,10 +371,10 @@ var CacheEncryption = class {
346
371
  return out;
347
372
  }
348
373
  if (magic.equals(MAGIC_CTR)) {
349
- 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");
350
375
  const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
351
376
  const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
352
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
377
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", keyObj, iv2);
353
378
  const plain2 = d2.update(ct2);
354
379
  const fin = d2.final();
355
380
  return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
@@ -357,12 +382,12 @@ var CacheEncryption = class {
357
382
  const is256 = magic.equals(MAGIC_256);
358
383
  const is128 = magic.equals(MAGIC_128);
359
384
  if (!is256 && !is128) return data;
360
- 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");
361
386
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
362
387
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
363
388
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
364
389
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
365
- const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
390
+ const d = (0, import_crypto.createDecipheriv)(algo, keyObj, iv);
366
391
  d.setAuthTag(tag);
367
392
  const plain = d.update(ct);
368
393
  d.final();
@@ -439,6 +464,8 @@ var WasmBloomFilter = class {
439
464
  // src/smart-memory-cache.ts
440
465
  var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0 };
441
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));
442
469
  var JsBloomFilter = class {
443
470
  bits;
444
471
  numBits;
@@ -626,6 +653,15 @@ var SmartMemoryCache = class {
626
653
  categoryHits = /* @__PURE__ */ new Map();
627
654
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
628
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 }));
629
665
  constructor(opts, existing) {
630
666
  this.opts = opts;
631
667
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
@@ -689,8 +725,9 @@ var SmartMemoryCache = class {
689
725
  const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
690
726
  const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
691
727
  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);
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);
694
731
  if (entryWatermark || byteWatermark) {
695
732
  this.smartEvict(category, false);
696
733
  }
@@ -726,9 +763,9 @@ var SmartMemoryCache = class {
726
763
  }
727
764
  smartEvict(targetCat, catOvf) {
728
765
  const now = Date.now();
729
- const SAMPLE = 16;
730
- const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT));
731
- const pool = [];
766
+ const pool = this._evictPool;
767
+ const gPool = this._evictGPool;
768
+ let poolLen = 0;
732
769
  if (catOvf) {
733
770
  const catKeySet = this.categoryKeys.get(targetCat);
734
771
  if (catKeySet) {
@@ -738,36 +775,62 @@ var SmartMemoryCache = class {
738
775
  if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
739
776
  catSeen++;
740
777
  const s = this.score(entry, 100, now, key);
741
- if (pool.length < EVICT) {
742
- pool.push({ key, score: s });
778
+ if (poolLen < EVICT_COUNT) {
779
+ pool[poolLen].key = key;
780
+ pool[poolLen].score = s;
781
+ poolLen++;
743
782
  } else {
744
783
  const j = Math.floor(Math.random() * catSeen);
745
- if (j < EVICT) pool[j] = { key, score: s };
784
+ if (j < EVICT_COUNT) {
785
+ pool[j].key = key;
786
+ pool[j].score = s;
787
+ }
746
788
  }
747
789
  }
748
790
  }
749
791
  }
750
- if (pool.length < EVICT) {
751
- const remaining = SAMPLE - pool.length;
792
+ if (poolLen < EVICT_COUNT) {
793
+ const remaining = EVICTION_SAMPLE - poolLen;
752
794
  let globalSeen = 0;
753
- const globalPool = [];
795
+ let gLen = 0;
754
796
  for (const [key, entry] of this.cache) {
755
797
  if (entry.priority === 4 && entry.expiresAt > now) continue;
756
798
  if (catOvf && this.getCategory(key) === targetCat) continue;
757
799
  globalSeen++;
758
800
  const s = this.score(entry, 0, now, key);
759
- if (globalPool.length < remaining) {
760
- globalPool.push({ key, score: s });
801
+ if (gLen < remaining) {
802
+ gPool[gLen].key = key;
803
+ gPool[gLen].score = s;
804
+ gLen++;
761
805
  } else {
762
806
  const j = Math.floor(Math.random() * globalSeen);
763
- if (j < remaining) globalPool[j] = { key, score: s };
807
+ if (j < remaining) {
808
+ gPool[j].key = key;
809
+ gPool[j].score = s;
810
+ }
764
811
  }
765
812
  }
766
- 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;
767
830
  }
768
- if (pool.length === 0) return;
769
- pool.sort((a, b) => a.score - b.score);
770
- 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;
771
834
  const entry = this.cache.get(key);
772
835
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
773
836
  this._delete(key, "capacity");
@@ -1172,7 +1235,15 @@ var SmartMemoryCache = class {
1172
1235
  var import_fs = __toESM(require("fs"), 1);
1173
1236
  var import_path = __toESM(require("path"), 1);
1174
1237
  var import_crypto2 = __toESM(require("crypto"), 1);
1238
+ var import_module = require("module");
1175
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
+ }
1176
1247
  var AES_ALGO = "aes-256-gcm";
1177
1248
  var IV_BYTES2 = 12;
1178
1249
  var TAG_BYTES2 = 16;
@@ -1189,6 +1260,20 @@ var DiskTier = class {
1189
1260
  // maintained in-memory; avoids walkCacheFiles() in stats
1190
1261
  /** Next bucket index (0–255) for the staggered janitor wheel. */
1191
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)
1192
1277
  constructor(opts) {
1193
1278
  this.opts = opts;
1194
1279
  }
@@ -1198,13 +1283,70 @@ var DiskTier = class {
1198
1283
  try {
1199
1284
  import_fs.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
1200
1285
  this.dirReady = true;
1286
+ this._initSqlite();
1201
1287
  } catch (err) {
1202
1288
  this.opts.logger.warn("DiskTier: cannot create cache dir", { dir: this.opts.dir, error: err.message });
1203
1289
  }
1204
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
+ }
1205
1346
  ensureUsageCounted() {
1206
1347
  if (this.usageCounted) return;
1207
1348
  this.usageCounted = true;
1349
+ if (this._db) return;
1208
1350
  try {
1209
1351
  this.ensureDir();
1210
1352
  let total = 0;
@@ -1392,10 +1534,17 @@ var DiskTier = class {
1392
1534
  try {
1393
1535
  await import_fs.default.promises.mkdir(import_path.default.dirname(filePath), { recursive: true });
1394
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
+ }
1395
1540
  this.opts.logger.debug("DiskTier: entry saved", { key: key.slice(0, 50), bytes: final.length });
1396
1541
  } catch (err) {
1397
1542
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
1398
1543
  this.fileCount = Math.max(0, this.fileCount - 1);
1544
+ if (this._db) try {
1545
+ this._stmtDelete.run(hash);
1546
+ } catch {
1547
+ }
1399
1548
  this.opts.logger.debug("DiskTier: save failed", { key: key.slice(0, 50), error: err.message });
1400
1549
  }
1401
1550
  }
@@ -1405,27 +1554,48 @@ var DiskTier = class {
1405
1554
  this.ensureDir();
1406
1555
  if (!this.dirReady) return null;
1407
1556
  const hash = this.keyToHash(key);
1408
- const filePath = this.findFilePath(hash);
1409
- if (!filePath) return null;
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
+ }
1410
1577
  try {
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 {
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;
1421
1591
  }
1422
- return null;
1423
1592
  }
1424
1593
  }
1425
1594
  const stat = import_fs.default.statSync(filePath);
1426
1595
  if (stat.size > this.opts.entryMaxBytes) {
1427
1596
  import_fs.default.unlinkSync(filePath);
1428
1597
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1598
+ if (this._db) this._stmtDelete.run(hash);
1429
1599
  return null;
1430
1600
  }
1431
1601
  const raw = import_fs.default.readFileSync(filePath);
@@ -1435,6 +1605,7 @@ var DiskTier = class {
1435
1605
  this.fileCount = Math.max(0, this.fileCount - 1);
1436
1606
  } catch {
1437
1607
  }
1608
+ if (this._db) this._stmtDelete.run(hash);
1438
1609
  let decrypted;
1439
1610
  if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
1440
1611
  const expiresAt = Number(raw.readBigUInt64LE(8));
@@ -1459,6 +1630,10 @@ var DiskTier = class {
1459
1630
  this.opts.logger.debug("DiskTier: hit (\u2192L1)", { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1460
1631
  return entry;
1461
1632
  } catch (err) {
1633
+ if (this._db) try {
1634
+ this._stmtDelete.run(hash);
1635
+ } catch {
1636
+ }
1462
1637
  this.opts.logger.debug("DiskTier: load failed", { key: key.slice(0, 50), error: err.message });
1463
1638
  return null;
1464
1639
  }
@@ -1466,7 +1641,14 @@ var DiskTier = class {
1466
1641
  /** Explicitly delete a key from disk (cache invalidation). */
1467
1642
  delete(key) {
1468
1643
  const hash = this.keyToHash(key);
1469
- const filePath = this.findFilePath(hash);
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
+ }
1470
1652
  if (!filePath) return;
1471
1653
  try {
1472
1654
  const stat = import_fs.default.statSync(filePath);
@@ -1480,6 +1662,20 @@ var DiskTier = class {
1480
1662
  purgeExpired() {
1481
1663
  this.ensureDir();
1482
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
+ }
1483
1679
  const now = Date.now();
1484
1680
  let purged = 0;
1485
1681
  const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
@@ -1555,22 +1751,64 @@ var DiskTier = class {
1555
1751
  return purged;
1556
1752
  }
1557
1753
  /**
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.
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.
1562
1761
  *
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.
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.
1565
1765
  *
1566
1766
  * Returns the number of entries deleted in this tick.
1567
1767
  */
1568
1768
  purgeNextBucket() {
1569
1769
  this.ensureDir();
1570
1770
  if (!this.dirReady) return 0;
1571
- const bucket = this._nextJanitorBucket.toString(16).padStart(2, "0");
1572
1771
  this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
1573
- const bucketPath = import_path.default.join(this.opts.dir, bucket);
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;
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);
1574
1812
  let files;
1575
1813
  try {
1576
1814
  files = import_fs.default.readdirSync(bucketPath);
@@ -1667,11 +1905,35 @@ var DiskTier = class {
1667
1905
  } catch {
1668
1906
  }
1669
1907
  }
1908
+ if (this._db) {
1909
+ this._db.exec("DELETE FROM meta");
1910
+ this.diskUsageBytes = 0;
1911
+ this.fileCount = 0;
1912
+ }
1670
1913
  return cleared;
1671
1914
  }
1672
1915
  get stats() {
1916
+ if (this._db) {
1917
+ const row = this._stmtStats.get();
1918
+ this.fileCount = row.cnt;
1919
+ this.diskUsageBytes = row.bytes;
1920
+ }
1673
1921
  return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1674
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
+ }
1675
1937
  };
1676
1938
 
1677
1939
  // src/cache-service.ts
@@ -1729,6 +1991,89 @@ function deepFreeze(obj) {
1729
1991
  for (const v of Object.values(obj)) deepFreeze(v);
1730
1992
  return obj;
1731
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
+ };
1732
2077
  function inferPriority(cacheKey) {
1733
2078
  if (cacheKey.includes("auth:") || cacheKey.includes("session:")) return 4 /* CRITICAL */;
1734
2079
  if (cacheKey.includes("user:") || cacheKey.includes("org:") || cacheKey.includes("profile:")) return 3 /* HIGH */;
@@ -1766,6 +2111,7 @@ var CacheService = class _CacheService {
1766
2111
  oomInterval = null;
1767
2112
  metricsInterval = null;
1768
2113
  _shutdownHandler = null;
2114
+ latencyTracker = null;
1769
2115
  instanceId;
1770
2116
  backplaneChannel;
1771
2117
  subClient = null;
@@ -1836,17 +2182,27 @@ var CacheService = class _CacheService {
1836
2182
  staleIfError: options.staleIfError ?? 0,
1837
2183
  l2WriteMode: options.l2WriteMode ?? "read-write",
1838
2184
  instanceName: options.instanceName ?? "",
2185
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
1839
2186
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
1840
2187
  tracer: options.tracer,
1841
2188
  notFoundTtl: options.notFoundTtl ?? 0,
1842
2189
  warmKeys: options.warmKeys,
1843
2190
  onHit: options.onHit,
1844
2191
  onMiss: options.onMiss,
1845
- frozen: options.frozen ?? false
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
1846
2197
  };
1847
2198
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
1848
2199
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
1849
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
+ }
1850
2206
  this.disk = new DiskTier({
1851
2207
  dir: this.opts.diskCacheDir,
1852
2208
  maxBytes: this.opts.diskMaxBytes,
@@ -1861,6 +2217,7 @@ var CacheService = class _CacheService {
1861
2217
  maxBytes: this.opts.l1MaxBytes,
1862
2218
  maxEntries: this.opts.l1MaxEntries,
1863
2219
  categories: this.opts.categoryLimits,
2220
+ evictionWatermark: this.opts.l1EvictionWatermark,
1864
2221
  diskSpill: (key, entry) => {
1865
2222
  setImmediate(() => {
1866
2223
  void this.disk.save(key, entry);
@@ -2187,12 +2544,18 @@ var CacheService = class _CacheService {
2187
2544
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
2188
2545
  const k = this.nk(cacheKey);
2189
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;
2190
2553
  const l1Hit = this.l1.get(k);
2191
2554
  if (l1Hit !== null) {
2192
2555
  if (l1Hit.isStale) {
2193
- const swrGraceMs2 = (opts.swr ?? 0) * 1e3;
2556
+ const swrGraceMs2 = optSwr * 1e3;
2194
2557
  if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
2195
- const priority2 = opts.priority ?? inferPriority(cacheKey);
2558
+ const priority2 = optPriority ?? inferPriority(cacheKey);
2196
2559
  this.revalidating.add(k);
2197
2560
  void this._revalidate(k, fetchFn, ttlSeconds * 1e3, swrGraceMs2, priority2);
2198
2561
  this.counters.swrRevalidations++;
@@ -2202,16 +2565,18 @@ var CacheService = class _CacheService {
2202
2565
  }
2203
2566
  } else {
2204
2567
  this.logger.debug("L1 hit");
2205
- if (opts.refreshAhead || opts.xfetchBeta) {
2568
+ const ra = optRefreshAhead;
2569
+ const xb = optXfetchBeta;
2570
+ if (ra || xb) {
2206
2571
  const now = l1Hit.fetchedAt ?? Date.now();
2207
2572
  const remaining = l1Hit.expiresAt - now;
2208
2573
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1e3;
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;
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;
2211
2576
  if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
2212
- const priority2 = opts.priority ?? inferPriority(cacheKey);
2577
+ const priority2 = optPriority ?? inferPriority(cacheKey);
2213
2578
  this.revalidating.add(k);
2214
- void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1e3, priority2);
2579
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1e3, priority2);
2215
2580
  this.counters.swrRevalidations++;
2216
2581
  this.logger.debug(
2217
2582
  shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
@@ -2227,8 +2592,8 @@ var CacheService = class _CacheService {
2227
2592
  return l1Hit.value;
2228
2593
  }
2229
2594
  const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
2230
- const swrGraceMs = (opts.swr ?? 0) * 1e3;
2231
- const priority = opts.priority ?? inferPriority(cacheKey);
2595
+ const swrGraceMs = optSwr * 1e3;
2596
+ const priority = optPriority ?? inferPriority(cacheKey);
2232
2597
  if (!this._redisDisabled) {
2233
2598
  try {
2234
2599
  const client = await this.getRedis();
@@ -2281,12 +2646,23 @@ var CacheService = class _CacheService {
2281
2646
  const fetchStart = Date.now();
2282
2647
  const data = await fetchFn();
2283
2648
  const delta = Date.now() - fetchStart;
2284
- const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1e3;
2285
- 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
+ }
2286
2662
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : void 0;
2287
2663
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
2288
2664
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
2289
- if (opts.tags?.length) await this._registerTags(k, opts.tags, Math.ceil(effectiveTtl / 1e3));
2665
+ if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
2290
2666
  if (!this._redisDisabled) {
2291
2667
  try {
2292
2668
  const client = await this.getRedis();
@@ -2317,6 +2693,7 @@ var CacheService = class _CacheService {
2317
2693
  const data = await fetchFn();
2318
2694
  const delta = Date.now() - fetchStart;
2319
2695
  const staleAt = Date.now() + ttlMs;
2696
+ if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
2320
2697
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
2321
2698
  if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
2322
2699
  try {
@@ -3069,7 +3446,20 @@ var CacheService = class _CacheService {
3069
3446
  sizeBytes: this.l1.memoryUsage,
3070
3447
  maxBytes: this.opts.l1MaxBytes
3071
3448
  },
3072
- 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
+ }
3073
3463
  };
3074
3464
  }
3075
3465
  /**
@@ -3160,6 +3550,7 @@ var CacheService = class _CacheService {
3160
3550
  }
3161
3551
  this.redis = null;
3162
3552
  }
3553
+ this.disk.close();
3163
3554
  }
3164
3555
  };
3165
3556
  // Annotate the CommonJS export names for ESM import in node: