tricache 0.6.5 → 0.6.6

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.d.ts CHANGED
@@ -156,6 +156,13 @@ interface CacheMetrics {
156
156
  revalidations: {
157
157
  total: number;
158
158
  };
159
+ /** Rate-limit / singleton diagnostics */
160
+ counters: {
161
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
162
+ errors: number;
163
+ /** Times a later `create(ns)` call passed options diverging from the live singleton. */
164
+ singletonDivergences: number;
165
+ };
159
166
  bloom: {
160
167
  /** Total bloom-filter checks (get() calls that passed prefix filter) */
161
168
  checksTotal: number;
@@ -636,6 +643,25 @@ interface CacheOptions {
636
643
  port: number;
637
644
  }>;
638
645
  };
646
+ /**
647
+ * When `true`, a second `CacheService.create()` call for an already-existing
648
+ * singleton (same namespace) whose options differ from the first call throws
649
+ * instead of silently returning the existing instance. Use in codebases where
650
+ * multiple init points could pass conflicting configuration (e.g. different
651
+ * Redis credentials or TTLs) and you want that class of bug to fail loudly.
652
+ *
653
+ * Default: `false` (warn once, return existing instance).
654
+ */
655
+ strictSingleton?: boolean;
656
+ /**
657
+ * `cache.increment()` distributed-rate-limit behaviour on a Redis error.
658
+ *
659
+ * Default: `false` (fail-open — on a Redis error the method returns `0`, so a
660
+ * caller's `if (count > LIMIT) reject()` guard never rejects during an outage).
661
+ * Set to `true` to instead re-throw the Redis error, letting the caller's limit
662
+ * guard enforce the limit even when Redis is unavailable.
663
+ */
664
+ failClosed?: boolean;
639
665
  }
640
666
 
641
667
  /**
@@ -697,17 +723,34 @@ declare class CacheService {
697
723
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
698
724
  private _subDisconnectedAt;
699
725
  private readonly counters;
726
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
727
+ private _incrementFallbackWarned;
700
728
  constructor(options?: CacheOptions);
701
729
  /**
702
730
  * Get (or create) the process-level singleton CacheService instance.
703
731
  *
704
732
  * Options are only applied on first call — subsequent calls return the
705
- * existing instance regardless of options passed.
733
+ * existing instance regardless of options passed. When the new options differ
734
+ * from what the existing singleton was built with, this is a silent no-op by
735
+ * default; set `strictSingleton: true` to throw instead, or watch the
736
+ * `singletonDivergences` metric for detection.
706
737
  *
707
738
  * When `namespace` is set the singleton is keyed by namespace, so two calls
708
739
  * with different namespaces return independent instances.
709
740
  */
710
741
  static create(options?: CacheOptions): CacheService;
742
+ /**
743
+ * Keys that, if set differently on a later `create()` call, represent a
744
+ * meaningful configuration divergence worth flagging (security/correctness
745
+ * relevant — not cosmetic, e.g. log level).
746
+ */
747
+ private static readonly DIVERGENT_KEYS;
748
+ /** Returns the names of options that differ between `a` and the live `b`. */
749
+ private static optionsDiff;
750
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
751
+ bumpSingletonDivergence(): void;
752
+ /** Read-only view of the options the singleton was constructed with. */
753
+ get options(): CacheOptions;
711
754
  /**
712
755
  * Async factory — accepts a Promise that resolves to CacheOptions.
713
756
  * Useful when config is fetched from a secret store at startup.
@@ -728,6 +771,8 @@ declare class CacheService {
728
771
  * receive and provide un-prefixed keys in the public API.
729
772
  */
730
773
  private nk;
774
+ /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
775
+ private unnk;
731
776
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
732
777
  private _jitterTtl;
733
778
  /** Shared no-op span for the common case where no tracer is configured.
@@ -800,8 +845,20 @@ declare class CacheService {
800
845
  */
801
846
  delete(cacheKey: string): Promise<void>;
802
847
  /**
803
- * Atomically increment a counter in Redis. Returns the new value.
804
- * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
848
+ * Distributed counter.
849
+ *
850
+ * When Redis is active, atomically increments the key via `INCR` and returns
851
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
852
+ * and, by default, fails OPEN — returning `0` so a caller's
853
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
854
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
855
+ * when Redis is unavailable.
856
+ *
857
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
858
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
859
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
860
+ * a one-time warning is logged because rate-limiting is then per-instance, not
861
+ * fleet-wide.
805
862
  */
