tricache 0.6.5 → 0.6.7

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
@@ -330,6 +330,20 @@ var CacheEncryption = class {
330
330
  get isEnabled() {
331
331
  return this._key !== null;
332
332
  }
333
+ /**
334
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
335
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
336
+ * cast in cache-service.ts — the worker pool reads these via this accessor
337
+ * instead of reaching into underscore-prefixed internals.
338
+ */
339
+ toWorkerInit() {
340
+ return {
341
+ keyBase64: this._key ? this._key.toString("base64") : "",
342
+ mode: this._mode,
343
+ prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
344
+ prevMode: this._prevMode
345
+ };
346
+ }
333
347
  // ── String (Redis) ────────────────────────────────────────────────────────
334
348
  /**
335
349
  * Encrypt a string for Redis storage.
@@ -372,18 +386,18 @@ var CacheEncryption = class {
372
386
  */
373
387
  decrypt(value) {
374
388
  try {
375
- return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
389
+ return this._decryptWithKey(value, this._key, this._keyObj);
376
390
  } catch (primaryErr) {
377
391
  if (this._prevKey) {
378
392
  try {
379
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
393
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
380
394
  } catch {
381
395
  }
382
396
  }
383
397
  throw primaryErr;
384
398
  }
385
399
  }
386
- _decryptWithKey(value, key, keyObj, mode) {
400
+ _decryptWithKey(value, key, keyObj) {
387
401
  if (value.startsWith(PREFIX_XOR)) {
388
402
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
389
403
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -418,8 +432,6 @@ var CacheEncryption = class {
418
432
  const plain = d.update(ct);
419
433
  d.final();
420
434
  return plain.toString("utf8");
421
- void mode;
422
- void key;
423
435
  }
424
436
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
425
437
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
@@ -569,8 +581,8 @@ var WasmBloomFilter = class {
569
581
  }
570
582
  /**
571
583
  * Maximum safe insertions before false-positive rate exceeds ~1 %.
572
- * Exact formula for k=7 hash rounds, m=100 000 bits:
573
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
584
+ * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
585
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
574
586
  */
575
587
  get maxCapacity() {
576
588
  return this._maxCapacity;
@@ -839,8 +851,8 @@ var SmartMemoryCache = class {
839
851
  const lim = this.getCategoryLimit(category);
840
852
  const catCnt = this.categoryCount.get(category) ?? 0;
841
853
  const catSz = this.categorySize.get(category) ?? 0;
842
- const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
843
- const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
854
+ let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
855
+ let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
844
856
  if (!catOvf && !glbOvf) {
845
857
  const wm = this.opts.evictionWatermark ?? 0.9;
846
858
  const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
@@ -850,7 +862,17 @@ var SmartMemoryCache = class {
850
862
  }
851
863
  return;
852
864
  }
853
- this.smartEvict(category, catOvf);
865
+ const MAX_EVICT_PASSES = 64;
866
+ let passes = 0;
867
+ do {
868
+ this.smartEvict(category, catOvf);
869
+ const lim2 = this.getCategoryLimit(category);
870
+ const catCnt2 = this.categoryCount.get(category) ?? 0;
871
+ const catSz2 = this.categorySize.get(category) ?? 0;
872
+ catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
873
+ glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
874
+ passes++;
875
+ } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
854
876
  }
855
877
  score(entry, catBonus, now, key) {
856
878
  const age = now - entry.lastAccess;
@@ -1398,9 +1420,6 @@ try {
1398
1420
  _SqliteDB = sqlite?.DatabaseSync ?? null;
1399
1421
  } catch {
1400
1422
  }
1401
- var AES_ALGO = "aes-256-gcm";
1402
- var IV_BYTES2 = 12;
1403
- var TAG_BYTES2 = 16;
1404
1423
  var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1405
1424
  var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1406
1425
  var V2_HEADER_LEN = 16;
@@ -1589,54 +1608,33 @@ var DiskTier = class {
1589
1608
  return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
1590
1609
  }
1591
1610
  encrypt(data) {
1592
- const key = this.opts.encryptionKey;
1593
- if (!key) return data;
1594
- const iv = import_crypto2.default.randomBytes(IV_BYTES2);
1595
- const c = import_crypto2.default.createCipheriv(AES_ALGO, key, iv);
1596
- const enc = Buffer.concat([c.update(data), c.final()]);
1597
- const tag = c.getAuthTag();
1598
- return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
1611
+ if (!this.opts.encryption) return data;
1612
+ return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
1599
1613
  }
1600
1614
  decrypt(data) {
1601
1615
  const mLen = DISK_MAGIC.length;
1602
1616
  if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
1603
- const key = this.opts.encryptionKey;
1604
- if (!key) throw new Error("DiskTier: entry is encrypted but no key is set");
1605
- const iv = data.subarray(mLen, mLen + IV_BYTES2);
1606
- const tag = data.subarray(mLen + IV_BYTES2, mLen + IV_BYTES2 + TAG_BYTES2);
1607
- const ct = data.subarray(mLen + IV_BYTES2 + TAG_BYTES2);
1608
- const d = import_crypto2.default.createDecipheriv(AES_ALGO, key, iv);
1609
- d.setAuthTag(tag);
1610
- return Buffer.concat([d.update(ct), d.final()]);
1617
+ if (!this.opts.encryption) throw new Error("DiskTier: entry is encrypted but no encryption configured");
1618
+ return this.opts.encryption.decryptBuffer(data.subarray(mLen));
1611
1619
  }
1612
1620
  /**
1613
- * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1614
- * the outer 16-byte header alongside the plaintext expiresAt).
1615
- * Returns the buffer unchanged when no encryption key is configured.
1621
+ * V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
1622
+ * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
1623
+ * Returns the buffer unchanged when no encryption instance is configured.
1616
1624
  */
1617
1625
  encryptV2(data) {
1618
- const key = this.opts.encryptionKey;
1619
- if (!key) return data;
1620
- const iv = import_crypto2.default.randomBytes(IV_BYTES2);
1621
- const c = import_crypto2.default.createCipheriv(AES_ALGO, key, iv);
1622
- const enc = Buffer.concat([c.update(data), c.final()]);
1623
- const tag = c.getAuthTag();
1624
- return Buffer.concat([iv, tag, enc]);
1626
+ if (!this.opts.encryption) return data;
1627
+ return this.opts.encryption.encryptBuffer(data);
1625
1628
  }
1626
1629
  /**
1627
1630
  * V2 decryption — inner payload after stripping the 16-byte header.
1628
- * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1629
- * without a key the payload is raw msgpack.
1631
+ * When an encryption instance is configured the format is the mode-aware
1632
+ * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
1633
+ * without one the payload is raw msgpack.
1630
1634
  */
1631
1635
  decryptV2(inner) {
1632
- const key = this.opts.encryptionKey;
1633
- if (!key) return inner;
1634
- const iv = inner.subarray(0, IV_BYTES2);
1635
- const tag = inner.subarray(IV_BYTES2, IV_BYTES2 + TAG_BYTES2);
1636
- const ct = inner.subarray(IV_BYTES2 + TAG_BYTES2);
1637
- const d = import_crypto2.default.createDecipheriv(AES_ALGO, key, iv);
1638
- d.setAuthTag(tag);
1639
- return Buffer.concat([d.update(ct), d.final()]);
1636
+ if (!this.opts.encryption) return inner;
1637
+ return this.opts.encryption.decryptBuffer(inner);
1640
1638
  }
1641
1639
  // ── Public API ────────────────────────────────────────────────────────────
1642
1640
  /**
@@ -2108,12 +2106,24 @@ var L2CircuitBreaker = class {
2108
2106
  state = 0 /* CLOSED */;
2109
2107
  failures = 0;
2110
2108
  openedAt = 0;
2111
- /** Call before each Redis attempt. Returns false when the circuit is open. */
2109
+ /** True while the single permitted HALF_OPEN probe is in flight. */
2110
+ probing = false;
2111
+ /**
2112
+ * Call before each Redis attempt. Returns false when the circuit is open.
2113
+ * In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
2114
+ * arriving while a probe is outstanding are rejected (return false) so a
2115
+ * recovering Redis node is not stampeded.
2116
+ */
2112
2117
  isAllowed() {
2113
2118
  if (this.state === 0 /* CLOSED */) return true;
2114
- if (this.state === 2 /* HALF_OPEN */) return true;
2119
+ if (this.state === 2 /* HALF_OPEN */) {
2120
+ if (this.probing) return false;
2121
+ this.probing = true;
2122
+ return true;
2123
+ }
2115
2124
  if (Date.now() - this.openedAt >= this.cooldownMs) {
2116
2125
  this.state = 2 /* HALF_OPEN */;
2126
+ this.probing = true;
2117
2127
  return true;
2118
2128
  }
2119
2129
  return false;
@@ -2121,11 +2131,13 @@ var L2CircuitBreaker = class {
2121
2131
  /** Call on Redis success. */
2122
2132
  onSuccess() {
2123
2133
  this.failures = 0;
2134
+ this.probing = false;
2124
2135
  this.state = 0 /* CLOSED */;
2125
2136
  }
2126
2137
  /** Call on Redis failure. */
2127
2138
  onFailure() {
2128
2139
  this.failures++;
2140
+ this.probing = false;
2129
2141
  if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
2130
2142
  this.state = 1 /* OPEN */;
2131
2143
  this.openedAt = Date.now();
@@ -2300,8 +2312,14 @@ var CacheService = class _CacheService {
2300
2312
  invSkipped: 0,
2301
2313
  oomEvictions: 0,
2302
2314
  oomLastAt: null,
2315
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
2316
+ counterErrors: 0,
2317
+ /** Times a later `create(ns)` call passed options differing from the live singleton. */
2318
+ singletonDivergences: 0,
2303
2319
  startedAt: Date.now()
2304
2320
  };
2321
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
2322
+ _incrementFallbackWarned = false;
2305
2323
  // ── Constructor (use CacheService.create() for the recommended singleton) ──
2306
2324
  constructor(options = {}) {
2307
2325
  const logger = options.logger ?? consoleLogger;
@@ -2372,7 +2390,9 @@ var CacheService = class _CacheService {
2372
2390
  backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
2373
2391
  disableDisk: options.disableDisk ?? false,
2374
2392
  redisClusterNodes: options.redisClusterNodes,
2375
- redisSentinel: options.redisSentinel
2393
+ redisSentinel: options.redisSentinel,
2394
+ strictSingleton: options.strictSingleton ?? false,
2395
+ failClosed: options.failClosed ?? false
2376
2396
  };
2377
2397
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2378
2398
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -2401,7 +2421,7 @@ var CacheService = class _CacheService {
2401
2421
  maxBytes: this.opts.diskMaxBytes,
2402
2422
  entryMaxBytes: this.opts.diskEntryMaxBytes,
2403
2423
  forbiddenPrefixes,
2404
- encryptionKey: this.enc.isEnabled ? this.enc["_key"] : null,
2424
+ encryption: this.enc.isEnabled ? this.enc : null,
2405
2425
  logger
2406
2426
  });
2407
2427
  this._namespace = ns;
@@ -2432,12 +2452,12 @@ var CacheService = class _CacheService {
2432
2452
  process.once("SIGINT", this._shutdownHandler);
2433
2453
  if (this.opts.workerThreads && this.enc.isEnabled) {
2434
2454
  try {
2435
- const encRef = this.enc;
2455
+ const encRef = this.enc.toWorkerInit();
2436
2456
  this._workerPool = new WorkerPool({
2437
- keyBase64: encRef._key ? encRef._key.toString("base64") : "",
2438
- mode: encRef._mode,
2439
- prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString("base64") : void 0,
2440
- prevMode: encRef._prevMode,
2457
+ keyBase64: encRef.keyBase64,
2458
+ mode: encRef.mode,
2459
+ prevKeyBase64: encRef.prevKeyBase64,
2460
+ prevMode: encRef.prevMode,
2441
2461
  size: this.opts.workerPoolSize || void 0
2442
2462
  });
2443
2463
  if (this._workerPool.isAvailable) {
@@ -2503,7 +2523,10 @@ var CacheService = class _CacheService {
2503
2523
  * Get (or create) the process-level singleton CacheService instance.
2504
2524
  *
2505
2525
  * Options are only applied on first call — subsequent calls return the
2506
- * existing instance regardless of options passed.
2526
+ * existing instance regardless of options passed. When the new options differ
2527
+ * from what the existing singleton was built with, this is a silent no-op by
2528
+ * default; set `strictSingleton: true` to throw instead, or watch the
2529
+ * `singletonDivergences` metric for detection.
2507
2530
  *
2508
2531
  * When `namespace` is set the singleton is keyed by namespace, so two calls
2509
2532
  * with different namespaces return independent instances.
@@ -2511,8 +2534,83 @@ var CacheService = class _CacheService {
2511
2534
  static create(options) {
2512
2535
  const g = globalThis;
2513
2536
  const key = _CacheService.globalKey(options);
2514
- if (!g[key]) g[key] = new _CacheService(options);
2515
- return g[key];
2537
+ if (!g[key]) {
2538
+ g[key] = new _CacheService(options);
2539
+ return g[key];
2540
+ }
2541
+ const existing = g[key];
2542
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
2543
+ if (diff.length > 0) {
2544
+ existing.bumpSingletonDivergence();
2545
+ const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
2546
+ if (existing.options.strictSingleton) {
2547
+ throw new Error(`strictSingleton: ${msg}`);
2548
+ }
2549
+ (existing.options.logger ?? consoleLogger).warn(msg, { divergentOptions: diff });
2550
+ }
2551
+ return existing;
2552
+ }
2553
+ /**
2554
+ * Keys that, if set differently on a later `create()` call, represent a
2555
+ * meaningful configuration divergence worth flagging (security/correctness
2556
+ * relevant — not cosmetic, e.g. log level).
2557
+ */
2558
+ static DIVERGENT_KEYS = [
2559
+ "redisHost",
2560
+ "redisPort",
2561
+ "redisTls",
2562
+ "disableRedis",
2563
+ "redisClusterNodes",
2564
+ "redisSentinel",
2565
+ "encryptionKey",
2566
+ "encryptionMode",
2567
+ "l1MaxBytes",
2568
+ "l1MaxEntries",
2569
+ "namespace",
2570
+ "frozen",
2571
+ "adaptiveTtl",
2572
+ "l2WriteMode",
2573
+ "instanceName",
2574
+ "invalidationBackplane"
2575
+ ];
2576
+ /** Returns the names of options that differ between `a` and the live `b`. */
2577
+ static optionsDiff(a, b) {
2578
+ const out = [];
2579
+ for (const k of _CacheService.DIVERGENT_KEYS) {
2580
+ const av = a[k];
2581
+ const bv = b[k];
2582
+ if (av === void 0) continue;
2583
+ const same = JSON.stringify(av) === JSON.stringify(bv) || k === "encryptionKey" && av === bv;
2584
+ if (!same) out.push(String(k));
2585
+ }
2586
+ return out;
2587
+ }
2588
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
2589
+ bumpSingletonDivergence() {
2590
+ this.counters.singletonDivergences++;
2591
+ }
2592
+ /** Read-only view of the options the singleton was constructed with. */
2593
+ get options() {
2594
+ const o = this.opts;
2595
+ return {
2596
+ namespace: o.namespace,
2597
+ logger: o.logger,
2598
+ l1MaxBytes: o.l1MaxBytes,
2599
+ l1MaxEntries: o.l1MaxEntries,
2600
+ redisHost: o.redisHost,
2601
+ redisPort: o.redisPort,
2602
+ redisTls: o.redisTls,
2603
+ disableRedis: this._redisDisabled,
2604
+ redisClusterNodes: o.redisClusterNodes,
2605
+ redisSentinel: o.redisSentinel,
2606
+ encryptionKey: o.encryptionKey,
2607
+ l2WriteMode: o.l2WriteMode,
2608
+ instanceName: o.instanceName,
2609
+ frozen: o.frozen,
2610
+ adaptiveTtl: o.adaptiveTtl,
2611
+ invalidationBackplane: o.invalidationBackplane,
2612
+ strictSingleton: o.strictSingleton
2613
+ };
2516
2614
  }
2517
2615
  /**
2518
2616
  * Async factory — accepts a Promise that resolves to CacheOptions.
@@ -2550,11 +2648,16 @@ var CacheService = class _CacheService {
2550
2648
  nk(key) {
2551
2649
  return this._namespace ? `${this._namespace}:${key}` : key;
2552
2650
  }
2651
+ /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
2652
+ unnk(key) {
2653
+ return this._namespace ? key.slice(this._namespace.length + 1) : key;
2654
+ }
2553
2655
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
2554
2656
  _jitterTtl(ttlMs) {
2555
2657
  const j = this.opts.ttlJitterFactor;
2556
2658
  if (j === 0) return ttlMs;
2557
- return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
2659
+ const rand = import_crypto3.default.randomInt(0, 1e5) / 5e4 - 1;
2660
+ return Math.round(ttlMs * (1 + rand * j));
2558
2661
  }
2559
2662
  /** Shared no-op span for the common case where no tracer is configured.
2560
2663
  * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
@@ -2645,6 +2748,12 @@ var CacheService = class _CacheService {
2645
2748
  _handleBackplaneMessage(message) {
2646
2749
  try {
2647
2750
  const msg = JSON.parse(message);
2751
+ if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob") {
2752
+ this.logger.warn("Backplane: rejected invalid pubsub message format", {
2753
+ raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
2754
+ });
2755
+ return;
2756
+ }
2648
2757
  if (msg.src === this.instanceId) {
2649
2758
  this.counters.invSkipped++;
2650
2759
  return;
@@ -2664,6 +2773,7 @@ var CacheService = class _CacheService {
2664
2773
  key: msg.key.slice(0, 60)
2665
2774
  });
2666
2775
  } catch {
2776
+ this.logger.warn("Backplane: malformed message JSON parse failed");
2667
2777
  }
2668
2778
  }
2669
2779
  async publishInvalidation(op, key) {
@@ -3174,12 +3284,31 @@ var CacheService = class _CacheService {
3174
3284
  }
3175
3285
  // ── Counter (distributed rate limiting) ──────────────────────────────────
3176
3286
  /**
3177
- * Atomically increment a counter in Redis. Returns the new value.
3178
- * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
3287
+ * Distributed counter.
3288
+ *
3289
+ * When Redis is active, atomically increments the key via `INCR` and returns
3290
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
3291
+ * and, by default, fails OPEN — returning `0` so a caller's
3292
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
3293
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
3294
+ * when Redis is unavailable.
3295
+ *
3296
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
3297
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
3298
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
3299
+ * a one-time warning is logged because rate-limiting is then per-instance, not
3300
+ * fleet-wide.
3179
3301
  */
3180
3302
  async increment(cacheKey, ttlSeconds) {
3181
3303
  const k = this.nk(cacheKey);
3182
3304
  if (this._redisDisabled) {
3305
+ if (!this._incrementFallbackWarned) {
3306
+ this._incrementFallbackWarned = true;
3307
+ this.logger.warn(
3308
+ "tricache: increment() using in-process counter \u2014 rate limiting is NOT fleet-wide (Redis disabled)",
3309
+ { cacheKey }
3310
+ );
3311
+ }
3183
3312
  const now = Date.now();
3184
3313
  const ttlMs = (ttlSeconds ?? 60) * 1e3;
3185
3314
  const entry = this._l1Counters.get(k);
@@ -3196,7 +3325,10 @@ var CacheService = class _CacheService {
3196
3325
  if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
3197
3326
  return count;
3198
3327
  } catch (err) {
3328
+ this.counters.counterErrors++;
3329
+ this.cb.onFailure();
3199
3330
  this.logger.error("increment: Redis error", { cacheKey }, err);
3331
+ if (this.opts.failClosed) throw err;
3200
3332
  return 0;
3201
3333
  }
3202
3334
  }
@@ -3370,7 +3502,8 @@ var CacheService = class _CacheService {
3370
3502
  const missIndexes = [];
3371
3503
  const missKeys = [];
3372
3504
  for (let i = 0; i < keys.length; i++) {
3373
- const entry = this.l1.getEntry(this.nk(keys[i]));
3505
+ const k = this.nk(keys[i]);
3506
+ const entry = this.l1.getEntry(k);
3374
3507
  if (entry && entry.expiresAt > Date.now()) {
3375
3508
  result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
3376
3509
  this.counters.l1Hits++;
@@ -3379,7 +3512,71 @@ var CacheService = class _CacheService {
3379
3512
  missKeys.push(keys[i]);
3380
3513
  }
3381
3514
  }
3515
+ if (missKeys.length === 0) return result;
3516
+ if (!this._redisDisabled) {
3517
+ try {
3518
+ const client = await this.getRedis();
3519
+ const nsKeys = missKeys.map((k) => this.nk(k));
3520
+ const pipeline = client.multi();
3521
+ for (const nk of nsKeys) pipeline.get(nk);
3522
+ const raws = await pipeline.exec();
3523
+ this.cb.onSuccess();
3524
+ for (let j = 0; j < missKeys.length; j++) {
3525
+ const raw = raws[j] ? raws[j][1] : null;
3526
+ const idx = missIndexes[j];
3527
+ if (raw) {
3528
+ let parsed;
3529
+ if (this.enc.isEnabled) {
3530
+ const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
3531
+ parsed = JSON.parse(decrypted);
3532
+ } else {
3533
+ parsed = JSON.parse(raw);
3534
+ }
3535
+ const k = nsKeys[j];
3536
+ const p = priority ?? inferPriority(missKeys[j]);
3537
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
3538
+ this.counters.l2Hits++;
3539
+ result[idx] = parsed;
3540
+ missIndexes[j] = -1;
3541
+ missKeys[j] = "";
3542
+ }
3543
+ }
3544
+ const remainingIdx = missIndexes.filter((i) => i >= 0);
3545
+ const remainingKeys = missKeys.filter((k) => k !== "");
3546
+ missIndexes.length = 0;
3547
+ missKeys.length = 0;
3548
+ missIndexes.push(...remainingIdx);
3549
+ missKeys.push(...remainingKeys);
3550
+ if (missKeys.length === 0) return result;
3551
+ } catch (err) {
3552
+ this.cb.onFailure();
3553
+ this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
3554
+ }
3555
+ }
3556
+ if (!this._diskDisabled) {
3557
+ for (let j = missKeys.length - 1; j >= 0; j--) {
3558
+ const k = this.nk(missKeys[j]);
3559
+ const diskHit = this.disk.load(k);
3560
+ if (diskHit !== null) {
3561
+ const promoted = this.l1.importEntries(
3562
+ [{ key: k, entry: diskHit }],
3563
+ this.opts.forbiddenSnapshotPrefixes
3564
+ );
3565
+ if (promoted > 0) {
3566
+ const l1Check = this.l1.get(k);
3567
+ if (l1Check !== null) {
3568
+ this.counters.diskHits++;
3569
+ result[missIndexes[j]] = l1Check.value;
3570
+ missIndexes.splice(j, 1);
3571
+ missKeys.splice(j, 1);
3572
+ }
3573
+ }
3574
+ }
3575
+ }
3576
+ if (missKeys.length === 0) return result;
3577
+ }
3382
3578
  if (missKeys.length > 0) {
3579
+ this.counters.fetches++;
3383
3580
  const fetched = await fetchFn(missKeys);
3384
3581
  for (let j = 0; j < missKeys.length; j++) {
3385
3582
  const v = fetched[missKeys[j]];
@@ -3469,7 +3666,7 @@ var CacheService = class _CacheService {
3469
3666
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3470
3667
  const parsed = JSON.parse(decrypted);
3471
3668
  const remainingMs = 10 * 60 * 1e3;
3472
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
3669
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3473
3670
  loaded++;
3474
3671
  ;
3475
3672
  } catch {
@@ -3745,6 +3942,10 @@ var CacheService = class _CacheService {
3745
3942
  sets: { total: c.sets },
3746
3943
  deletes: { total: c.deletes },
3747
3944
  revalidations: { total: c.swrRevalidations },
3945
+ counters: {
3946
+ errors: c.counterErrors,
3947
+ singletonDivergences: c.singletonDivergences
3948
+ },
3748
3949
  bloom: {
3749
3950
  checksTotal: l1s.bloom.checks,
3750
3951
  falsePositives: l1s.bloom.falsePositives,