tricache 0.1.0 → 0.2.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
@@ -42,11 +42,11 @@ module.exports = __toCommonJS(index_exports);
42
42
 
43
43
  // src/cache-service.ts
44
44
  var import_ioredis = require("ioredis");
45
+ var import_msgpackr3 = require("msgpackr");
45
46
  var import_crypto3 = __toESM(require("crypto"), 1);
46
47
  var import_os = __toESM(require("os"), 1);
47
48
  var import_fs2 = __toESM(require("fs"), 1);
48
49
  var import_path2 = __toESM(require("path"), 1);
49
- var import_msgpackr3 = require("msgpackr");
50
50
 
51
51
  // src/types.ts
52
52
  var consoleLogger = {
@@ -82,6 +82,8 @@ var IV_POOL_COUNT = 64;
82
82
  var CacheEncryption = class {
83
83
  _key = null;
84
84
  _mode;
85
+ _prevKey = null;
86
+ _prevMode = "aes-256-gcm";
85
87
  // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
86
88
  _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
87
89
  _ivOffset = IV_BYTES * IV_POOL_COUNT;
@@ -144,7 +146,7 @@ var CacheEncryption = class {
144
146
  }
145
147
  return out;
146
148
  }
147
- constructor(keyBase64, logger, mode = "aes-256-gcm") {
149
+ constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
148
150
  this._mode = mode;
149
151
  if (!keyBase64) {
150
152
  if (process.env.NODE_ENV === "production") {
@@ -175,6 +177,15 @@ var CacheEncryption = class {
175
177
  } catch (err) {
176
178
  logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
177
179
  }
180
+ if (previousKeyBase64) {
181
+ try {
182
+ this._prevMode = previousMode ?? mode;
183
+ this._prevKey = Buffer.from(previousKeyBase64, "base64");
184
+ logger.debug("Previous encryption key loaded for key rotation fallback");
185
+ } catch (err) {
186
+ logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
187
+ }
188
+ }
178
189
  }
179
190
  get isEnabled() {
180
191
  return this._key !== null;
@@ -216,19 +227,37 @@ var CacheEncryption = class {
216
227
  /**
217
228
  * Decrypt a Redis value.
218
229
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
230
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
219
231
  */
220
232
  decrypt(value) {
233
+ try {
234
+ return this._decryptWithKey(value, this._key, this._mode);
235
+ } catch (primaryErr) {
236
+ if (this._prevKey) {
237
+ try {
238
+ return this._decryptWithKey(value, this._prevKey, this._prevMode);
239
+ } catch {
240
+ }
241
+ }
242
+ throw primaryErr;
243
+ }
244
+ }
245
+ _decryptWithKey(value, key, mode) {
221
246
  if (value.startsWith(PREFIX_XOR)) {
222
- if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
247
+ if (!key) throw new Error("Cannot decrypt: encryption key is not set");
223
248
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
224
- return this._xorBuffer(masked).toString("utf8");
249
+ const klen = key.length;
250
+ const len = masked.length;
251
+ const out = Buffer.allocUnsafe(len);
252
+ for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
253
+ return out.toString("utf8");
225
254
  }
226
255
  if (value.startsWith(PREFIX_CTR)) {
227
- if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
256
+ if (!key) throw new Error("Cannot decrypt: encryption key is not set");
228
257
  const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
229
258
  const iv2 = combined2.subarray(0, CTR_IV_BYTES);
230
259
  const ct2 = combined2.subarray(CTR_IV_BYTES);
231
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", this._key, iv2);
260
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
232
261
  const plain2 = d2.update(ct2);
233
262
  d2.final();
234
263
  return plain2.toString("utf8");
@@ -236,18 +265,19 @@ var CacheEncryption = class {
236
265
  const is256 = value.startsWith(PREFIX_256);
237
266
  const is128 = value.startsWith(PREFIX_128);
238
267
  if (!is256 && !is128) return value;
239
- if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
268
+ if (!key) throw new Error("Cannot decrypt: encryption key is not set");
240
269
  const prefix = is128 ? PREFIX_128 : PREFIX_256;
241
270
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
242
271
  const combined = Buffer.from(value.slice(prefix.length), "base64");
243
272
  const iv = combined.subarray(0, IV_BYTES);
244
273
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
245
274
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
246
- const d = (0, import_crypto.createDecipheriv)(algo, this._key, iv);
275
+ const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
247
276
  d.setAuthTag(tag);
248
277
  const plain = d.update(ct);
249
278
  d.final();
250
279
  return plain.toString("utf8");
280
+ void mode;
251
281
  }
252
282
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
253
283
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
@@ -287,19 +317,37 @@ var CacheEncryption = class {
287
317
  /**
288
318
  * Decrypt a raw Buffer from disk/snapshot.
289
319
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
320
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
290
321
  */
291
322
  decryptBuffer(data) {
323
+ try {
324
+ return this._decryptBufferWithKey(data, this._key);
325
+ } catch (primaryErr) {
326
+ if (this._prevKey) {
327
+ try {
328
+ return this._decryptBufferWithKey(data, this._prevKey);
329
+ } catch {
330
+ }
331
+ }
332
+ throw primaryErr;
333
+ }
334
+ }
335
+ _decryptBufferWithKey(data, key) {
292
336
  if (data.length < MAGIC_LEN) return data;
293
337
  const magic = data.subarray(0, MAGIC_LEN);
294
338
  if (magic.equals(MAGIC_XOR)) {
295
- if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
296
- return this._xorBuffer(data.subarray(MAGIC_LEN));
339
+ if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
340
+ const raw = data.subarray(MAGIC_LEN);
341
+ const klen = key.length;
342
+ const out = Buffer.allocUnsafe(raw.length);
343
+ for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
344
+ return out;
297
345
  }
298
346
  if (magic.equals(MAGIC_CTR)) {
299
- if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
347
+ if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
300
348
  const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
301
349
  const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
302
- const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", this._key, iv2);
350
+ const d2 = (0, import_crypto.createDecipheriv)("aes-128-ctr", key, iv2);
303
351
  const plain2 = d2.update(ct2);
304
352
  d2.final();
305
353
  return plain2;
@@ -307,12 +355,12 @@ var CacheEncryption = class {
307
355
  const is256 = magic.equals(MAGIC_256);
308
356
  const is128 = magic.equals(MAGIC_128);
309
357
  if (!is256 && !is128) return data;
310
- if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
358
+ if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
311
359
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
312
360
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
313
361
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
314
362
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
315
- const d = (0, import_crypto.createDecipheriv)(algo, this._key, iv);
363
+ const d = (0, import_crypto.createDecipheriv)(algo, key, iv);
316
364
  d.setAuthTag(tag);
317
365
  const plain = d.update(ct);
318
366
  d.final();
@@ -504,6 +552,7 @@ var SmartMemoryCache = class {
504
552
  bloomChecks = 0;
505
553
  bloomFalsePos = 0;
506
554
  compressions = 0;
555
+ categoryHits = /* @__PURE__ */ new Map();
507
556
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
508
557
  _bloomDirtyCount = 0;
509
558
  constructor(opts, existing) {
@@ -544,7 +593,7 @@ var SmartMemoryCache = class {
544
593
  getCategoryLimit(cat) {
545
594
  return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
546
595
  }
547
- _delete(key) {
596
+ _delete(key, reason = "manual") {
548
597
  const entry = this.cache.get(key);
549
598
  if (!entry) return false;
550
599
  const cat = this.getCategory(key);
@@ -553,7 +602,14 @@ var SmartMemoryCache = class {
553
602
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
554
603
  this.categoryKeys.get(cat)?.delete(key);
555
604
  this._bloomDirtyCount++;
556
- return this.cache.delete(key);
605
+ const deleted = this.cache.delete(key);
606
+ if (deleted && this.opts.onEviction) {
607
+ try {
608
+ this.opts.onEviction(key, reason);
609
+ } catch {
610
+ }
611
+ }
612
+ return deleted;
557
613
  }
558
614
  ensureCapacity(category, neededSize) {
559
615
  const lim = this.getCategoryLimit(category);
@@ -635,7 +691,7 @@ var SmartMemoryCache = class {
635
691
  for (const { key } of pool.slice(0, EVICT)) {
636
692
  const entry = this.cache.get(key);
637
693
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
638
- this._delete(key);
694
+ this._delete(key, "capacity");
639
695
  }
640
696
  }
641
697
  // ── Public API ────────────────────────────────────────────────────────────
@@ -649,12 +705,14 @@ var SmartMemoryCache = class {
649
705
  }
650
706
  const now = Date.now();
651
707
  if (entry.expiresAt < now) {
652
- this._delete(key);
708
+ this._delete(key, "ttl");
653
709
  return null;
654
710
  }
655
711
  entry.hits++;
656
712
  entry.lastAccess = now;
657
- const value = (0, import_msgpackr.unpack)(entry.data);
713
+ const cat = this.getCategory(key);
714
+ this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
715
+ const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
658
716
  const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
659
717
  return { value, isStale };
660
718
  }
@@ -677,7 +735,7 @@ var SmartMemoryCache = class {
677
735
  }
678
736
  this.ensureCapacity(cat, size);
679
737
  const now = Date.now();
680
- this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
738
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
681
739
  this.bloom.add(key);
682
740
  this.maybeRebuildBloom();
683
741
  this.totalSize += size;
@@ -691,7 +749,7 @@ var SmartMemoryCache = class {
691
749
  ks.add(key);
692
750
  }
693
751
  delete(key) {
694
- const deleted = this._delete(key);
752
+ const deleted = this._delete(key, "manual");
695
753
  if (deleted) this.maybeRebuildBloom();
696
754
  return deleted;
697
755
  }
@@ -704,10 +762,77 @@ var SmartMemoryCache = class {
704
762
  }
705
763
  deletePattern(pattern) {
706
764
  let n = 0;
707
- for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
765
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
708
766
  if (n > 0) this.maybeRebuildBloom();
709
767
  return n;
710
768
  }
769
+ /** Flush all entries, or only those whose key starts with `prefix`. */
770
+ clear(prefix) {
771
+ if (prefix) {
772
+ const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
773
+ return this.deletePattern(pattern);
774
+ }
775
+ const count = this.cache.size;
776
+ this.cache.clear();
777
+ this.totalSize = 0;
778
+ this.categoryCount.clear();
779
+ this.categorySize.clear();
780
+ this.categoryKeys.clear();
781
+ this.categoryHits.clear();
782
+ this.bloom.reset();
783
+ this._bloomDirtyCount = 0;
784
+ return count;
785
+ }
786
+ /**
787
+ * Evict entries that violate current category or global limits.
788
+ * Returns the number of entries evicted.
789
+ */
790
+ rebalance() {
791
+ const now = Date.now();
792
+ let evicted = 0;
793
+ for (const [cat, limit] of Object.entries(this.opts.categories)) {
794
+ const catKeys = this.categoryKeys.get(cat);
795
+ if (!catKeys || catKeys.size === 0) continue;
796
+ let catCnt = this.categoryCount.get(cat) ?? 0;
797
+ let catSz = this.categorySize.get(cat) ?? 0;
798
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
799
+ const candidates = [];
800
+ for (const key of catKeys) {
801
+ const entry = this.cache.get(key);
802
+ if (!entry) continue;
803
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
804
+ candidates.push({ key, score: this.score(entry, 0, now) });
805
+ }
806
+ candidates.sort((a, b) => a.score - b.score);
807
+ for (const { key } of candidates) {
808
+ catCnt = this.categoryCount.get(cat) ?? 0;
809
+ catSz = this.categorySize.get(cat) ?? 0;
810
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
811
+ const entry = this.cache.get(key);
812
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
813
+ this._delete(key, "rebalance");
814
+ evicted++;
815
+ }
816
+ }
817
+ while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
818
+ const before = this.cache.size;
819
+ this.smartEvict("default", false);
820
+ if (this.cache.size >= before) break;
821
+ evicted += before - this.cache.size;
822
+ }
823
+ if (evicted > 0) this.maybeRebuildBloom();
824
+ return evicted;
825
+ }
826
+ /**
827
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
828
+ * Only reflects L1 state — does not query Redis or disk.
829
+ */
830
+ ttl(key) {
831
+ const entry = this.cache.get(key);
832
+ if (!entry) return null;
833
+ const remaining = entry.expiresAt - Date.now();
834
+ return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
835
+ }
711
836
  /**
712
837
  * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
713
838
  * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
@@ -730,7 +855,7 @@ var SmartMemoryCache = class {
730
855
  for (const { key } of candidates.slice(0, count)) {
731
856
  const entry = this.cache.get(key);
732
857
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
733
- this._delete(key);
858
+ this._delete(key, "oom");
734
859
  evicted++;
735
860
  }
736
861
  return evicted;
@@ -739,7 +864,7 @@ var SmartMemoryCache = class {
739
864
  const now = Date.now();
740
865
  let cleaned = 0;
741
866
  for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
742
- this._delete(key);
867
+ this._delete(key, "ttl");
743
868
  cleaned++;
744
869
  }
745
870
  if (cleaned > 0) {
@@ -769,7 +894,8 @@ var SmartMemoryCache = class {
769
894
  if (this.cache.has(key)) continue;
770
895
  const rawData = entry.data;
771
896
  const data = !entry.isCompressed ? (0, import_msgpackr.pack)(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
772
- this.cache.set(key, { ...entry, data, isCompressed: true });
897
+ const value = (0, import_msgpackr.unpack)(data);
898
+ this.cache.set(key, { ...entry, data, value, isCompressed: true });
773
899
  this.bloom.add(key);
774
900
  loaded++;
775
901
  }
@@ -785,9 +911,12 @@ var SmartMemoryCache = class {
785
911
  }
786
912
  getStats() {
787
913
  const categories = {};
788
- for (const [cat, cnt] of this.categoryCount) categories[cat] = cnt;
914
+ for (const [cat, cnt] of this.categoryCount) {
915
+ categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
916
+ }
789
917
  return {
790
918
  entries: this.cache.size,
919
+ sizeBytes: this.totalSize,
791
920
  sizeKB: Math.round(this.totalSize / 1024),
792
921
  categories,
793
922
  bloom: {
@@ -803,6 +932,56 @@ var SmartMemoryCache = class {
803
932
  }
804
933
  };
805
934
  }
935
+ /**
936
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
937
+ * Does NOT count as a hit or perform SWR logic.
938
+ */
939
+ getEntry(key) {
940
+ const entry = this.cache.get(key);
941
+ if (!entry) return void 0;
942
+ if (entry.expiresAt <= Date.now()) return void 0;
943
+ return entry;
944
+ }
945
+ /**
946
+ * Return true if the key exists in L1 and has not expired.
947
+ * Uses the bloom filter as a fast negative check.
948
+ */
949
+ has(key) {
950
+ if (!this.bloom.mightContain(key)) return false;
951
+ const entry = this.cache.get(key);
952
+ if (!entry) return false;
953
+ if (entry.expiresAt <= Date.now()) {
954
+ this._delete(key, "ttl");
955
+ return false;
956
+ }
957
+ return true;
958
+ }
959
+ /**
960
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
961
+ * @param newTtlMs - New TTL from now, in milliseconds.
962
+ */
963
+ touch(key, newTtlMs) {
964
+ const entry = this.cache.get(key);
965
+ if (!entry) return false;
966
+ const now = Date.now();
967
+ if (entry.expiresAt <= now) {
968
+ this._delete(key, "ttl");
969
+ return false;
970
+ }
971
+ entry.expiresAt = now + newTtlMs;
972
+ return true;
973
+ }
974
+ /**
975
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
976
+ * Returns `false` if the key is absent or already expired.
977
+ */
978
+ bumpExpiry(key, additionalMs) {
979
+ const entry = this.cache.get(key);
980
+ if (!entry) return false;
981
+ if (entry.expiresAt <= Date.now()) return false;
982
+ entry.expiresAt += additionalMs;
983
+ return true;
984
+ }
806
985
  bloomMightContain(key) {
807
986
  return this.bloom.mightContain(key);
808
987
  }
@@ -1066,6 +1245,23 @@ var DiskTier = class {
1066
1245
  }
1067
1246
  return purged;
1068
1247
  }
1248
+ /** Delete every file in the disk cache. Returns the count deleted. */
1249
+ clear() {
1250
+ this.ensureDir();
1251
+ if (!this.dirReady) return 0;
1252
+ let cleared = 0;
1253
+ for (const filePath of this.walkCacheFiles()) {
1254
+ try {
1255
+ const stat = import_fs.default.statSync(filePath);
1256
+ import_fs.default.unlinkSync(filePath);
1257
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1258
+ this.fileCount = Math.max(0, this.fileCount - 1);
1259
+ cleared++;
1260
+ } catch {
1261
+ }
1262
+ }
1263
+ return cleared;
1264
+ }
1069
1265
  get stats() {
1070
1266
  return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1071
1267
  }
@@ -1098,6 +1294,9 @@ var CacheService = class _CacheService {
1098
1294
  _redisDisabled;
1099
1295
  inflight = /* @__PURE__ */ new Map();
1100
1296
  revalidating = /* @__PURE__ */ new Set();
1297
+ _l1Counters = /* @__PURE__ */ new Map();
1298
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
1299
+ tagIndex = /* @__PURE__ */ new Map();
1101
1300
  redis = null;
1102
1301
  redisConnecting = null;
1103
1302
  snapshotLoaded = false;
@@ -1131,7 +1330,13 @@ var CacheService = class _CacheService {
1131
1330
  this.logger = logger;
1132
1331
  const ns = options.namespace?.trim() ?? "";
1133
1332
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
1134
- this.enc = new CacheEncryption(encKeyRaw, logger, options.encryptionMode);
1333
+ this.enc = new CacheEncryption(
1334
+ encKeyRaw,
1335
+ logger,
1336
+ options.encryptionMode,
1337
+ options.previousEncryptionKey,
1338
+ options.previousEncryptionMode
1339
+ );
1135
1340
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
1136
1341
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
1137
1342
  this.opts = {
@@ -1165,7 +1370,10 @@ var CacheService = class _CacheService {
1165
1370
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
1166
1371
  oomEvictPercent: options.oomEvictPercent ?? 0.2,
1167
1372
  onMetrics: options.onMetrics,
1168
- metricsIntervalMs: options.metricsIntervalMs ?? 6e4
1373
+ metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
1374
+ staleIfError: options.staleIfError ?? 0,
1375
+ l2WriteMode: options.l2WriteMode ?? "read-write",
1376
+ instanceName: options.instanceName ?? ""
1169
1377
  };
1170
1378
  this.disk = new DiskTier({
1171
1379
  dir: this.opts.diskCacheDir,
@@ -1184,6 +1392,7 @@ var CacheService = class _CacheService {
1184
1392
  diskSpill: (key, entry) => {
1185
1393
  void this.disk.save(key, entry);
1186
1394
  },
1395
+ onEviction: options.onEviction,
1187
1396
  logger
1188
1397
  });
1189
1398
  if (!this.snapshotLoaded) {
@@ -1250,6 +1459,17 @@ var CacheService = class _CacheService {
1250
1459
  if (!g[key]) g[key] = new _CacheService(options);
1251
1460
  return g[key];
1252
1461
  }
1462
+ /**
1463
+ * Async factory — accepts a Promise that resolves to CacheOptions.
1464
+ * Useful when config is fetched from a secret store at startup.
1465
+ *
1466
+ * @example
1467
+ * const cache = await CacheService.createAsync(fetchSecrets());
1468
+ */
1469
+ static async createAsync(options) {
1470
+ const resolved = await options;
1471
+ return _CacheService.create(resolved);
1472
+ }
1253
1473
  /** Replace the singleton (useful in tests). */
1254
1474
  static reset(options) {
1255
1475
  const g = globalThis;
@@ -1335,43 +1555,49 @@ var CacheService = class _CacheService {
1335
1555
  if (this.redis?.status === "ready") return this.redis;
1336
1556
  if (this.redisConnecting) return this.redisConnecting;
1337
1557
  this.redisConnecting = (async () => {
1338
- const client = new import_ioredis.Redis({
1339
- host: this.opts.redisHost,
1340
- port: this.opts.redisPort,
1341
- tls: this.opts.redisTls ? {} : void 0,
1342
- connectTimeout: 1e4,
1343
- lazyConnect: false,
1344
- maxRetriesPerRequest: 3,
1345
- enableAutoPipelining: true,
1346
- keepAlive: 3e4,
1347
- family: 4,
1348
- retryStrategy: (times) => Math.min(times * 50, 2e3)
1349
- });
1350
- client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
1351
- client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
1352
- client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
1353
- await new Promise((resolve, reject) => {
1354
- client.once("ready", resolve);
1355
- client.once("error", reject);
1356
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1357
- });
1358
- this.redis = client;
1359
- this.redisConnecting = null;
1360
- return client;
1558
+ try {
1559
+ const client = new import_ioredis.Redis({
1560
+ host: this.opts.redisHost,
1561
+ port: this.opts.redisPort,
1562
+ tls: this.opts.redisTls ? {} : void 0,
1563
+ connectTimeout: 1e4,
1564
+ lazyConnect: false,
1565
+ maxRetriesPerRequest: 3,
1566
+ enableAutoPipelining: true,
1567
+ keepAlive: 3e4,
1568
+ family: 4,
1569
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
1570
+ });
1571
+ client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
1572
+ client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
1573
+ client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
1574
+ await new Promise((resolve, reject) => {
1575
+ client.once("ready", resolve);
1576
+ client.once("error", reject);
1577
+ setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1578
+ });
1579
+ this.redis = client;
1580
+ this.redisConnecting = null;
1581
+ return client;
1582
+ } catch (err) {
1583
+ this.redisConnecting = null;
1584
+ throw err;
1585
+ }
1361
1586
  })();
1362
1587
  return this.redisConnecting;
1363
1588
  }
1364
1589
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
1365
- writeSnapshot() {
1590
+ writeSnapshot(altPath) {
1366
1591
  try {
1367
1592
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
1368
1593
  if (entries.length === 0) return;
1369
1594
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
1370
1595
  const packed = (0, import_msgpackr3.pack)(payload);
1371
1596
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
1372
- import_fs2.default.writeFileSync(this.opts.snapshotPath, final, { mode: 384 });
1597
+ const dest = altPath ?? this.opts.snapshotPath;
1598
+ import_fs2.default.writeFileSync(dest, final, { mode: 384 });
1373
1599
  this.logger.info("Cache snapshot written", {
1374
- path: this.opts.snapshotPath,
1600
+ path: dest,
1375
1601
  entries: entries.length,
1376
1602
  sizeKB: Math.round(final.length / 1024),
1377
1603
  encrypted: this.enc.isEnabled
@@ -1534,7 +1760,7 @@ var CacheService = class _CacheService {
1534
1760
  const data = await fetchFn();
1535
1761
  const staleAt = Date.now() + ttlMs;
1536
1762
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
1537
- if (!this._redisDisabled) {
1763
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1538
1764
  try {
1539
1765
  const client = await this.getRedis();
1540
1766
  const s = JSON.stringify(data);
@@ -1545,20 +1771,53 @@ var CacheService = class _CacheService {
1545
1771
  }
1546
1772
  this.logger.debug("SWR: revalidation complete", { cacheKey });
1547
1773
  } catch (err) {
1548
- this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
1774
+ if (this.opts.staleIfError > 0) {
1775
+ const additionalMs = this.opts.staleIfError * 1e3;
1776
+ this.l1.bumpExpiry(cacheKey, additionalMs);
1777
+ this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
1778
+ cacheKey,
1779
+ staleIfErrorSecs: this.opts.staleIfError
1780
+ });
1781
+ } else {
1782
+ this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
1783
+ }
1549
1784
  } finally {
1550
1785
  this.revalidating.delete(cacheKey);
1551
1786
  }
1552
1787
  }
1553
1788
  // ── Explicit set / delete ─────────────────────────────────────────────────
1554
1789
  /** Explicitly write a value into L1 (+ L2 in production). */
1555
- async set(cacheKey, data, ttlSeconds = 300, priority) {
1790
+ async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
1556
1791
  const ttlMs = ttlSeconds * 1e3;
1557
1792
  const p = priority ?? inferPriority(cacheKey);
1558
1793
  const k = this.nk(cacheKey);
1559
1794
  this.counters.sets++;
1560
1795
  this.l1.set(k, data, ttlMs, p);
1561
- if (!this._redisDisabled) {
1796
+ if (opts?.tags?.length) {
1797
+ for (const tag of opts.tags) {
1798
+ const tagKey = this.nk(`_tag_:${tag}`);
1799
+ let members = this.tagIndex.get(tagKey);
1800
+ if (!members) {
1801
+ members = /* @__PURE__ */ new Set();
1802
+ this.tagIndex.set(tagKey, members);
1803
+ }
1804
+ members.add(k);
1805
+ }
1806
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1807
+ try {
1808
+ const client = await this.getRedis();
1809
+ const pl = client.pipeline();
1810
+ for (const tag of opts.tags) {
1811
+ const tagKey = this.nk(`_tag_:${tag}`);
1812
+ pl.sadd(tagKey, k);
1813
+ pl.expire(tagKey, ttlSeconds + 3600);
1814
+ }
1815
+ await pl.exec();
1816
+ } catch {
1817
+ }
1818
+ }
1819
+ }
1820
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1562
1821
  try {
1563
1822
  const client = await this.getRedis();
1564
1823
  const s = JSON.stringify(data);
@@ -1587,7 +1846,7 @@ var CacheService = class _CacheService {
1587
1846
  this.l1.delete(k);
1588
1847
  this.disk.delete(k);
1589
1848
  }
1590
- if (!this._redisDisabled) {
1849
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1591
1850
  try {
1592
1851
  const client = await this.getRedis();
1593
1852
  if (isPattern) {
@@ -1614,8 +1873,18 @@ var CacheService = class _CacheService {
1614
1873
  * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
1615
1874
  */
1616
1875
  async increment(cacheKey, ttlSeconds) {
1617
- if (this._redisDisabled) return 0;
1618
1876
  const k = this.nk(cacheKey);
1877
+ if (this._redisDisabled) {
1878
+ const now = Date.now();
1879
+ const ttlMs = (ttlSeconds ?? 60) * 1e3;
1880
+ const entry = this._l1Counters.get(k);
1881
+ if (entry && entry.expiresAt > now) {
1882
+ entry.value++;
1883
+ return entry.value;
1884
+ }
1885
+ this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
1886
+ return 1;
1887
+ }
1619
1888
  try {
1620
1889
  const client = await this.getRedis();
1621
1890
  const count = await client.incr(k);
@@ -1626,7 +1895,225 @@ var CacheService = class _CacheService {
1626
1895
  return 0;
1627
1896
  }
1628
1897
  }
1629
- // ── Stats ─────────────────────────────────────────────────────────────────
1898
+ // ── Clear / Rebalance / TTL ────────────────────────────────────────────────
1899
+ /**
1900
+ * Flush all cached entries, or only those whose key starts with `prefix`.
1901
+ *
1902
+ * @example
1903
+ * await cache.clear(); // flush everything
1904
+ * await cache.clear('user:abc'); // flush all keys for one user
1905
+ */
1906
+ async clear(prefix) {
1907
+ this.counters.deletes++;
1908
+ const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
1909
+ if (k) {
1910
+ this.l1.deletePattern(k);
1911
+ } else {
1912
+ this.l1.clear();
1913
+ this.disk.clear();
1914
+ this._l1Counters.clear();
1915
+ this.tagIndex.clear();
1916
+ }
1917
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1918
+ try {
1919
+ const client = await this.getRedis();
1920
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
1921
+ const stream = client.scanStream({ match: pattern, count: 100 });
1922
+ const keys = [];
1923
+ await new Promise((resolve, reject) => {
1924
+ stream.on("data", (chunk) => keys.push(...chunk));
1925
+ stream.on("end", resolve);
1926
+ stream.on("error", reject);
1927
+ });
1928
+ if (keys.length > 0) await client.del(...keys);
1929
+ } catch (err) {
1930
+ this.logger.debug("clear: Redis unavailable", { error: err.message });
1931
+ }
1932
+ }
1933
+ void this.publishInvalidation(
1934
+ "del-glob",
1935
+ k ?? (this._namespace ? `${this._namespace}:*` : "*")
1936
+ );
1937
+ }
1938
+ /**
1939
+ * Evict L1 entries that violate the current category or global capacity limits.
1940
+ * Useful after a write burst or after adding stricter `categoryLimits`.
1941
+ * Returns the number of entries evicted.
1942
+ */
1943
+ rebalance() {
1944
+ return this.l1.rebalance();
1945
+ }
1946
+ /**
1947
+ * Return the remaining TTL in seconds for a key currently in L1.
1948
+ * Returns null if the key is absent from L1 or has already expired.
1949
+ * Only reflects L1 state — does not query Redis or disk.
1950
+ */
1951
+ ttl(cacheKey) {
1952
+ return this.l1.ttl(this.nk(cacheKey));
1953
+ }
1954
+ /**
1955
+ * Return true if the key exists in L1 and has not expired.
1956
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
1957
+ */
1958
+ has(cacheKey) {
1959
+ return this.l1.has(this.nk(cacheKey));
1960
+ }
1961
+ /**
1962
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
1963
+ * Returns `false` if the key is absent or already expired.
1964
+ *
1965
+ * @param newTtlSeconds - The new TTL from now, in seconds.
1966
+ */
1967
+ async touch(cacheKey, newTtlSeconds) {
1968
+ const k = this.nk(cacheKey);
1969
+ const hit = this.l1.touch(k, newTtlSeconds * 1e3);
1970
+ if (hit && !this._redisDisabled) {
1971
+ try {
1972
+ const client = await this.getRedis();
1973
+ void client.expire(k, newTtlSeconds);
1974
+ } catch {
1975
+ }
1976
+ }
1977
+ return hit;
1978
+ }
1979
+ /**
1980
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
1981
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
1982
+ *
1983
+ * @example
1984
+ * const fresh = cache.getIfFresh('user:123');
1985
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
1986
+ */
1987
+ getIfFresh(cacheKey) {
1988
+ const k = this.nk(cacheKey);
1989
+ const entry = this.l1.getEntry(k);
1990
+ if (!entry) return null;
1991
+ const now = Date.now();
1992
+ if (entry.expiresAt <= now) return null;
1993
+ if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
1994
+ return entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
1995
+ }
1996
+ /**
1997
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
1998
+ * Preserves input ordering. Uses inflight coalescing per key.
1999
+ *
2000
+ * @param keys - Array of cache keys.
2001
+ * @param fetchFn - Called with only the keys that missed L1.
2002
+ * @param ttl - TTL in seconds for newly fetched values.
2003
+ */
2004
+ async mget(keys, fetchFn, ttl = 300, priority) {
2005
+ const result = new Array(keys.length);
2006
+ const missIndexes = [];
2007
+ const missKeys = [];
2008
+ for (let i = 0; i < keys.length; i++) {
2009
+ const entry = this.l1.getEntry(this.nk(keys[i]));
2010
+ if (entry && entry.expiresAt > Date.now()) {
2011
+ result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
2012
+ this.counters.l1Hits++;
2013
+ } else {
2014
+ missIndexes.push(i);
2015
+ missKeys.push(keys[i]);
2016
+ }
2017
+ }
2018
+ if (missKeys.length > 0) {
2019
+ const fetched = await fetchFn(missKeys);
2020
+ for (let j = 0; j < missKeys.length; j++) {
2021
+ const v = fetched[missKeys[j]];
2022
+ result[missIndexes[j]] = v;
2023
+ if (v !== void 0) {
2024
+ await this.set(missKeys[j], v, ttl, priority);
2025
+ }
2026
+ }
2027
+ }
2028
+ return result;
2029
+ }
2030
+ /**
2031
+ * Invalidate all keys associated with a tag.
2032
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
2033
+ *
2034
+ * @example
2035
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
2036
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
2037
+ */
2038
+ async invalidateTag(tag) {
2039
+ const tagKey = this.nk(`_tag_:${tag}`);
2040
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
2041
+ for (const k of members) {
2042
+ this.l1.delete(k);
2043
+ this.disk.delete(k);
2044
+ }
2045
+ this.tagIndex.delete(tagKey);
2046
+ if (!this._redisDisabled) {
2047
+ try {
2048
+ const client = await this.getRedis();
2049
+ const redisMembers = await client.smembers(tagKey);
2050
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
2051
+ if (toDelete.length > 0) {
2052
+ await client.del(...toDelete, tagKey);
2053
+ } else {
2054
+ await client.del(tagKey);
2055
+ }
2056
+ } catch (err) {
2057
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
2058
+ }
2059
+ }
2060
+ }
2061
+ /**
2062
+ * Measure L1 / disk / Redis latency.
2063
+ * Useful for health checks and dashboards.
2064
+ *
2065
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
2066
+ * `l2` is `null` when Redis is disabled.
2067
+ */
2068
+ async ping() {
2069
+ const t0 = Date.now();
2070
+ this.l1.has("__ping__");
2071
+ const l1 = Date.now() - t0;
2072
+ const t1 = Date.now();
2073
+ void this.disk.stats;
2074
+ const disk = Date.now() - t1;
2075
+ let l2 = null;
2076
+ if (!this._redisDisabled) {
2077
+ try {
2078
+ const client = await this.getRedis();
2079
+ const t2 = Date.now();
2080
+ await client.ping();
2081
+ l2 = Date.now() - t2;
2082
+ } catch {
2083
+ l2 = null;
2084
+ }
2085
+ }
2086
+ return { l1, disk, l2 };
2087
+ }
2088
+ /**
2089
+ * Export all live L1 entries to Redis via a single pipeline.
2090
+ * Useful for warming a new Redis instance or for zero-downtime failover.
2091
+ * Returns the number of keys written.
2092
+ */
2093
+ async drainToL2() {
2094
+ if (this._redisDisabled) return 0;
2095
+ try {
2096
+ const client = await this.getRedis();
2097
+ const entries = this.l1.exportEntries([]);
2098
+ const now = Date.now();
2099
+ if (entries.length === 0) return 0;
2100
+ const pl = client.pipeline();
2101
+ for (const { key, entry } of entries) {
2102
+ const remainingMs = entry.expiresAt - now;
2103
+ if (remainingMs <= 0) continue;
2104
+ const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
2105
+ const s = JSON.stringify(entry.value);
2106
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2107
+ pl.setex(key, ttlSecs, stored);
2108
+ }
2109
+ await pl.exec();
2110
+ return entries.length;
2111
+ } catch (err) {
2112
+ this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
2113
+ return 0;
2114
+ }
2115
+ }
2116
+ // ── Stats ─────────────────────────────────────────────────────────────
1630
2117
  stats() {
1631
2118
  return {
1632
2119
  l1: this.l1.getStats(),
@@ -1693,8 +2180,11 @@ var CacheService = class _CacheService {
1693
2180
  * @param m - Snapshot returned by `cache.metrics()`
1694
2181
  * @param prefix - Metric name prefix. Default: `"tricache"`
1695
2182
  */
1696
- static toPrometheusText(m, prefix = "tricache") {
1697
- const lbl = m.namespace ? `{namespace="${m.namespace}"}` : "";
2183
+ static toPrometheusText(m, prefix = "tricache", instanceName) {
2184
+ const parts = [];
2185
+ if (m.namespace) parts.push(`namespace="${m.namespace}"`);
2186
+ if (instanceName) parts.push(`instance="${instanceName}"`);
2187
+ const lbl = parts.length ? `{${parts.join(",")}}` : "";
1698
2188
  const lines = [];
1699
2189
  const counter = (name, val, help) => {
1700
2190
  lines.push(`# HELP ${prefix}_${name}_total ${help}`);