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/README.md CHANGED
@@ -20,7 +20,7 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
20
20
  | Feature | Detail |
21
21
  |---|---|
22
22
  | **Adaptive eviction** | LFU × LRU × priority score + Count-Min Sketch cross-eviction frequency; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
23
- | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **78 % survival rate** in benchmark flood tests |
23
+ | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **84 % survival rate** in benchmark flood tests |
24
24
  | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
25
25
  | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
26
26
  | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
@@ -243,6 +243,15 @@ CacheService.create({
243
243
  adaptiveTtlMax: 86400, // ceiling: never exceed 24 h (default)
244
244
  adaptiveTtlMultiplier: 20, // p95Ms × 20 = TTL in seconds (default)
245
245
 
246
+ // ── Singleton + rate-limit safety ──────────────────────────────────────
247
+ // strictSingleton: when true, a later create() for an existing namespace
248
+ // whose options differ from the first call THROWS instead of silently
249
+ // returning the existing instance. Guards against conflicting init points.
250
+ strictSingleton: false,
251
+ // failClosed: when true, increment() re-throws on a Redis error instead of
252
+ // failing open (returning 0). Enforces the rate-limit guard during outages.
253
+ failClosed: false,
254
+
246
255
  // ── OpenTelemetry tracer ──────────────────────────────────────────────
247
256
  // Pass any @opentelemetry/api-compatible tracer. No peer dependency.
248
257
  // Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
@@ -310,7 +319,7 @@ CacheService.create({
310
319
 
311
320
  ### `CacheService.create(options?)` → `CacheService`
312
321
 
313
- Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance.
322
+ Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance. When the new options differ from what the existing singleton was built with, this is a **silent no-op by default** (a one-time warning is logged and the `singletonDivergences` metric is incremented). Set `strictSingleton: true` on the first call to instead **throw** on a divergent later call — use this when multiple init points could pass conflicting Redis credentials or TTLs.
314
323
 
315
324
  ### `CacheService.createAsync(optionsOrPromise)` → `Promise<CacheService>`
316
325
 
@@ -334,7 +343,7 @@ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` f
334
343
  |---|---|---|---|
335
344
  | `key` | `string` | — | Cache key |
336
345
  | `fetchFn` | `() => Promise<T>` | — | Called on a miss; result is cached |
337
- | `ttlSeconds` | `number` | `300` | Hard TTL in seconds |
346
+ | `ttlSeconds` | `number` | `300` | Hard TTL in seconds. **When `adaptiveTtl` is enabled, this is only authoritative until ≥ 5 samples are collected for the key — after that the library derives TTL from the p95 fetch latency** (see Adaptive TTL config). Use `opts` or a separate cache instance if you need a hard floor. |
338
347
  | `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
339
348
  | `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
340
349
  | `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
@@ -361,7 +370,7 @@ await cache.delete('org:42'); // org:42:members is evicted too
361
370
 
362
371
  ### `cache.mget<T>(keys, fetchFn, ttl?, priority?)` → `Promise<(T | undefined)[]>`
363
372
 
364
- Batch read. Returns L1-cached values for hot keys; calls `fetchFn` only with the keys that missed. Preserves input ordering.
373
+ Batch read. Checks **all three tiers** for each key — L1 (RAM), then L2 (Redis, in one pipelined `MGET`), then the L1.5 disk spill — and calls `fetchFn` only for keys that miss every tier. Preserves input ordering and counts exactly one hit per key (no double-counting across tiers).
365
374
 
366
375
  `ttl` accepts a **plain number** (uniform TTL) or a **function `(key: string) => number`** (per-key TTL). The function is only called for miss keys — L1 hits are unaffected.
367
376
 
@@ -528,7 +537,9 @@ cache.rebalance();
528
537
 
529
538
  ### `cache.increment(key, ttlSeconds?)` → `Promise<number>`
530
539
 
531
- Redis `INCR` — atomically increments a counter, setting TTL on first write. When Redis is disabled, maintains an in-process counter with the same TTL semantics so rate-limiting works in dev/test.
540
+ Distributed counter. With Redis active, atomically increments via `INCR` and returns the fleet-wide value. **By default it fails OPEN on a Redis error** — it returns `0`, so a caller's `if (count > LIMIT) reject()` guard will NOT reject during an outage. Set `failClosed: true` to re-throw the error instead, enforcing the limit even when Redis is unavailable. Track failures via `cache.metrics().counters.errors`.
541
+
542
+ When Redis is disabled, it maintains an **in-process** counter with the same TTL semantics so dev/test rate-limiting works — but rate-limiting is then per-instance, **not fleet-wide**. A one-time warning is logged the first time this fallback is used.
532
543
 
533
544
  ### `cache.metrics()` → `CacheMetrics`
534
545
 
@@ -834,10 +845,13 @@ ioredis monitors the current master via the Sentinel topology and transparently
834
845
 
835
846
  ## ⚡ WASM Bloom filter
836
847
 
837
- A 100,000-bit filter with k=7 hash probes:
848
+ A 100,000-bit filter with k=7 hash probes is used when it is large enough for the
849
+ configured `l1MaxEntries`; otherwise a right-sized pure-JS filter is instantiated
850
+ automatically (see `createBloomFilter`). For the default 100K-bit filter:
838
851
 
839
- - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.01%**
840
- - At rated capacity (~18,000 entries) — false-positive rate ≈ **1%**
852
+ - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.00007%** (m=100,000, k=7)
853
+ - At its rated capacity (~10,400 entries) — false-positive rate ≈ **1%**
854
+ - When `l1MaxEntries` exceeds the WASM filter's ~10,400-entry capacity, a JS filter sized via the optimal formula (m = ⌈–n·ln p / (ln 2)²⌉, k = round(ln 2 · m / n) clamped to [4, 10]) is used instead — no capacity cliff.
841
855
  - The filter rebuilds automatically when stale bits from deleted/expired entries accumulate
842
856
 
843
857
  Mechanics:
@@ -858,12 +872,12 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
858
872
  |---|---|---|---|
859
873
  | `get` — hot hit (8K entries) | **2.81 M/s** | 356 ns | bloom → Map lookup → return cached value |
860
874
  | `get` — cold miss | **7.14 M/s** | 140 ns | bloom gates → early return |
861
- | `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
862
- | `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
863
- | `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
864
- | `set` — CRITICAL priority | 730.1 K/s | 1.37 µs | same set path; skipped in eviction sort |
875
+ | `set` — tiny payload | 1.06 M/s | 944 ns | pack() + Map.set + bloom.add |
876
+ | `set` — small payload (< 512 B) | 574.1 K/s | 1.74 µs | pack() same unified path, larger payload |
877
+ | `set` — large payload (≥ 512 B) | 228.6 K/s | 4.37 µs | pack() larger payload |
878
+ | `set` — CRITICAL priority | 843.6 K/s | 1.19 µs | same set path; skipped in eviction sort |
865
879
  | `delete` — exact key | **5.36 M/s** | 186 ns | Map.delete |
866
- | `deletePattern` — glob wildcard | 7.2 K/s | 138 µs | O(n) Map scan |
880
+ | `deletePattern` — glob wildcard | 18.7 K/s | 53.48 µs | O(n) Map scan |
867
881
  | Count-Min Sketch estimate | **3.37 M/s** | 297 ns | 4 row lookups — called on every `get()` hit and `set()` |
868
882
 
869
883
  **Iterator interface (L1 live entries, 500 entries)**
@@ -148,6 +148,20 @@ var CacheEncryption = class {
148
148
  get isEnabled() {
149
149
  return this._key !== null;
150
150
  }
151
+ /**
152
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
153
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
154
+ * cast in cache-service.ts — the worker pool reads these via this accessor
155
+ * instead of reaching into underscore-prefixed internals.
156
+ */
157
+ toWorkerInit() {
158
+ return {
159
+ keyBase64: this._key ? this._key.toString("base64") : "",
160
+ mode: this._mode,
161
+ prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
162
+ prevMode: this._prevMode
163
+ };
164
+ }
151
165
  // ── String (Redis) ────────────────────────────────────────────────────────
152
166
  /**
153
167
  * Encrypt a string for Redis storage.
@@ -190,18 +204,18 @@ var CacheEncryption = class {
190
204
  */
191
205
  decrypt(value) {
192
206
  try {
193
- return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
207
+ return this._decryptWithKey(value, this._key, this._keyObj);
194
208
  } catch (primaryErr) {
195
209
  if (this._prevKey) {
196
210
  try {
197
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
211
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
198
212
  } catch {
199
213
  }
200
214
  }
201
215
  throw primaryErr;
202
216
  }
203
217
  }
204
- _decryptWithKey(value, key, keyObj, mode) {
218
+ _decryptWithKey(value, key, keyObj) {
205
219
  if (value.startsWith(PREFIX_XOR)) {
206
220
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
207
221
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -236,8 +250,6 @@ var CacheEncryption = class {
236
250
  const plain = d.update(ct);
237
251
  d.final();
238
252
  return plain.toString("utf8");
239
- void mode;
240
- void key;
241
253
  }
242
254
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
243
255
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
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,6 +2648,10 @@ 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;
@@ -3174,12 +3276,31 @@ var CacheService = class _CacheService {
3174
3276
  }
3175
3277
  // ── Counter (distributed rate limiting) ──────────────────────────────────
3176
3278
  /**
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).
3279
+ * Distributed counter.
3280
+ *
3281
+ * When Redis is active, atomically increments the key via `INCR` and returns
3282
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
3283
+ * and, by default, fails OPEN — returning `0` so a caller's
3284
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
3285
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
3286
+ * when Redis is unavailable.
3287
+ *
3288
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
3289
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
3290
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
3291
+ * a one-time warning is logged because rate-limiting is then per-instance, not
3292
+ * fleet-wide.
3179
3293
  */
3180
3294
  async increment(cacheKey, ttlSeconds) {
3181
3295
  const k = this.nk(cacheKey);
3182
3296
  if (this._redisDisabled) {
3297
+ if (!this._incrementFallbackWarned) {
3298
+ this._incrementFallbackWarned = true;
3299
+ this.logger.warn(
3300
+ "tricache: increment() using in-process counter \u2014 rate limiting is NOT fleet-wide (Redis disabled)",
3301
+ { cacheKey }
3302
+ );
3303
+ }
3183
3304
  const now = Date.now();
3184
3305
  const ttlMs = (ttlSeconds ?? 60) * 1e3;
3185
3306
  const entry = this._l1Counters.get(k);
@@ -3196,7 +3317,10 @@ var CacheService = class _CacheService {
3196
3317
  if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
3197
3318
  return count;
3198
3319
  } catch (err) {
3320
+ this.counters.counterErrors++;
3321
+ this.cb.onFailure();
3199
3322
  this.logger.error("increment: Redis error", { cacheKey }, err);
3323
+ if (this.opts.failClosed) throw err;
3200
3324
  return 0;
3201
3325
  }
3202
3326
  }
@@ -3370,7 +3494,8 @@ var CacheService = class _CacheService {
3370
3494
  const missIndexes = [];
3371
3495
  const missKeys = [];
3372
3496
  for (let i = 0; i < keys.length; i++) {
3373
- const entry = this.l1.getEntry(this.nk(keys[i]));
3497
+ const k = this.nk(keys[i]);
3498
+ const entry = this.l1.getEntry(k);
3374
3499
  if (entry && entry.expiresAt > Date.now()) {
3375
3500
  result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
3376
3501
  this.counters.l1Hits++;
@@ -3379,7 +3504,71 @@ var CacheService = class _CacheService {
3379
3504
  missKeys.push(keys[i]);
3380
3505
  }
3381
3506
  }
3507
+ if (missKeys.length === 0) return result;
3508
+ if (!this._redisDisabled) {
3509
+ try {
3510
+ const client = await this.getRedis();
3511
+ const nsKeys = missKeys.map((k) => this.nk(k));
3512
+ const pipeline = client.multi();
3513
+ for (const nk of nsKeys) pipeline.get(nk);
3514
+ const raws = await pipeline.exec();
3515
+ this.cb.onSuccess();
3516
+ for (let j = 0; j < missKeys.length; j++) {
3517
+ const raw = raws[j] ? raws[j][1] : null;
3518
+ const idx = missIndexes[j];
3519
+ if (raw) {
3520
+ let parsed;
3521
+ if (this.enc.isEnabled) {
3522
+ const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
3523
+ parsed = JSON.parse(decrypted);
3524
+ } else {
3525
+ parsed = JSON.parse(raw);
3526
+ }
3527
+ const k = nsKeys[j];
3528
+ const p = priority ?? inferPriority(missKeys[j]);
3529
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
3530
+ this.counters.l2Hits++;
3531
+ result[idx] = parsed;
3532
+ missIndexes[j] = -1;
3533
+ missKeys[j] = "";
3534
+ }
3535
+ }
3536
+ const remainingIdx = missIndexes.filter((i) => i >= 0);
3537
+ const remainingKeys = missKeys.filter((k) => k !== "");
3538
+ missIndexes.length = 0;
3539
+ missKeys.length = 0;
3540
+ missIndexes.push(...remainingIdx);
3541
+ missKeys.push(...remainingKeys);
3542
+ if (missKeys.length === 0) return result;
3543
+ } catch (err) {
3544
+ this.cb.onFailure();
3545
+ this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
3546
+ }
3547
+ }
3548
+ if (!this._diskDisabled) {
3549
+ for (let j = missKeys.length - 1; j >= 0; j--) {
3550
+ const k = this.nk(missKeys[j]);
3551
+ const diskHit = this.disk.load(k);
3552
+ if (diskHit !== null) {
3553
+ const promoted = this.l1.importEntries(
3554
+ [{ key: k, entry: diskHit }],
3555
+ this.opts.forbiddenSnapshotPrefixes
3556
+ );
3557
+ if (promoted > 0) {
3558
+ const l1Check = this.l1.get(k);
3559
+ if (l1Check !== null) {
3560
+ this.counters.diskHits++;
3561
+ result[missIndexes[j]] = l1Check.value;
3562
+ missIndexes.splice(j, 1);
3563
+ missKeys.splice(j, 1);
3564
+ }
3565
+ }
3566
+ }
3567
+ }
3568
+ if (missKeys.length === 0) return result;
3569
+ }
3382
3570
  if (missKeys.length > 0) {
3571
+ this.counters.fetches++;
3383
3572
  const fetched = await fetchFn(missKeys);
3384
3573
  for (let j = 0; j < missKeys.length; j++) {
3385
3574
  const v = fetched[missKeys[j]];
@@ -3469,7 +3658,7 @@ var CacheService = class _CacheService {
3469
3658
  const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
3470
3659
  const parsed = JSON.parse(decrypted);
3471
3660
  const remainingMs = 10 * 60 * 1e3;
3472
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
3661
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3473
3662
  loaded++;
3474
3663
  ;
3475
3664
  } catch {
@@ -3745,6 +3934,10 @@ var CacheService = class _CacheService {
3745
3934
  sets: { total: c.sets },
3746
3935
  deletes: { total: c.deletes },
3747
3936
  revalidations: { total: c.swrRevalidations },
3937
+ counters: {
3938
+ errors: c.counterErrors,
3939
+ singletonDivergences: c.singletonDivergences
3940
+ },
3748
3941
  bloom: {
3749
3942
  checksTotal: l1s.bloom.checks,
3750
3943
  falsePositives: l1s.bloom.falsePositives,