806
863
  increment(cacheKey: string, ttlSeconds?: number): Promise<number>;
807
864
  /**
@@ -1134,6 +1191,18 @@ declare class CacheEncryption {
1134
1191
  private _xorBuffer;
1135
1192
  constructor(keyBase64: string | undefined, logger: ILogger, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
1136
1193
  get isEnabled(): boolean;
1194
+ /**
1195
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
1196
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
1197
+ * cast in cache-service.ts — the worker pool reads these via this accessor
1198
+ * instead of reaching into underscore-prefixed internals.
1199
+ */
1200
+ toWorkerInit(): {
1201
+ keyBase64: string;
1202
+ mode: EncryptionMode;
1203
+ prevKeyBase64: string | undefined;
1204
+ prevMode: EncryptionMode;
1205
+ };
1137
1206
  /**
1138
1207
  * Encrypt a string for Redis storage.
1139
1208
  * Returns a mode-prefixed base64 string when a key is configured;
@@ -1409,7 +1478,10 @@ interface DiskTierOptions {
1409
1478
  maxBytes: number;
1410
1479
  entryMaxBytes: number;
1411
1480
  forbiddenPrefixes: readonly string[];
1412
- encryptionKey?: Buffer | null;
1481
+ /** Mode-aware encryption instance. When set, disk files are encrypted with the
1482
+ * same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
1483
+ * When null, files are written unencrypted. Pass `cache.encryption` here. */
1484
+ encryption?: CacheEncryption | null;
1413
1485
  logger: ILogger;
1414
1486
  }
1415
1487
  declare class DiskTier {
@@ -1477,15 +1549,16 @@ declare class DiskTier {
1477
1549
  private encrypt;
1478
1550
  private decrypt;
1479
1551
  /**
1480
- * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1481
- * the outer 16-byte header alongside the plaintext expiresAt).
1482
- * Returns the buffer unchanged when no encryption key is configured.
1552
+ * V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
1553
+ * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
1554
+ * Returns the buffer unchanged when no encryption instance is configured.
1483
1555
  */
1484
1556
  private encryptV2;
1485
1557
  /**
1486
1558
  * V2 decryption — inner payload after stripping the 16-byte header.
1487
- * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1488
- * without a key the payload is raw msgpack.
1559
+ * When an encryption instance is configured the format is the mode-aware
1560
+ * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
1561
+ * without one the payload is raw msgpack.
1489
1562
  */
1490
1563
  private decryptV2;
1491
1564
  /**
@@ -1561,8 +1634,8 @@ declare class WasmBloomFilter {
1561
1634
  get insertions(): number;
1562
1635
  /**
1563
1636
  * Maximum safe insertions before false-positive rate exceeds ~1 %.
1564
- * Exact formula for k=7 hash rounds, m=100 000 bits:
1565
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
1637
+ * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
1638
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
1566
1639
  */
1567
1640
  get maxCapacity(): number;
1568
1641
  }
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CacheEncryption
3
- } from "./chunk-IB4HMBA2.js";
3
+ } from "./chunk-FKY5R3CE.js";
4
4
 
5
5
  // src/cache-service.ts
6
6
  import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
@@ -199,8 +199,8 @@ var WasmBloomFilter = class {
199
199
  }
200
200
  /**
201
201
  * Maximum safe insertions before false-positive rate exceeds ~1 %.
202
- * Exact formula for k=7 hash rounds, m=100 000 bits:
203
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
202
+ * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
203
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
204
204
  */
