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.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // src/cache-service.ts
2
2
  import { Redis as RedisClient } from "ioredis";
3
+ import { pack as pack3, unpack as unpack3 } from "msgpackr";
3
4
  import crypto2 from "crypto";
4
5
  import os from "os";
5
6
  import fs2 from "fs";
6
7
  import path2 from "path";
7
- import { pack as pack3, unpack as unpack3 } from "msgpackr";
8
8
 
9
9
  // src/types.ts
10
10
  var consoleLogger = {
@@ -40,6 +40,8 @@ var IV_POOL_COUNT = 64;
40
40
  var CacheEncryption = class {
41
41
  _key = null;
42
42
  _mode;
43
+ _prevKey = null;
44
+ _prevMode = "aes-256-gcm";
43
45
  // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
44
46
  _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
45
47
  _ivOffset = IV_BYTES * IV_POOL_COUNT;
@@ -102,7 +104,7 @@ var CacheEncryption = class {
102
104
  }
103
105
  return out;
104
106
  }
105
- constructor(keyBase64, logger, mode = "aes-256-gcm") {
107
+ constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
106
108
  this._mode = mode;
107
109
  if (!keyBase64) {
108
110
  if (process.env.NODE_ENV === "production") {
@@ -133,6 +135,15 @@ var CacheEncryption = class {
133
135
  } catch (err) {
134
136
  logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
135
137
  }
138
+ if (previousKeyBase64) {
139
+ try {
140
+ this._prevMode = previousMode ?? mode;
141
+ this._prevKey = Buffer.from(previousKeyBase64, "base64");
142
+ logger.debug("Previous encryption key loaded for key rotation fallback");
143
+ } catch (err) {
144
+ logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
145
+ }
146
+ }
136
147
  }
137
148
  get isEnabled() {
138
149
  return this._key !== null;
@@ -174,19 +185,37 @@ var CacheEncryption = class {
174
185
  /**
175
186
  * Decrypt a Redis value.
176
187
  * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
188
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
177
189
  */
178
190
  decrypt(value) {
191
+ try {
192
+ return this._decryptWithKey(value, this._key, this._mode);
193
+ } catch (primaryErr) {
194
+ if (this._prevKey) {
195
+ try {
196
+ return this._decryptWithKey(value, this._prevKey, this._prevMode);
197
+ } catch {
198
+ }
199
+ }
200
+ throw primaryErr;
201
+ }
202
+ }
203
+ _decryptWithKey(value, key, mode) {
179
204
  if (value.startsWith(PREFIX_XOR)) {
180
- if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
205
+ if (!key) throw new Error("Cannot decrypt: encryption key is not set");
181
206
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
182
- return this._xorBuffer(masked).toString("utf8");
207
+ const klen = key.length;
208
+ const len = masked.length;
209
+ const out = Buffer.allocUnsafe(len);
210
+ for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
211
+ return out.toString("utf8");
183
212
  }
184
213
  if (value.startsWith(PREFIX_CTR)) {
185
- if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
214
+ if (!key) throw new Error("Cannot decrypt: encryption key is not set");
186
215
  const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
187
216
  const iv2 = combined2.subarray(0, CTR_IV_BYTES);
188
217
  const ct2 = combined2.subarray(CTR_IV_BYTES);
189
- const d2 = createDecipheriv("aes-128-ctr", this._key, iv2);
218
+ const d2 = createDecipheriv("aes-128-ctr", key, iv2);
190
219
  const plain2 = d2.update(ct2);
191
220
  d2.final();
192
221
  return plain2.toString("utf8");
@@ -194,18 +223,19 @@ var CacheEncryption = class {
194
223
  const is256 = value.startsWith(PREFIX_256);
195
224
  const is128 = value.startsWith(PREFIX_128);
196
225
  if (!is256 && !is128) return value;
197
- if (!this._key) throw new Error("Cannot decrypt: encryption key is not set");
226
+ if (!key) throw new Error("Cannot decrypt: encryption key is not set");
198
227
  const prefix = is128 ? PREFIX_128 : PREFIX_256;
199
228
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
200
229
  const combined = Buffer.from(value.slice(prefix.length), "base64");
201
230
  const iv = combined.subarray(0, IV_BYTES);
202
231
  const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
203
232
  const ct = combined.subarray(IV_BYTES + TAG_BYTES);
204
- const d = createDecipheriv(algo, this._key, iv);
233
+ const d = createDecipheriv(algo, key, iv);
205
234
  d.setAuthTag(tag);
206
235
  const plain = d.update(ct);
207
236
  d.final();
208
237
  return plain.toString("utf8");
238
+ void mode;
209
239
  }
210
240
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
211
241
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
@@ -245,19 +275,37 @@ var CacheEncryption = class {
245
275
  /**
246
276
  * Decrypt a raw Buffer from disk/snapshot.
247
277
  * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
278
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
248
279
  */
249
280
  decryptBuffer(data) {
281
+ try {
282
+ return this._decryptBufferWithKey(data, this._key);
283
+ } catch (primaryErr) {
284
+ if (this._prevKey) {
285
+ try {
286
+ return this._decryptBufferWithKey(data, this._prevKey);
287
+ } catch {
288
+ }
289
+ }
290
+ throw primaryErr;
291
+ }
292
+ }
293
+ _decryptBufferWithKey(data, key) {
250
294
  if (data.length < MAGIC_LEN) return data;
251
295
  const magic = data.subarray(0, MAGIC_LEN);
252
296
  if (magic.equals(MAGIC_XOR)) {
253
- if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
254
- return this._xorBuffer(data.subarray(MAGIC_LEN));
297
+ if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
298
+ const raw = data.subarray(MAGIC_LEN);
299
+ const klen = key.length;
300
+ const out = Buffer.allocUnsafe(raw.length);
301
+ for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
302
+ return out;
255
303
  }
256
304
  if (magic.equals(MAGIC_CTR)) {
257
- if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
305
+ if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
258
306
  const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
259
307
  const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
260
- const d2 = createDecipheriv("aes-128-ctr", this._key, iv2);
308
+ const d2 = createDecipheriv("aes-128-ctr", key, iv2);
261
309
  const plain2 = d2.update(ct2);
262
310
  d2.final();
263
311
  return plain2;
@@ -265,12 +313,12 @@ var CacheEncryption = class {
265
313
  const is256 = magic.equals(MAGIC_256);
266
314
  const is128 = magic.equals(MAGIC_128);
267
315
  if (!is256 && !is128) return data;
268
- if (!this._key) throw new Error("Cannot decrypt buffer: encryption key is not set");
316
+ if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
269
317
  const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
270
318
  const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
271
319
  const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
272
320
  const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
273
- const d = createDecipheriv(algo, this._key, iv);
321
+ const d = createDecipheriv(algo, key, iv);
274
322
  d.setAuthTag(tag);
275
323
  const plain = d.update(ct);
276
324
  d.final();
@@ -462,6 +510,7 @@ var SmartMemoryCache = class {
462
510
  bloomChecks = 0;
463
511
  bloomFalsePos = 0;
464
512
  compressions = 0;
513
+ categoryHits = /* @__PURE__ */ new Map();
465
514
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
466
515
  _bloomDirtyCount = 0;
467
516
  constructor(opts, existing) {
@@ -502,7 +551,7 @@ var SmartMemoryCache = class {
502
551
  getCategoryLimit(cat) {
503
552
  return this.opts.categories[cat] ?? this.opts.categories["default"] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
504
553
  }
505
- _delete(key) {
554
+ _delete(key, reason = "manual") {
506
555
  const entry = this.cache.get(key);
507
556
  if (!entry) return false;
508
557
  const cat = this.getCategory(key);
@@ -511,7 +560,14 @@ var SmartMemoryCache = class {
511
560
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
512
561
  this.categoryKeys.get(cat)?.delete(key);
513
562
  this._bloomDirtyCount++;
514
- return this.cache.delete(key);
563
+ const deleted = this.cache.delete(key);
564
+ if (deleted && this.opts.onEviction) {
565
+ try {
566
+ this.opts.onEviction(key, reason);
567
+ } catch {
568
+ }
569
+ }
570
+ return deleted;
515
571
  }
516
572
  ensureCapacity(category, neededSize) {
517
573
  const lim = this.getCategoryLimit(category);
@@ -593,7 +649,7 @@ var SmartMemoryCache = class {
593
649
  for (const { key } of pool.slice(0, EVICT)) {
594
650
  const entry = this.cache.get(key);
595
651
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
596
- this._delete(key);
652
+ this._delete(key, "capacity");
597
653
  }
598
654
  }
599
655
  // ── Public API ────────────────────────────────────────────────────────────
@@ -607,12 +663,14 @@ var SmartMemoryCache = class {
607
663
  }
608
664
  const now = Date.now();
609
665
  if (entry.expiresAt < now) {
610
- this._delete(key);
666
+ this._delete(key, "ttl");
611
667
  return null;
612
668
  }
613
669
  entry.hits++;
614
670
  entry.lastAccess = now;
615
- const value = unpack(entry.data);
671
+ const cat = this.getCategory(key);
672
+ this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
673
+ const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
616
674
  const isStale = entry.staleAt !== void 0 && now > entry.staleAt;
617
675
  return { value, isStale };
618
676
  }
@@ -635,7 +693,7 @@ var SmartMemoryCache = class {
635
693
  }
636
694
  this.ensureCapacity(cat, size);
637
695
  const now = Date.now();
638
- this.cache.set(key, { data: packed, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
696
+ this.cache.set(key, { data: packed, value: data, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority });
639
697
  this.bloom.add(key);
640
698
  this.maybeRebuildBloom();
641
699
  this.totalSize += size;
@@ -649,7 +707,7 @@ var SmartMemoryCache = class {
649
707
  ks.add(key);
650
708
  }
651
709
  delete(key) {
652
- const deleted = this._delete(key);
710
+ const deleted = this._delete(key, "manual");
653
711
  if (deleted) this.maybeRebuildBloom();
654
712
  return deleted;
655
713
  }
@@ -662,10 +720,77 @@ var SmartMemoryCache = class {
662
720
  }
663
721
  deletePattern(pattern) {
664
722
  let n = 0;
665
- for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key)) n++;
723
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, "manual")) n++;
666
724
  if (n > 0) this.maybeRebuildBloom();
667
725
  return n;
668
726
  }
727
+ /** Flush all entries, or only those whose key starts with `prefix`. */
728
+ clear(prefix) {
729
+ if (prefix) {
730
+ const pattern = prefix.includes("*") ? prefix : `${prefix}*`;
731
+ return this.deletePattern(pattern);
732
+ }
733
+ const count = this.cache.size;
734
+ this.cache.clear();
735
+ this.totalSize = 0;
736
+ this.categoryCount.clear();
737
+ this.categorySize.clear();
738
+ this.categoryKeys.clear();
739
+ this.categoryHits.clear();
740
+ this.bloom.reset();
741
+ this._bloomDirtyCount = 0;
742
+ return count;
743
+ }
744
+ /**
745
+ * Evict entries that violate current category or global limits.
746
+ * Returns the number of entries evicted.
747
+ */
748
+ rebalance() {
749
+ const now = Date.now();
750
+ let evicted = 0;
751
+ for (const [cat, limit] of Object.entries(this.opts.categories)) {
752
+ const catKeys = this.categoryKeys.get(cat);
753
+ if (!catKeys || catKeys.size === 0) continue;
754
+ let catCnt = this.categoryCount.get(cat) ?? 0;
755
+ let catSz = this.categorySize.get(cat) ?? 0;
756
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
757
+ const candidates = [];
758
+ for (const key of catKeys) {
759
+ const entry = this.cache.get(key);
760
+ if (!entry) continue;
761
+ if (entry.priority === 4 && entry.expiresAt > now) continue;
762
+ candidates.push({ key, score: this.score(entry, 0, now) });
763
+ }
764
+ candidates.sort((a, b) => a.score - b.score);
765
+ for (const { key } of candidates) {
766
+ catCnt = this.categoryCount.get(cat) ?? 0;
767
+ catSz = this.categorySize.get(cat) ?? 0;
768
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
769
+ const entry = this.cache.get(key);
770
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
771
+ this._delete(key, "rebalance");
772
+ evicted++;
773
+ }
774
+ }
775
+ while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
776
+ const before = this.cache.size;
777
+ this.smartEvict("default", false);
778
+ if (this.cache.size >= before) break;
779
+ evicted += before - this.cache.size;
780
+ }
781
+ if (evicted > 0) this.maybeRebuildBloom();
782
+ return evicted;
783
+ }
784
+ /**
785
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
786
+ * Only reflects L1 state — does not query Redis or disk.
787
+ */
788
+ ttl(key) {
789
+ const entry = this.cache.get(key);
790
+ if (!entry) return null;
791
+ const remaining = entry.expiresAt - Date.now();
792
+ return remaining > 0 ? Math.ceil(remaining / 1e3) : null;
793
+ }
669
794
  /**
670
795
  * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
671
796
  * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
@@ -688,7 +813,7 @@ var SmartMemoryCache = class {
688
813
  for (const { key } of candidates.slice(0, count)) {
689
814
  const entry = this.cache.get(key);
690
815
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
691
- this._delete(key);
816
+ this._delete(key, "oom");
692
817
  evicted++;
693
818
  }
694
819
  return evicted;
@@ -697,7 +822,7 @@ var SmartMemoryCache = class {
697
822
  const now = Date.now();
698
823
  let cleaned = 0;
699
824
  for (const [key, entry] of this.cache) if (entry.expiresAt < now) {
700
- this._delete(key);
825
+ this._delete(key, "ttl");
701
826
  cleaned++;
702
827
  }
703
828
  if (cleaned > 0) {
@@ -727,7 +852,8 @@ var SmartMemoryCache = class {
727
852
  if (this.cache.has(key)) continue;
728
853
  const rawData = entry.data;
729
854
  const data = !entry.isCompressed ? pack(JSON.parse(rawData)) : rawData instanceof Uint8Array ? Buffer.from(rawData) : rawData;
730
- this.cache.set(key, { ...entry, data, isCompressed: true });
855
+ const value = unpack(data);
856
+ this.cache.set(key, { ...entry, data, value, isCompressed: true });
731
857
  this.bloom.add(key);
732
858
  loaded++;
733
859
  }
@@ -743,9 +869,12 @@ var SmartMemoryCache = class {
743
869
  }
744
870
  getStats() {
745
871
  const categories = {};
746
- for (const [cat, cnt] of this.categoryCount) categories[cat] = cnt;
872
+ for (const [cat, cnt] of this.categoryCount) {
873
+ categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
874
+ }
747
875
  return {
748
876
  entries: this.cache.size,
877
+ sizeBytes: this.totalSize,
749
878
  sizeKB: Math.round(this.totalSize / 1024),
750
879
  categories,
751
880
  bloom: {
@@ -761,6 +890,56 @@ var SmartMemoryCache = class {
761
890
  }
762
891
  };
763
892
  }
893
+ /**
894
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
895
+ * Does NOT count as a hit or perform SWR logic.
896
+ */
897
+ getEntry(key) {
898
+ const entry = this.cache.get(key);
899
+ if (!entry) return void 0;
900
+ if (entry.expiresAt <= Date.now()) return void 0;
901
+ return entry;
902
+ }
903
+ /**
904
+ * Return true if the key exists in L1 and has not expired.
905
+ * Uses the bloom filter as a fast negative check.
906
+ */
907
+ has(key) {
908
+ if (!this.bloom.mightContain(key)) return false;
909
+ const entry = this.cache.get(key);
910
+ if (!entry) return false;
911
+ if (entry.expiresAt <= Date.now()) {
912
+ this._delete(key, "ttl");
913
+ return false;
914
+ }
915
+ return true;
916
+ }
917
+ /**
918
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
919
+ * @param newTtlMs - New TTL from now, in milliseconds.
920
+ */
921
+ touch(key, newTtlMs) {
922
+ const entry = this.cache.get(key);
923
+ if (!entry) return false;
924
+ const now = Date.now();
925
+ if (entry.expiresAt <= now) {
926
+ this._delete(key, "ttl");
927
+ return false;
928
+ }
929
+ entry.expiresAt = now + newTtlMs;
930
+ return true;
931
+ }
932
+ /**
933
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
934
+ * Returns `false` if the key is absent or already expired.
935
+ */
936
+ bumpExpiry(key, additionalMs) {
937
+ const entry = this.cache.get(key);
938
+ if (!entry) return false;
939
+ if (entry.expiresAt <= Date.now()) return false;
940
+ entry.expiresAt += additionalMs;
941
+ return true;
942
+ }
764
943
  bloomMightContain(key) {
765
944
  return this.bloom.mightContain(key);
766
945
  }
@@ -1024,6 +1203,23 @@ var DiskTier = class {
1024
1203
  }
1025
1204
  return purged;
1026
1205
  }
1206
+ /** Delete every file in the disk cache. Returns the count deleted. */
1207
+ clear() {
1208
+ this.ensureDir();
1209
+ if (!this.dirReady) return 0;
1210
+ let cleared = 0;
1211
+ for (const filePath of this.walkCacheFiles()) {
1212
+ try {
1213
+ const stat = fs.statSync(filePath);
1214
+ fs.unlinkSync(filePath);
1215
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1216
+ this.fileCount = Math.max(0, this.fileCount - 1);
1217
+ cleared++;
1218
+ } catch {
1219
+ }
1220
+ }
1221
+ return cleared;
1222
+ }
1027
1223
  get stats() {
1028
1224
  return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
1029
1225
  }
@@ -1056,6 +1252,9 @@ var CacheService = class _CacheService {
1056
1252
  _redisDisabled;
1057
1253
  inflight = /* @__PURE__ */ new Map();
1058
1254
  revalidating = /* @__PURE__ */ new Set();
1255
+ _l1Counters = /* @__PURE__ */ new Map();
1256
+ /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
1257
+ tagIndex = /* @__PURE__ */ new Map();
1059
1258
  redis = null;
1060
1259
  redisConnecting = null;
1061
1260
  snapshotLoaded = false;
@@ -1089,7 +1288,13 @@ var CacheService = class _CacheService {
1089
1288
  this.logger = logger;
1090
1289
  const ns = options.namespace?.trim() ?? "";
1091
1290
  const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
1092
- this.enc = new CacheEncryption(encKeyRaw, logger, options.encryptionMode);
1291
+ this.enc = new CacheEncryption(
1292
+ encKeyRaw,
1293
+ logger,
1294
+ options.encryptionMode,
1295
+ options.previousEncryptionKey,
1296
+ options.previousEncryptionMode
1297
+ );
1093
1298
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
1094
1299
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
1095
1300
  this.opts = {
@@ -1123,7 +1328,10 @@ var CacheService = class _CacheService {
1123
1328
  oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
1124
1329
  oomEvictPercent: options.oomEvictPercent ?? 0.2,
1125
1330
  onMetrics: options.onMetrics,
1126
- metricsIntervalMs: options.metricsIntervalMs ?? 6e4
1331
+ metricsIntervalMs: options.metricsIntervalMs ?? 6e4,
1332
+ staleIfError: options.staleIfError ?? 0,
1333
+ l2WriteMode: options.l2WriteMode ?? "read-write",
1334
+ instanceName: options.instanceName ?? ""
1127
1335
  };
1128
1336
  this.disk = new DiskTier({
1129
1337
  dir: this.opts.diskCacheDir,
@@ -1142,6 +1350,7 @@ var CacheService = class _CacheService {
1142
1350
  diskSpill: (key, entry) => {
1143
1351
  void this.disk.save(key, entry);
1144
1352
  },
1353
+ onEviction: options.onEviction,
1145
1354
  logger
1146
1355
  });
1147
1356
  if (!this.snapshotLoaded) {
@@ -1208,6 +1417,17 @@ var CacheService = class _CacheService {
1208
1417
  if (!g[key]) g[key] = new _CacheService(options);
1209
1418
  return g[key];
1210
1419
  }
1420
+ /**
1421
+ * Async factory — accepts a Promise that resolves to CacheOptions.
1422
+ * Useful when config is fetched from a secret store at startup.
1423
+ *
1424
+ * @example
1425
+ * const cache = await CacheService.createAsync(fetchSecrets());
1426
+ */
1427
+ static async createAsync(options) {
1428
+ const resolved = await options;
1429
+ return _CacheService.create(resolved);
1430
+ }
1211
1431
  /** Replace the singleton (useful in tests). */
1212
1432
  static reset(options) {
1213
1433
  const g = globalThis;
@@ -1293,43 +1513,49 @@ var CacheService = class _CacheService {
1293
1513
  if (this.redis?.status === "ready") return this.redis;
1294
1514
  if (this.redisConnecting) return this.redisConnecting;
1295
1515
  this.redisConnecting = (async () => {
1296
- const client = new RedisClient({
1297
- host: this.opts.redisHost,
1298
- port: this.opts.redisPort,
1299
- tls: this.opts.redisTls ? {} : void 0,
1300
- connectTimeout: 1e4,
1301
- lazyConnect: false,
1302
- maxRetriesPerRequest: 3,
1303
- enableAutoPipelining: true,
1304
- keepAlive: 3e4,
1305
- family: 4,
1306
- retryStrategy: (times) => Math.min(times * 50, 2e3)
1307
- });
1308
- client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
1309
- client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
1310
- client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
1311
- await new Promise((resolve, reject) => {
1312
- client.once("ready", resolve);
1313
- client.once("error", reject);
1314
- setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1315
- });
1316
- this.redis = client;
1317
- this.redisConnecting = null;
1318
- return client;
1516
+ try {
1517
+ const client = new RedisClient({
1518
+ host: this.opts.redisHost,
1519
+ port: this.opts.redisPort,
1520
+ tls: this.opts.redisTls ? {} : void 0,
1521
+ connectTimeout: 1e4,
1522
+ lazyConnect: false,
1523
+ maxRetriesPerRequest: 3,
1524
+ enableAutoPipelining: true,
1525
+ keepAlive: 3e4,
1526
+ family: 4,
1527
+ retryStrategy: (times) => Math.min(times * 50, 2e3)
1528
+ });
1529
+ client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
1530
+ client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
1531
+ client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
1532
+ await new Promise((resolve, reject) => {
1533
+ client.once("ready", resolve);
1534
+ client.once("error", reject);
1535
+ setTimeout(() => reject(new Error("Redis connection timeout")), 15e3);
1536
+ });
1537
+ this.redis = client;
1538
+ this.redisConnecting = null;
1539
+ return client;
1540
+ } catch (err) {
1541
+ this.redisConnecting = null;
1542
+ throw err;
1543
+ }
1319
1544
  })();
1320
1545
  return this.redisConnecting;
1321
1546
  }
1322
1547
  // ── Snapshot (cold-start persistence) ────────────────────────────────────
1323
- writeSnapshot() {
1548
+ writeSnapshot(altPath) {
1324
1549
  try {
1325
1550
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
1326
1551
  if (entries.length === 0) return;
1327
1552
  const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
1328
1553
  const packed = pack3(payload);
1329
1554
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
1330
- fs2.writeFileSync(this.opts.snapshotPath, final, { mode: 384 });
1555
+ const dest = altPath ?? this.opts.snapshotPath;
1556
+ fs2.writeFileSync(dest, final, { mode: 384 });
1331
1557
  this.logger.info("Cache snapshot written", {
1332
- path: this.opts.snapshotPath,
1558
+ path: dest,
1333
1559
  entries: entries.length,
1334
1560
  sizeKB: Math.round(final.length / 1024),
1335
1561
  encrypted: this.enc.isEnabled
@@ -1492,7 +1718,7 @@ var CacheService = class _CacheService {
1492
1718
  const data = await fetchFn();
1493
1719
  const staleAt = Date.now() + ttlMs;
1494
1720
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt);
1495
- if (!this._redisDisabled) {
1721
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1496
1722
  try {
1497
1723
  const client = await this.getRedis();
1498
1724
  const s = JSON.stringify(data);
@@ -1503,20 +1729,53 @@ var CacheService = class _CacheService {
1503
1729
  }
1504
1730
  this.logger.debug("SWR: revalidation complete", { cacheKey });
1505
1731
  } catch (err) {
1506
- this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
1732
+ if (this.opts.staleIfError > 0) {
1733
+ const additionalMs = this.opts.staleIfError * 1e3;
1734
+ this.l1.bumpExpiry(cacheKey, additionalMs);
1735
+ this.logger.debug("SWR: revalidation failed, stale-if-error extending expiry", {
1736
+ cacheKey,
1737
+ staleIfErrorSecs: this.opts.staleIfError
1738
+ });
1739
+ } else {
1740
+ this.logger.debug("SWR: revalidation failed", { cacheKey, error: err.message });
1741
+ }
1507
1742
  } finally {
1508
1743
  this.revalidating.delete(cacheKey);
1509
1744
  }
1510
1745
  }
1511
1746
  // ── Explicit set / delete ─────────────────────────────────────────────────
1512
1747
  /** Explicitly write a value into L1 (+ L2 in production). */
1513
- async set(cacheKey, data, ttlSeconds = 300, priority) {
1748
+ async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
1514
1749
  const ttlMs = ttlSeconds * 1e3;
1515
1750
  const p = priority ?? inferPriority(cacheKey);
1516
1751
  const k = this.nk(cacheKey);
1517
1752
  this.counters.sets++;
1518
1753
  this.l1.set(k, data, ttlMs, p);
1519
- if (!this._redisDisabled) {
1754
+ if (opts?.tags?.length) {
1755
+ for (const tag of opts.tags) {
1756
+ const tagKey = this.nk(`_tag_:${tag}`);
1757
+ let members = this.tagIndex.get(tagKey);
1758
+ if (!members) {
1759
+ members = /* @__PURE__ */ new Set();
1760
+ this.tagIndex.set(tagKey, members);
1761
+ }
1762
+ members.add(k);
1763
+ }
1764
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1765
+ try {
1766
+ const client = await this.getRedis();
1767
+ const pl = client.pipeline();
1768
+ for (const tag of opts.tags) {
1769
+ const tagKey = this.nk(`_tag_:${tag}`);
1770
+ pl.sadd(tagKey, k);
1771
+ pl.expire(tagKey, ttlSeconds + 3600);
1772
+ }
1773
+ await pl.exec();
1774
+ } catch {
1775
+ }
1776
+ }
1777
+ }
1778
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1520
1779
  try {
1521
1780
  const client = await this.getRedis();
1522
1781
  const s = JSON.stringify(data);
@@ -1545,7 +1804,7 @@ var CacheService = class _CacheService {
1545
1804
  this.l1.delete(k);
1546
1805
  this.disk.delete(k);
1547
1806
  }
1548
- if (!this._redisDisabled) {
1807
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1549
1808
  try {
1550
1809
  const client = await this.getRedis();
1551
1810
  if (isPattern) {
@@ -1572,8 +1831,18 @@ var CacheService = class _CacheService {
1572
1831
  * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
1573
1832
  */
1574
1833
  async increment(cacheKey, ttlSeconds) {
1575
- if (this._redisDisabled) return 0;
1576
1834
  const k = this.nk(cacheKey);
1835
+ if (this._redisDisabled) {
1836
+ const now = Date.now();
1837
+ const ttlMs = (ttlSeconds ?? 60) * 1e3;
1838
+ const entry = this._l1Counters.get(k);
1839
+ if (entry && entry.expiresAt > now) {
1840
+ entry.value++;
1841
+ return entry.value;
1842
+ }
1843
+ this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
1844
+ return 1;
1845
+ }
1577
1846
  try {
1578
1847
  const client = await this.getRedis();
1579
1848
  const count = await client.incr(k);
@@ -1584,7 +1853,225 @@ var CacheService = class _CacheService {
1584
1853
  return 0;
1585
1854
  }
1586
1855
  }
1587
- // ── Stats ─────────────────────────────────────────────────────────────────
1856
+ // ── Clear / Rebalance / TTL ────────────────────────────────────────────────
1857
+ /**
1858
+ * Flush all cached entries, or only those whose key starts with `prefix`.
1859
+ *
1860
+ * @example
1861
+ * await cache.clear(); // flush everything
1862
+ * await cache.clear('user:abc'); // flush all keys for one user
1863
+ */
1864
+ async clear(prefix) {
1865
+ this.counters.deletes++;
1866
+ const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
1867
+ if (k) {
1868
+ this.l1.deletePattern(k);
1869
+ } else {
1870
+ this.l1.clear();
1871
+ this.disk.clear();
1872
+ this._l1Counters.clear();
1873
+ this.tagIndex.clear();
1874
+ }
1875
+ if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
1876
+ try {
1877
+ const client = await this.getRedis();
1878
+ const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
1879
+ const stream = client.scanStream({ match: pattern, count: 100 });
1880
+ const keys = [];
1881
+ await new Promise((resolve, reject) => {
1882
+ stream.on("data", (chunk) => keys.push(...chunk));
1883
+ stream.on("end", resolve);
1884
+ stream.on("error", reject);
1885
+ });
1886
+ if (keys.length > 0) await client.del(...keys);
1887
+ } catch (err) {
1888
+ this.logger.debug("clear: Redis unavailable", { error: err.message });
1889
+ }
1890
+ }
1891
+ void this.publishInvalidation(
1892
+ "del-glob",
1893
+ k ?? (this._namespace ? `${this._namespace}:*` : "*")
1894
+ );
1895
+ }
1896
+ /**
1897
+ * Evict L1 entries that violate the current category or global capacity limits.
1898
+ * Useful after a write burst or after adding stricter `categoryLimits`.
1899
+ * Returns the number of entries evicted.
1900
+ */
1901
+ rebalance() {
1902
+ return this.l1.rebalance();
1903
+ }
1904
+ /**
1905
+ * Return the remaining TTL in seconds for a key currently in L1.
1906
+ * Returns null if the key is absent from L1 or has already expired.
1907
+ * Only reflects L1 state — does not query Redis or disk.
1908
+ */
1909
+ ttl(cacheKey) {
1910
+ return this.l1.ttl(this.nk(cacheKey));
1911
+ }
1912
+ /**
1913
+ * Return true if the key exists in L1 and has not expired.
1914
+ * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
1915
+ */
1916
+ has(cacheKey) {
1917
+ return this.l1.has(this.nk(cacheKey));
1918
+ }
1919
+ /**
1920
+ * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
1921
+ * Returns `false` if the key is absent or already expired.
1922
+ *
1923
+ * @param newTtlSeconds - The new TTL from now, in seconds.
1924
+ */
1925
+ async touch(cacheKey, newTtlSeconds) {
1926
+ const k = this.nk(cacheKey);
1927
+ const hit = this.l1.touch(k, newTtlSeconds * 1e3);
1928
+ if (hit && !this._redisDisabled) {
1929
+ try {
1930
+ const client = await this.getRedis();
1931
+ void client.expire(k, newTtlSeconds);
1932
+ } catch {
1933
+ }
1934
+ }
1935
+ return hit;
1936
+ }
1937
+ /**
1938
+ * Return the cached value from L1 **only if it is fresh** (not in the SWR grace window).
1939
+ * Returns `null` when the key is absent, expired, or stale — without triggering a fetch.
1940
+ *
1941
+ * @example
1942
+ * const fresh = cache.getIfFresh('user:123');
1943
+ * if (fresh !== null) return fresh; // serve from L1, no network hop
1944
+ */
1945
+ getIfFresh(cacheKey) {
1946
+ const k = this.nk(cacheKey);
1947
+ const entry = this.l1.getEntry(k);
1948
+ if (!entry) return null;
1949
+ const now = Date.now();
1950
+ if (entry.expiresAt <= now) return null;
1951
+ if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
1952
+ return entry.value !== void 0 ? entry.value : unpack3(entry.data);
1953
+ }
1954
+ /**
1955
+ * Batch get — fetches multiple keys, using L1 where hot and calling `fetchFn` for misses.
1956
+ * Preserves input ordering. Uses inflight coalescing per key.
1957
+ *
1958
+ * @param keys - Array of cache keys.
1959
+ * @param fetchFn - Called with only the keys that missed L1.
1960
+ * @param ttl - TTL in seconds for newly fetched values.
1961
+ */
1962
+ async mget(keys, fetchFn, ttl = 300, priority) {
1963
+ const result = new Array(keys.length);
1964
+ const missIndexes = [];
1965
+ const missKeys = [];
1966
+ for (let i = 0; i < keys.length; i++) {
1967
+ const entry = this.l1.getEntry(this.nk(keys[i]));
1968
+ if (entry && entry.expiresAt > Date.now()) {
1969
+ result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
1970
+ this.counters.l1Hits++;
1971
+ } else {
1972
+ missIndexes.push(i);
1973
+ missKeys.push(keys[i]);
1974
+ }
1975
+ }
1976
+ if (missKeys.length > 0) {
1977
+ const fetched = await fetchFn(missKeys);
1978
+ for (let j = 0; j < missKeys.length; j++) {
1979
+ const v = fetched[missKeys[j]];
1980
+ result[missIndexes[j]] = v;
1981
+ if (v !== void 0) {
1982
+ await this.set(missKeys[j], v, ttl, priority);
1983
+ }
1984
+ }
1985
+ }
1986
+ return result;
1987
+ }
1988
+ /**
1989
+ * Invalidate all keys associated with a tag.
1990
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
1991
+ *
1992
+ * @example
1993
+ * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
1994
+ * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
1995
+ */
1996
+ async invalidateTag(tag) {
1997
+ const tagKey = this.nk(`_tag_:${tag}`);
1998
+ const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
1999
+ for (const k of members) {
2000
+ this.l1.delete(k);
2001
+ this.disk.delete(k);
2002
+ }
2003
+ this.tagIndex.delete(tagKey);
2004
+ if (!this._redisDisabled) {
2005
+ try {
2006
+ const client = await this.getRedis();
2007
+ const redisMembers = await client.smembers(tagKey);
2008
+ const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
2009
+ if (toDelete.length > 0) {
2010
+ await client.del(...toDelete, tagKey);
2011
+ } else {
2012
+ await client.del(tagKey);
2013
+ }
2014
+ } catch (err) {
2015
+ this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
2016
+ }
2017
+ }
2018
+ }
2019
+ /**
2020
+ * Measure L1 / disk / Redis latency.
2021
+ * Useful for health checks and dashboards.
2022
+ *
2023
+ * @returns `{ l1, disk, l2 }` latencies in milliseconds.
2024
+ * `l2` is `null` when Redis is disabled.
2025
+ */
2026
+ async ping() {
2027
+ const t0 = Date.now();
2028
+ this.l1.has("__ping__");
2029
+ const l1 = Date.now() - t0;
2030
+ const t1 = Date.now();
2031
+ void this.disk.stats;
2032
+ const disk = Date.now() - t1;
2033
+ let l2 = null;
2034
+ if (!this._redisDisabled) {
2035
+ try {
2036
+ const client = await this.getRedis();
2037
+ const t2 = Date.now();
2038
+ await client.ping();
2039
+ l2 = Date.now() - t2;
2040
+ } catch {
2041
+ l2 = null;
2042
+ }
2043
+ }
2044
+ return { l1, disk, l2 };
2045
+ }
2046
+ /**
2047
+ * Export all live L1 entries to Redis via a single pipeline.
2048
+ * Useful for warming a new Redis instance or for zero-downtime failover.
2049
+ * Returns the number of keys written.
2050
+ */
2051
+ async drainToL2() {
2052
+ if (this._redisDisabled) return 0;
2053
+ try {
2054
+ const client = await this.getRedis();
2055
+ const entries = this.l1.exportEntries([]);
2056
+ const now = Date.now();
2057
+ if (entries.length === 0) return 0;
2058
+ const pl = client.pipeline();
2059
+ for (const { key, entry } of entries) {
2060
+ const remainingMs = entry.expiresAt - now;
2061
+ if (remainingMs <= 0) continue;
2062
+ const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1e3));
2063
+ const s = JSON.stringify(entry.value);
2064
+ const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
2065
+ pl.setex(key, ttlSecs, stored);
2066
+ }
2067
+ await pl.exec();
2068
+ return entries.length;
2069
+ } catch (err) {
2070
+ this.logger.debug("drainToL2: Redis unavailable", { error: err.message });
2071
+ return 0;
2072
+ }
2073
+ }
2074
+ // ── Stats ─────────────────────────────────────────────────────────────
1588
2075
  stats() {
1589
2076
  return {
1590
2077
  l1: this.l1.getStats(),
@@ -1651,8 +2138,11 @@ var CacheService = class _CacheService {
1651
2138
  * @param m - Snapshot returned by `cache.metrics()`
1652
2139
  * @param prefix - Metric name prefix. Default: `"tricache"`
1653
2140
  */
1654
- static toPrometheusText(m, prefix = "tricache") {
1655
- const lbl = m.namespace ? `{namespace="${m.namespace}"}` : "";
2141
+ static toPrometheusText(m, prefix = "tricache", instanceName) {
2142
+ const parts = [];
2143
+ if (m.namespace) parts.push(`namespace="${m.namespace}"`);
2144
+ if (instanceName) parts.push(`instance="${instanceName}"`);
2145
+ const lbl = parts.length ? `{${parts.join(",")}}` : "";
1656
2146
  const lines = [];
1657
2147
  const counter = (name, val, help) => {
1658
2148
  lines.push(`# HELP ${prefix}_${name}_total ${help}`);