205
205
  get maxCapacity() {
206
206
  return this._maxCapacity;
@@ -469,8 +469,8 @@ var SmartMemoryCache = class {
469
469
  const lim = this.getCategoryLimit(category);
470
470
  const catCnt = this.categoryCount.get(category) ?? 0;
471
471
  const catSz = this.categorySize.get(category) ?? 0;
472
- const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
473
- const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
472
+ let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
473
+ let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
474
474
  if (!catOvf && !glbOvf) {
475
475
  const wm = this.opts.evictionWatermark ?? 0.9;
476
476
  const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
@@ -480,7 +480,17 @@ var SmartMemoryCache = class {
480
480
  }
481
481
  return;
482
482
  }
483
- this.smartEvict(category, catOvf);
483
+ const MAX_EVICT_PASSES = 64;
484
+ let passes = 0;
485
+ do {
486
+ this.smartEvict(category, catOvf);
487
+ const lim2 = this.getCategoryLimit(category);
488
+ const catCnt2 = this.categoryCount.get(category) ?? 0;
489
+ const catSz2 = this.categorySize.get(category) ?? 0;
490
+ catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
491
+ glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
492
+ passes++;
493
+ } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
484
494
  }
485
495
  score(entry, catBonus, now, key) {
486
496
  const age = now - entry.lastAccess;
@@ -1028,9 +1038,6 @@ try {
1028
1038
  _SqliteDB = sqlite?.DatabaseSync ?? null;
1029
1039
  } catch {
1030
1040
  }
1031
- var AES_ALGO = "aes-256-gcm";
1032
- var IV_BYTES = 12;
1033
- var TAG_BYTES = 16;
1034
1041
  var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
1035
1042
  var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
1036
1043
  var V2_HEADER_LEN = 16;
@@ -1219,54 +1226,33 @@ var DiskTier = class {
1219
1226
  return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
1220
1227
  }
1221
1228
  encrypt(data) {
1222
- const key = this.opts.encryptionKey;
1223
- if (!key) return data;
1224
- const iv = crypto.randomBytes(IV_BYTES);
1225
- const c = crypto.createCipheriv(AES_ALGO, key, iv);
1226
- const enc = Buffer.concat([c.update(data), c.final()]);
1227
- const tag = c.getAuthTag();
1228
- return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
1229
+ if (!this.opts.encryption) return data;
1230
+ return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
1229
1231
  }
1230
1232
  decrypt(data) {
1231
1233
  const mLen = DISK_MAGIC.length;
1232
1234
  if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
1233
- const key = this.opts.encryptionKey;
1234
- if (!key) throw new Error("DiskTier: entry is encrypted but no key is set");
1235
- const iv = data.subarray(mLen, mLen + IV_BYTES);
1236
- const tag = data.subarray(mLen + IV_BYTES, mLen + IV_BYTES + TAG_BYTES);
1237
- const ct = data.subarray(mLen + IV_BYTES + TAG_BYTES);
1238
- const d = crypto.createDecipheriv(AES_ALGO, key, iv);
1239
- d.setAuthTag(tag);
1240
- return Buffer.concat([d.update(ct), d.final()]);
1235
+ if (!this.opts.encryption) throw new Error("DiskTier: entry is encrypted but no encryption configured");
1236
+ return this.opts.encryption.decryptBuffer(data.subarray(mLen));
1241
1237
  }
1242
1238
  /**
1243
- * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
1244
- * the outer 16-byte header alongside the plaintext expiresAt).
1245
- * Returns the buffer unchanged when no encryption key is configured.
1239
+ * V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
1240
+ * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
1241
+ * Returns the buffer unchanged when no encryption instance is configured.
1246
1242
  */
1247
1243
  encryptV2(data) {
1248
- const key = this.opts.encryptionKey;
1249
- if (!key) return data;
1250
- const iv = crypto.randomBytes(IV_BYTES);
1251
- const c = crypto.createCipheriv(AES_ALGO, key, iv);
1252
- const enc = Buffer.concat([c.update(data), c.final()]);
1253
- const tag = c.getAuthTag();
1254
- return Buffer.concat([iv, tag, enc]);
1244
+ if (!this.opts.encryption) return data;
1245
+ return this.opts.encryption.encryptBuffer(data);
1255
1246
  }
1256
1247
  /**
1257
1248
  * V2 decryption — inner payload after stripping the 16-byte header.
1258
- * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
1259
- * without a key the payload is raw msgpack.
1249
+ * When an encryption instance is configured the format is the mode-aware
1250
+ * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
1251
+ * without one the payload is raw msgpack.
1260
1252
  */
1261
1253
  decryptV2(inner) {
1262
- const key = this.opts.encryptionKey;
1263
- if (!key) return inner;
1264
- const iv = inner.subarray(0, IV_BYTES);
1265
- const tag = inner.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
1266
- const ct = inner.subarray(IV_BYTES + TAG_BYTES);
1267
- const d = crypto.createDecipheriv(AES_ALGO, key, iv);
1268
- d.setAuthTag(tag);
1269
- return Buffer.concat([d.update(ct), d.final()]);
1254
+ if (!this.opts.encryption) return inner;
1255
+ return this.opts.encryption.decryptBuffer(inner);
1270
1256
  }
1271
1257
  // ── Public API ────────────────────────────────────────────────────────────
1272
1258
  /**
@@ -1738,12 +1724,24 @@ var L2CircuitBreaker = class {
1738
1724
  state = 0 /* CLOSED */;
1739
1725
  failures = 0;
1740
1726
  openedAt = 0;
1741
- /** Call before each Redis attempt. Returns false when the circuit is open. */
1727
+ /** True while the single permitted HALF_OPEN probe is in flight. */
1728
+ probing = false;
1729
+ /**
1730
+ * Call before each Redis attempt. Returns false when the circuit is open.
1731
+ * In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
1732
+ * arriving while a probe is outstanding are rejected (return false) so a
1733
+ * recovering Redis node is not stampeded.
1734
+ */
1742
1735
  isAllowed() {
1743
1736
  if (this.state === 0 /* CLOSED */) return true;
1744
- if (this.state === 2 /* HALF_OPEN */) return true;
1737
+ if (this.state === 2 /* HALF_OPEN */) {
1738
+ if (this.probing) return false;
1739
+ this.probing = true;
1740
+ return true;
1741
+ }
1745
1742
  if (Date.now() - this.openedAt >= this.cooldownMs) {
1746
1743
  this.state = 2 /* HALF_OPEN */;
1744
+ this.probing = true;
1747
1745
  return true;
1748
1746
  }
1749
1747
  return false;
@@ -1751,11 +1749,13 @@ var L2CircuitBreaker = class {
1751
1749
  /** Call on Redis success. */
1752
1750
  onSuccess() {
1753
1751
  this.failures = 0;
1752
+ this.probing = false;
1754
1753
  this.state = 0 /* CLOSED */;
1755
1754
  }
1756
1755
  /** Call on Redis failure. */
1757
1756
  onFailure() {
1758
1757
  this.failures++;
1758
+ this.probing = false;
1759
1759
  if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
1760
1760
  this.state = 1 /* OPEN */;
1761
1761
  this.openedAt = Date.now();
@@ -1930,8 +1930,14 @@ var CacheService = class _CacheService {
1930
1930
  invSkipped: 0,
1931
1931
  oomEvictions: 0,
1932
1932
  oomLastAt: null,
1933
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
1934
+ counterErrors: 0,
1935
+ /** Times a later `create(ns)` call passed options differing from the live singleton. */
1936
+ singletonDivergences: 0,
1933
1937
  startedAt: Date.now()
1934
1938
  };
1939
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
1940
+ _incrementFallbackWarned = false;
1935
1941
  // ── Constructor (use CacheService.create() for the recommended singleton) ──
1936
1942
  constructor(options = {}) {
1937
1943
  const logger = options.logger ?? consoleLogger;
@@ -2002,7 +2008,9 @@ var CacheService = class _CacheService {
2002
2008
  backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
2003
2009
  disableDisk: options.disableDisk ?? false,
2004
2010
  redisClusterNodes: options.redisClusterNodes,
2005
- redisSentinel: options.redisSentinel
2011
+ redisSentinel: options.redisSentinel,
2012
+ strictSingleton: options.strictSingleton ?? false,
2013
+ failClosed: options.failClosed ?? false
2006
2014
  };
2007
2015
  const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
2008
2016
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
@@ -2031,7 +2039,7 @@ var CacheService = class _CacheService {
2031
2039
  maxBytes: this.opts.diskMaxBytes,
2032
2040
  entryMaxBytes: this.opts.diskEntryMaxBytes,
2033
2041
  forbiddenPrefixes,
2034
- encryptionKey: this.enc.isEnabled ? this.enc["_key"] : null,
2042
+ encryption: this.enc.isEnabled ? this.enc : null,
2035
2043
  logger
2036
2044
  });
2037
2045
  this._namespace = ns;
@@ -2062,12 +2070,12 @@ var CacheService = class _CacheService {
2062
2070
  process.once("SIGINT", this._shutdownHandler);
2063
2071
  if (this.opts.workerThreads && this.enc.isEnabled) {
2064
2072
  try {
2065
- const encRef = this.enc;
2073
+ const encRef = this.enc.toWorkerInit();
2066
2074
  this._workerPool = new WorkerPool({
2067
- keyBase64: encRef._key ? encRef._key.toString("base64") : "",
2068
- mode: encRef._mode,
2069
- prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString("base64") : void 0,
2070
- prevMode: encRef._prevMode,
2075
+ keyBase64: encRef.keyBase64,
2076
+ mode: encRef.mode,
2077
+ prevKeyBase64: encRef.prevKeyBase64,
2078
+ prevMode: encRef.prevMode,
2071
2079
  size: this.opts.workerPoolSize || void 0
2072
2080
  });
2073
2081
  if (this._workerPool.isAvailable) {
@@ -2133,7 +2141,10 @@ var CacheService = class _CacheService {
2133
2141
  * Get (or create) the process-level singleton CacheService instance.
2134
2142
  *
2135
2143
  * Options are only applied on first call — subsequent calls return the
2136
- * existing instance regardless of options passed.
2144
+ * existing instance regardless of options passed. When the new options differ
2145
+ * from what the existing singleton was built with, this is a silent no-op by
2146
+ * default; set `strictSingleton: true` to throw instead, or watch the
2147
+ * `singletonDivergences` metric for detection.
2137
2148
  *
2138
2149
  * When `namespace` is set the singleton is keyed by namespace, so two calls
2139
2150
  * with different namespaces return independent instances.
@@ -2141,8 +2152,83 @@ var CacheService = class _CacheService {
2141
2152
  static create(options) {
2142
2153
  const g = globalThis;
2143
2154
  const key = _CacheService.globalKey(options);
2144
- if (!g[key]) g[key] = new _CacheService(options);
2145
- return g[key];
2155
+ if (!g[key]) {
2156
+ g[key] = new _CacheService(options);
2157
+ return g[key];
2158
+ }
2159
+ const existing = g[key];
2160
+ const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
2161
+ if (diff.length > 0) {
2162
+ existing.bumpSingletonDivergence();
2163
+ const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
2164
+ if (existing.options.strictSingleton) {
2165
+ throw new Error(`strictSingleton: ${msg}`);
2166
+ }
2167
+ (existing.options.logger ?? consoleLogger).warn(msg, { divergentOptions: diff });
2168
+ }
2169
+ return existing;
2170
+ }
2171
+ /**
2172
+ * Keys that, if set differently on a later `create()` call, represent a
2173
+ * meaningful configuration divergence worth flagging (security/correctness
2174
+ * relevant — not cosmetic, e.g. log level).
2175
+ */
2176
+ static DIVERGENT_KEYS = [
2177
+ "redisHost",
2178
+ "redisPort",
2179
+ "redisTls",
2180
+ "disableRedis",
2181
+ "redisClusterNodes",
2182
+ "redisSentinel",
2183
+ "encryptionKey",
2184
+ "encryptionMode",
2185
+ "l1MaxBytes",
2186
+ "l1MaxEntries",
2187
+ "namespace",
2188
+ "frozen",
2189
+ "adaptiveTtl",
2190
+ "l2WriteMode",
2191
+ "instanceName",
2192
+ "invalidationBackplane"
2193
+ ];
2194
+ /** Returns the names of options that differ between `a` and the live `b`. */
2195
+ static optionsDiff(a, b) {
2196
+ const out = [];
2197
+ for (const k of _CacheService.DIVERGENT_KEYS) {
2198
+ const av = a[k];
2199
+ const bv = b[k];
2200
+ if (av === void 0) continue;
2201
+ const same = JSON.stringify(av) === JSON.stringify(bv) || k === "encryptionKey" && av === bv;
2202
+ if (!same) out.push(String(k));
2203
+ }
2204
+ return out;
2205
+ }
2206
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
2207
+ bumpSingletonDivergence() {
2208
+ this.counters.singletonDivergences++;
2209
+ }
2210
+ /** Read-only view of the options the singleton was constructed with. */
2211
+ get options() {
2212
+ const o = this.opts;
2213
+ return {
2214
+ namespace: o.namespace,
2215
+ logger: o.logger,
2216
+ l1MaxBytes: o.l1MaxBytes,
2217
+ l1MaxEntries: o.l1MaxEntries,
2218
+ redisHost: o.redisHost,
2219
+ redisPort: o.redisPort,
2220
+ redisTls: o.redisTls,
2221
+ disableRedis: this._redisDisabled,
2222
+ redisClusterNodes: o.redisClusterNodes,
2223
+ redisSentinel: o.redisSentinel,
2224
+ encryptionKey: o.encryptionKey,
2225
+ l2WriteMode: o.l2WriteMode,
2226
+ instanceName: o.instanceName,
2227
+ frozen: o.frozen,
2228
+ adaptiveTtl: o.adaptiveTtl,
2229
+ invalidationBackplane: o.invalidationBackplane,
2230
+ strictSingleton: o.strictSingleton
2231
+ };
2146
2232
  }
2147
2233
  /**
2148
2234
  * Async factory — accepts a Promise that resolves to CacheOptions.
@@ -2180,6 +2266,10 @@ var CacheService = class _CacheService {
2180
2266
  nk(key) {
2181
2267
  return this._namespace ? `${this._namespace}:${key}` : key;
2182
2268
  }
2269
+ /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
2270
+ unnk(key) {
2271
+ return this._namespace ? key.slice(this._namespace.length + 1) : key;
2272
+ }
2183
2273
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
2184
2274
  _jitterTtl(ttlMs) {
2185
2275
  const j = this.opts.ttlJitterFactor;
@@ -2804,12 +2894,31 @@ var CacheService = class _CacheService {
2804
2894
  }
2805
2895
  // ── Counter (distributed rate limiting) ──────────────────────────────────
2806
2896
  /**
2807
- * Atomically increment a counter in Redis. Returns the new value.
2808
- * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
2897
+ * Distributed counter.
2898
+ *
2899
+ * When Redis is active, atomically increments the key via `INCR` and returns
2900
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
2901
+ * and, by default, fails OPEN — returning `0` so a caller's
2902
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
2903
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
2904
+ * when Redis is unavailable.
2905
+ *
2906
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
2907
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
2908
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
2909
+ * a one-time warning is logged because rate-limiting is then per-instance, not
2910
+ * fleet-wide.
2809
2911
  */
2810
2912
  async increment(cacheKey, ttlSeconds) {
2811
2913
  const k = this.nk(cacheKey);
2812
2914
  if (this._redisDisabled) {
2915
+ if (!this._incrementFallbackWarned) {
2916
+ this._incrementFallbackWarned = true;
2917
+ this.logger.warn(
2918
+ "tricache: increment() using in-process counter \u2014 rate limiting is NOT fleet-wide (Redis disabled)",
2919
+ { cacheKey }
2920
+ );
2921
+ }
2813
2922
  const now = Date.now();
2814
2923
  const ttlMs = (ttlSeconds ?? 60) * 1e3;
2815
2924
  const entry = this._l1Counters.get(k);
@@ -2826,7 +2935,10 @@ var CacheService = class _CacheService {
2826
2935
  if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
2827
2936
  return count;
2828
2937
  } catch (err) {
2938
+ this.counters.counterErrors++;
2939
+ this.cb.onFailure();
2829
2940
  this.logger.error("increment: Redis error", { cacheKey }, err);
2941
+ if (this.opts.failClosed) throw err;
2830
2942
  return 0;
2831
2943
  }
2832
2944
  }
@@ -3000,7 +3112,8 @@ var CacheService = class _CacheService {
3000
3112
  const missIndexes = [];
3001
3113
  const missKeys = [];
3002
3114
  for (let i = 0; i < keys.length; i++) {
3003
- const entry = this.l1.getEntry(this.nk(keys[i]));
3115
+ const k = this.nk(keys[i]);
3116
+ const entry = this.l1.getEntry(k);
3004
3117
  if (entry && entry.expiresAt > Date.now()) {
3005
3118
  result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
3006
3119
  this.counters.l1Hits++;
@@ -3009,7 +3122,71 @@ var CacheService = class _CacheService {
3009
3122
  missKeys.push(keys[i]);
3010
3123
  }
3011
3124
  }
3125
+ if (missKeys.length === 0) return result;
3126
+ if (!this._redisDisabled) {
3127
+ try {
3128
+ const client = await this.getRedis();
3129
+ const nsKeys = missKeys.map((k) => this.nk(k));
3130
+ const pipeline = client.multi();
3131
+ for (const nk of nsKeys) pipeline.get(nk);
3132
+ const raws = await pipeline.exec();
3133
+ this.cb.onSuccess();
3134
+ for (let j = 0; j < missKeys.length; j++) {
3135
+ const raw = raws[j] ? raws[j][1] : null;
3136
+ const idx = missIndexes[j];
3137
+ if (raw) {
3138
+ let parsed;
3139
+ if (this.enc.isEnabled) {
3140
+ const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
3141
+ parsed = JSON.parse(decrypted);
3142
+ } else {
3143
+ parsed = JSON.parse(raw);
3144
+ }
3145
+ const k = nsKeys[j];
3146
+ const p = priority ?? inferPriority(missKeys[j]);
3147
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
3148
+ this.counters.l2Hits++;
3149
+ result[idx] = parsed;
3150
+ missIndexes[j] = -1;
3151
+ missKeys[j] = "";
3152
+ }
3153
+ }
3154
+ const remainingIdx = missIndexes.filter((i) => i >= 0);
3155
+ const remainingKeys = missKeys.filter((k) => k !== "");
3156
+ missIndexes.length = 0;
3157
+ missKeys.length = 0;
3158
+ missIndexes.push(...remainingIdx);
3159
+ missKeys.push(...remainingKeys);
3160
+ if (missKeys.length === 0) return result;
3161
+ } catch (err) {
3162
+ this.cb.onFailure();
3163
+ this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
3164
+ }
3165
+ }
3166
+ if (!this._diskDisabled) {
3167
+ for (let j = missKeys.length - 1; j >= 0; j--) {
3168
+ const k = this.nk(missKeys[j]);
3169
+ const diskHit = this.disk.load(k);
3170
+ if (diskHit !== null) {
3171
+ const promoted = this.l1.importEntries(
3172
+ [{ key: k, entry: diskHit }],
3173
+ this.opts.forbiddenSnapshotPrefixes
3174
+ );
3175
+ if (promoted > 0) {
3176
+ const l1Check = this.l1.get(k);
3177
+ if (l1Check !== null) {
3178
+ this.counters.diskHits++;
3179
+ result[missIndexes[j]] = l1Check.value;
3180
+ missIndexes.splice(j, 1);
3181
+ missKeys.splice(j, 1);
3182
+ }
3183
+ }
3184
+ }
3185
+ }
3186
+ if (missKeys.length === 0) return result;
3187
+ }
3012
3188
  if (missKeys.length > 0) {
3189
+ this.counters.fetches++;
3013
3190
  const fetched = await fetchFn(missKeys);
3014
3191
  for (let j = 0; j < missKeys.length; j++) {
3015
3192
  const v = fetched[missKeys[j]];
@@ -3099,7 +3276,7 @@ var CacheService = class _CacheService {
3099
3276
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3100
3277
  const parsed = JSON.parse(decrypted);
3101
3278
  const remainingMs = 10 * 60 * 1e3;
3102
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
3279
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3103
3280
  loaded++;
3104
3281
  ;
3105
3282
  } catch {
@@ -3375,6 +3552,10 @@ var CacheService = class _CacheService {
3375
3552
  sets: { total: c.sets },
3376
3553
  deletes: { total: c.deletes },
3377
3554
  revalidations: { total: c.swrRevalidations },
3555
+ counters: {
3556
+ errors: c.counterErrors,
3557
+ singletonDivergences: c.singletonDivergences
3558
+ },
3378
3559
  bloom: {
3379
3560
  checksTotal: l1s.bloom.checks,
3380
3561
  falsePositives: l1s.bloom.falsePositives,