tricache 0.6.4 → 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.
@@ -69,18 +69,30 @@ class L2CircuitBreaker {
69
69
  private state = CBState.CLOSED;
70
70
  private failures = 0;
71
71
  private openedAt = 0;
72
+ /** True while the single permitted HALF_OPEN probe is in flight. */
73
+ private probing = false;
72
74
  constructor(
73
75
  private readonly threshold: number,
74
76
  private readonly cooldownMs: number,
75
77
  ) {}
76
78
 
77
- /** Call before each Redis attempt. Returns false when the circuit is open. */
79
+ /**
80
+ * Call before each Redis attempt. Returns false when the circuit is open.
81
+ * In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
82
+ * arriving while a probe is outstanding are rejected (return false) so a
83
+ * recovering Redis node is not stampeded.
84
+ */
78
85
  isAllowed(): boolean {
79
86
  if (this.state === CBState.CLOSED) return true;
80
- if (this.state === CBState.HALF_OPEN) return true; // one probe allowed
87
+ if (this.state === CBState.HALF_OPEN) {
88
+ if (this.probing) return false; // a probe is already in flight
89
+ this.probing = true;
90
+ return true; // this caller is the one permitted probe
91
+ }
81
92
  // OPEN: check if cooldown elapsed
82
93
  if (Date.now() - this.openedAt >= this.cooldownMs) {
83
- this.state = CBState.HALF_OPEN;
94
+ this.state = CBState.HALF_OPEN;
95
+ this.probing = true;
84
96
  return true; // probe
85
97
  }
86
98
  return false;
@@ -89,12 +101,14 @@ class L2CircuitBreaker {
89
101
  /** Call on Redis success. */
90
102
  onSuccess(): void {
91
103
  this.failures = 0;
104
+ this.probing = false;
92
105
  this.state = CBState.CLOSED;
93
106
  }
94
107
 
95
108
  /** Call on Redis failure. */
96
109
  onFailure(): void {
97
110
  this.failures++;
111
+ this.probing = false;
98
112
  if (this.state === CBState.HALF_OPEN || this.failures >= this.threshold) {
99
113
  this.state = CBState.OPEN;
100
114
  this.openedAt = Date.now();
@@ -324,6 +338,8 @@ export class CacheService {
324
338
  disableDisk: boolean;
325
339
  redisClusterNodes: Array<{ host: string; port: number }> | undefined;
326
340
  redisSentinel: { name: string; sentinels: Array<{ host: string; port: number }> } | undefined;
341
+ strictSingleton: boolean;
342
+ failClosed: boolean;
327
343
  };
328
344
  /** Pre-computed once — opts.namespace never changes after construction. */
329
345
  private readonly _namespace: string;
@@ -370,9 +386,16 @@ export class CacheService {
370
386
  invSkipped: 0,
371
387
  oomEvictions: 0,
372
388
  oomLastAt: null as number | null,
389
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
390
+ counterErrors: 0,
391
+ /** Times a later `create(ns)` call passed options differing from the live singleton. */
392
+ singletonDivergences: 0,
373
393
  startedAt: Date.now(),
374
394
  };
375
395
 
396
+ /** One-time guard so the in-process increment() fallback warning fires only once. */
397
+ private _incrementFallbackWarned = false;
398
+
376
399
  // ── Constructor (use CacheService.create() for the recommended singleton) ──
377
400
 
378
401
  constructor(options: CacheOptions = {}) {
@@ -450,6 +473,8 @@ export class CacheService {
450
473
  disableDisk: options.disableDisk ?? false,
451
474
  redisClusterNodes: options.redisClusterNodes,
452
475
  redisSentinel: options.redisSentinel,
476
+ strictSingleton: options.strictSingleton ?? false,
477
+ failClosed: options.failClosed ?? false,
453
478
  };
454
479
 
455
480
  // Circuit breaker for L2 Redis
@@ -487,7 +512,7 @@ export class CacheService {
487
512
  maxBytes: this.opts.diskMaxBytes,
488
513
  entryMaxBytes: this.opts.diskEntryMaxBytes,
489
514
  forbiddenPrefixes: forbiddenPrefixes,
490
- encryptionKey: this.enc.isEnabled ? (this.enc as unknown as { _key: Buffer })['_key'] : null,
515
+ encryption: this.enc.isEnabled ? this.enc : null,
491
516
  logger,
492
517
  });
493
518
 
@@ -529,17 +554,12 @@ export class CacheService {
529
554
  // ── Fix 1: Worker thread pool for off-main-thread AES-GCM ────────────────
530
555
  if (this.opts.workerThreads && this.enc.isEnabled) {
531
556
  try {
532
- const encRef = this.enc as unknown as {
533
- _key: Buffer | null;
534
- _mode: string;
535
- _prevKey: Buffer | null;
536
- _prevMode: string;
537
- };
557
+ const encRef = this.enc.toWorkerInit();
538
558
  this._workerPool = new WorkerPool({
539
- keyBase64: encRef._key ? encRef._key.toString('base64') : '',
540
- mode: encRef._mode as never,
541
- prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString('base64') : undefined,
542
- prevMode: encRef._prevMode as never,
559
+ keyBase64: encRef.keyBase64,
560
+ mode: encRef.mode as never,
561
+ prevKeyBase64: encRef.prevKeyBase64,
562
+ prevMode: encRef.prevMode as never,
543
563
  size: this.opts.workerPoolSize || undefined,
544
564
  });
545
565
  if (this._workerPool.isAvailable) {
@@ -618,7 +638,10 @@ export class CacheService {
618
638
  * Get (or create) the process-level singleton CacheService instance.
619
639
  *
620
640
  * Options are only applied on first call — subsequent calls return the
621
- * existing instance regardless of options passed.
641
+ * existing instance regardless of options passed. When the new options differ
642
+ * from what the existing singleton was built with, this is a silent no-op by
643
+ * default; set `strictSingleton: true` to throw instead, or watch the
644
+ * `singletonDivergences` metric for detection.
622
645
  *
623
646
  * When `namespace` is set the singleton is keyed by namespace, so two calls
624
647
  * with different namespaces return independent instances.
@@ -626,8 +649,80 @@ export class CacheService {
626
649
  static create(options?: CacheOptions): CacheService {
627
650
  const g = globalThis as Record<string, unknown>;
628
651
  const key = CacheService.globalKey(options);
629
- if (!g[key]) g[key] = new CacheService(options);
630
- return g[key] as CacheService;
652
+ if (!g[key]) {
653
+ g[key] = new CacheService(options);
654
+ return g[key] as CacheService;
655
+ }
656
+
657
+ // Singleton already exists for this namespace — detect & surface divergence.
658
+ const existing = g[key] as CacheService;
659
+ const diff = CacheService.optionsDiff(options ?? {}, existing.options);
660
+ if (diff.length > 0) {
661
+ existing.bumpSingletonDivergence();
662
+ const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || '(default)'}' — ignoring divergent options: ${diff.join(', ')}`;
663
+ if (existing.options.strictSingleton) {
664
+ throw new Error(`strictSingleton: ${msg}`);
665
+ }
666
+ (existing.options.logger ?? consoleLogger).warn(msg, { divergentOptions: diff });
667
+ }
668
+ return existing;
669
+ }
670
+
671
+ /**
672
+ * Keys that, if set differently on a later `create()` call, represent a
673
+ * meaningful configuration divergence worth flagging (security/correctness
674
+ * relevant — not cosmetic, e.g. log level).
675
+ */
676
+ private static readonly DIVERGENT_KEYS: Array<keyof CacheOptions> = [
677
+ 'redisHost', 'redisPort', 'redisTls', 'disableRedis',
678
+ 'redisClusterNodes', 'redisSentinel', 'encryptionKey', 'encryptionMode',
679
+ 'l1MaxBytes', 'l1MaxEntries', 'namespace', 'frozen', 'adaptiveTtl',
680
+ 'l2WriteMode', 'instanceName', 'invalidationBackplane',
681
+ ];
682
+
683
+ /** Returns the names of options that differ between `a` and the live `b`. */
684
+ private static optionsDiff(a: CacheOptions, b: CacheOptions): string[] {
685
+ const out: string[] = [];
686
+ for (const k of CacheService.DIVERGENT_KEYS) {
687
+ const av = a[k];
688
+ const bv = (b as Record<string, unknown>)[k as string];
689
+ // Treat undefined (not passed) as "no opinion" — only flag explicit conflicts.
690
+ if (av === undefined) continue;
691
+ const same =
692
+ JSON.stringify(av) === JSON.stringify(bv) ||
693
+ (k === 'encryptionKey' && av === bv);
694
+ if (!same) out.push(String(k));
695
+ }
696
+ return out;
697
+ }
698
+
699
+ /** Increment the singleton-divergence counter (surfaced in `metrics()`). */
700
+ bumpSingletonDivergence(): void {
701
+ this.counters.singletonDivergences++;
702
+ }
703
+
704
+ /** Read-only view of the options the singleton was constructed with. */
705
+ get options(): CacheOptions {
706
+ const o = this.opts;
707
+ return {
708
+ namespace: o.namespace,
709
+ logger: o.logger,
710
+ l1MaxBytes: o.l1MaxBytes,
711
+ l1MaxEntries: o.l1MaxEntries,
712
+ redisHost: o.redisHost,
713
+ redisPort: o.redisPort,
714
+ redisTls: o.redisTls,
715
+ disableRedis: this._redisDisabled,
716
+ redisClusterNodes: o.redisClusterNodes,
717
+ redisSentinel: o.redisSentinel,
718
+ encryptionKey: o.encryptionKey,
719
+ l2WriteMode: o.l2WriteMode,
720
+ instanceName: o.instanceName,
721
+ frozen: o.frozen,
722
+ adaptiveTtl: o.adaptiveTtl,
723
+ invalidationBackplane: o.invalidationBackplane,
724
+ strictSingleton: o.strictSingleton,
725
+ };
631
726
  }
632
727
 
633
728
  /**
@@ -671,6 +766,11 @@ export class CacheService {
671
766
  return this._namespace ? `${this._namespace}:${key}` : key;
672
767
  }
673
768
 
769
+ /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
770
+ private unnk(key: string): string {
771
+ return this._namespace ? key.slice(this._namespace.length + 1) : key;
772
+ }
773
+
674
774
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
675
775
  private _jitterTtl(ttlMs: number): number {
676
776
  const j = this.opts.ttlJitterFactor;
@@ -1421,13 +1521,32 @@ export class CacheService {
1421
1521
  // ── Counter (distributed rate limiting) ──────────────────────────────────
1422
1522
 
1423
1523
  /**
1424
- * Atomically increment a counter in Redis. Returns the new value.
1425
- * Returns 0 if Redis is disabled (safe fallback — rate limiting won't block in dev).
1524
+ * Distributed counter.
1525
+ *
1526
+ * When Redis is active, atomically increments the key via `INCR` and returns
1527
+ * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
1528
+ * and, by default, fails OPEN — returning `0` so a caller's
1529
+ * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
1530
+ * `failClosed: true` to re-throw the error instead, enforcing the limit even
1531
+ * when Redis is unavailable.
1532
+ *
1533
+ * When Redis is disabled (or `disableRedis: true`), this maintains an
1534
+ * IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
1535
+ * works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
1536
+ * a one-time warning is logged because rate-limiting is then per-instance, not
1537
+ * fleet-wide.
1426
1538
  */
1427
1539
  async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
1428
1540
  const k = this.nk(cacheKey);
1429
1541
 
1430
1542
  if (this._redisDisabled) {
1543
+ if (!this._incrementFallbackWarned) {
1544
+ this._incrementFallbackWarned = true;
1545
+ this.logger.warn(
1546
+ 'tricache: increment() using in-process counter — rate limiting is NOT fleet-wide (Redis disabled)',
1547
+ { cacheKey },
1548
+ );
1549
+ }
1431
1550
  const now = Date.now();
1432
1551
  const ttlMs = (ttlSeconds ?? 60) * 1_000;
1433
1552
  const entry = this._l1Counters.get(k);
@@ -1445,7 +1564,10 @@ export class CacheService {
1445
1564
  if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
1446
1565
  return count;
1447
1566
  } catch (err) {
1567
+ this.counters.counterErrors++;
1568
+ this.cb.onFailure();
1448
1569
  this.logger.error('increment: Redis error', { cacheKey }, err as Error);
1570
+ if (this.opts.failClosed) throw err;
1449
1571
  return 0;
1450
1572
  }
1451
1573
  }
@@ -1642,8 +1764,10 @@ export class CacheService {
1642
1764
  const missIndexes: number[] = [];
1643
1765
  const missKeys: string[] = [];
1644
1766
 
1767
+ // ── Tier 1: L1 (in-memory) ──
1645
1768
  for (let i = 0; i < keys.length; i++) {
1646
- const entry = this.l1.getEntry(this.nk(keys[i]));
1769
+ const k = this.nk(keys[i]);
1770
+ const entry = this.l1.getEntry(k);
1647
1771
  if (entry && entry.expiresAt > Date.now()) {
1648
1772
  result[i] = (entry.value !== undefined ? entry.value : unpack(entry.data)) as T;
1649
1773
  this.counters.l1Hits++;
@@ -1653,7 +1777,85 @@ export class CacheService {
1653
1777
  }
1654
1778
  }
1655
1779
 
1780
+ if (missKeys.length === 0) return result;
1781
+
1782
+ // ── Tier 2: L2 (Redis) — fetch all remaining misses in one pipeline ──
1783
+ if (!this._redisDisabled) {
1784
+ try {
1785
+ const client = await this.getRedis();
1786
+ const nsKeys = missKeys.map(k => this.nk(k));
1787
+ const pipeline = client.multi();
1788
+ for (const nk of nsKeys) pipeline.get(nk);
1789
+ const raws = await pipeline.exec() as Array<[Error | null, string | null] | null>;
1790
+ this.cb.onSuccess();
1791
+ for (let j = 0; j < missKeys.length; j++) {
1792
+ const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
1793
+ const idx = missIndexes[j];
1794
+ if (raw) {
1795
+ let parsed: T;
1796
+ if (this.enc.isEnabled) {
1797
+ const decrypted = (this._workerPool && raw.length > this.opts.workerThresholdBytes)
1798
+ ? await this._workerPool.decrypt(raw)
1799
+ : this.enc.decrypt(raw);
1800
+ parsed = JSON.parse(decrypted) as T;
1801
+ } else {
1802
+ parsed = JSON.parse(raw) as T;
1803
+ }
1804
+ const k = nsKeys[j];
1805
+ const p = priority ?? inferPriority(missKeys[j]);
1806
+ this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
1807
+ this.counters.l2Hits++;
1808
+ result[idx] = parsed;
1809
+ // Mark this miss slot as resolved (position j in the parallel arrays).
1810
+ // NOTE: must use j here, NOT idx — idx is the value (an index into the
1811
+ // original keys[]), which only equals j when missIndexes is contiguous
1812
+ // (every key missed). With interleaved L1 hits, missIndexes is sparse
1813
+ // and missIndexes[idx] would clobber an unrelated slot.
1814
+ missIndexes[j] = -1;
1815
+ missKeys[j] = '';
1816
+ }
1817
+ }
1818
+ // Compact the still-missing arrays.
1819
+ const remainingIdx = missIndexes.filter(i => i >= 0);
1820
+ const remainingKeys = missKeys.filter(k => k !== '');
1821
+ missIndexes.length = 0; missKeys.length = 0;
1822
+ missIndexes.push(...remainingIdx);
1823
+ missKeys.push(...remainingKeys);
1824
+ if (missKeys.length === 0) return result;
1825
+ } catch (err) {
1826
+ this.cb.onFailure();
1827
+ this.logger.debug('mget: Redis unavailable, continuing to disk/fetch', { error: (err as Error).message });
1828
+ }
1829
+ }
1830
+
1831
+ // ── Tier 1.5: disk spill (evicted L1 entries) ──
1832
+ if (!this._diskDisabled) {
1833
+ for (let j = missKeys.length - 1; j >= 0; j--) {
1834
+ const k = this.nk(missKeys[j]);
1835
+ const diskHit = this.disk.load(k);
1836
+ if (diskHit !== null) {
1837
+ const promoted = this.l1.importEntries(
1838
+ [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
1839
+ this.opts.forbiddenSnapshotPrefixes,
1840
+ );
1841
+ if (promoted > 0) {
1842
+ const l1Check = this.l1.get(k);
1843
+ if (l1Check !== null) {
1844
+ this.counters.diskHits++;
1845
+ result[missIndexes[j]] = l1Check.value as T;
1846
+ // Remove from miss set.
1847
+ missIndexes.splice(j, 1);
1848
+ missKeys.splice(j, 1);
1849
+ }
1850
+ }
1851
+ }
1852
+ }
1853
+ if (missKeys.length === 0) return result;
1854
+ }
1855
+
1856
+ // ── Tier 3: fetchFn for whatever still missed ──
1656
1857
  if (missKeys.length > 0) {
1858
+ this.counters.fetches++;
1657
1859
  const fetched = await fetchFn(missKeys);
1658
1860
  for (let j = 0; j < missKeys.length; j++) {
1659
1861
  const v = fetched[missKeys[j]];
@@ -1758,7 +1960,7 @@ export class CacheService {
1758
1960
  // Use a 10-minute TTL as a reasonable default; the real TTL is not
1759
1961
  // returned by GET (use PTTL to be precise, but that doubles round-trips).
1760
1962
  const remainingMs = 10 * 60 * 1_000;
1761
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
1963
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
1762
1964
  loaded++;;
1763
1965
  } catch { /* skip malformed entries */ }
1764
1966
  }
@@ -2065,6 +2267,10 @@ export class CacheService {
2065
2267
  sets: { total: c.sets },
2066
2268
  deletes: { total: c.deletes },
2067
2269
  revalidations: { total: c.swrRevalidations },
2270
+ counters: {
2271
+ errors: c.counterErrors,
2272
+ singletonDivergences: c.singletonDivergences,
2273
+ },
2068
2274
 
2069
2275
  bloom: {
2070
2276
  checksTotal: l1s.bloom.checks,
package/src/disk-tier.ts CHANGED
@@ -17,9 +17,9 @@
17
17
  import fs from 'fs';
18
18
  import path from 'path';
19
19
  import crypto from 'crypto';
20
- import { createRequire } from 'module';
21
20
  import { pack, unpack } from 'msgpackr';
22
21
  import { DiskCacheEntry, ILogger } from './types.js';
22
+ import { CacheEncryption } from './encryption.js';
23
23
 
24
24
  // ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
25
25
  // Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
@@ -37,14 +37,18 @@ type _SqliteDB = {
37
37
  };
38
38
  let _SqliteDB: (new (p: string) => _SqliteDB) | null = null;
39
39
  try {
40
- const _req = createRequire(import.meta.url);
41
- _SqliteDB = (_req('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB }).DatabaseSync;
40
+ // process.getBuiltinModule is available in Node >= 22.3.0 (within our >=22.13.0 engine
41
+ // requirement). It's synchronous and does not require the esbuild __require shim.
42
+ const sqlite = (process as unknown as { getBuiltinModule(m: string): unknown })
43
+ .getBuiltinModule('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB } | undefined;
44
+ _SqliteDB = sqlite?.DatabaseSync ?? null;
42
45
  } catch { /* node:sqlite unavailable — file-only mode */ }
43
- // ── Encryption (self-contained to avoid circular import) ─────────────────────
44
-
45
- const AES_ALGO = 'aes-256-gcm' as const;
46
- const IV_BYTES = 12;
47
- const TAG_BYTES = 16;
46
+ // ── Encryption (delegates to CacheEncryption — mode-aware, no reimplementation) ──
47
+ // DiskTier keeps its own V2 envelope (magic | plaintext expiresAt | payload) but
48
+ // delegates the payload cipher to CacheEncryption, which already supports all four
49
+ // modes (aes-256-gcm, aes-128-gcm, aes-128-ctr, xor) and is the single source of
50
+ // truth for the on-disk binary format. This avoids a hardcoded aes-256-gcm that
51
+ // threw (and silently no-op'd the disk tier) for any non-default mode.
48
52
  const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
49
53
  /**
50
54
  * V2 file format — expiresAt stored in plaintext outside the ciphertext so the
@@ -73,7 +77,10 @@ export interface DiskTierOptions {
73
77
  maxBytes: number;
74
78
  entryMaxBytes: number;
75
79
  forbiddenPrefixes: readonly string[];
76
- encryptionKey?: Buffer | null;
80
+ /** Mode-aware encryption instance. When set, disk files are encrypted with the
81
+ * same algorithm as L2/Redis (aes-256-gcm, aes-128-gcm, aes-128-ctr, or xor).
82
+ * When null, files are written unencrypted. Pass `cache.encryption` here. */
83
+ encryption?: CacheEncryption | null;
77
84
  logger: ILogger;
78
85
  }
79
86
 
@@ -259,57 +266,37 @@ export class DiskTier {
259
266
  }
260
267
 
261
268
  private encrypt(data: Buffer): Buffer {
262
- const key = this.opts.encryptionKey;
263
- if (!key) return data;
264
- const iv = crypto.randomBytes(IV_BYTES);
265
- const c = crypto.createCipheriv(AES_ALGO, key, iv);
266
- const enc = Buffer.concat([c.update(data), c.final()]);
267
- const tag = c.getAuthTag();
268
- return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
269
+ if (!this.opts.encryption) return data;
270
+ // V1 envelope: DISK_MAGIC prefix wrapping the mode-aware CacheEncryption blob.
271
+ return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
269
272
  }
270
273
 
271
274
  private decrypt(data: Buffer): Buffer {
272
275
  const mLen = DISK_MAGIC.length;
273
276
  if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
274
- const key = this.opts.encryptionKey;
275
- if (!key) throw new Error('DiskTier: entry is encrypted but no key is set');
276
- const iv = data.subarray(mLen, mLen + IV_BYTES);
277
- const tag = data.subarray(mLen + IV_BYTES, mLen + IV_BYTES + TAG_BYTES);
278
- const ct = data.subarray(mLen + IV_BYTES + TAG_BYTES);
279
- const d = crypto.createDecipheriv(AES_ALGO, key, iv);
280
- d.setAuthTag(tag);
281
- return Buffer.concat([d.update(ct), d.final()]);
277
+ if (!this.opts.encryption) throw new Error('DiskTier: entry is encrypted but no encryption configured');
278
+ return this.opts.encryption.decryptBuffer(data.subarray(mLen));
282
279
  }
283
280
 
284
281
  /**
285
- * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
286
- * the outer 16-byte header alongside the plaintext expiresAt).
287
- * Returns the buffer unchanged when no encryption key is configured.
282
+ * V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
283
+ * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
284
+ * Returns the buffer unchanged when no encryption instance is configured.
288
285
  */
289
286
  private encryptV2(data: Buffer): Buffer {
290
- const key = this.opts.encryptionKey;
291
- if (!key) return data;
292
- const iv = crypto.randomBytes(IV_BYTES);
293
- const c = crypto.createCipheriv(AES_ALGO, key, iv);
294
- const enc = Buffer.concat([c.update(data), c.final()]);
295
- const tag = c.getAuthTag();
296
- return Buffer.concat([iv, tag, enc]);
287
+ if (!this.opts.encryption) return data;
288
+ return this.opts.encryption.encryptBuffer(data);
297
289
  }
298
290
 
299
291
  /**
300
292
  * V2 decryption — inner payload after stripping the 16-byte header.
301
- * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
302
- * without a key the payload is raw msgpack.
293
+ * When an encryption instance is configured the format is the mode-aware
294
+ * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
295
+ * without one the payload is raw msgpack.
303
296
  */
304
297
  private decryptV2(inner: Buffer): Buffer {
305
- const key = this.opts.encryptionKey;
306
- if (!key) return inner;
307
- const iv = inner.subarray(0, IV_BYTES);
308
- const tag = inner.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
309
- const ct = inner.subarray(IV_BYTES + TAG_BYTES);
310
- const d = crypto.createDecipheriv(AES_ALGO, key, iv);
311
- d.setAuthTag(tag);
312
- return Buffer.concat([d.update(ct), d.final()]);
298
+ if (!this.opts.encryption) return inner;
299
+ return this.opts.encryption.decryptBuffer(inner);
313
300
  }
314
301
 
315
302
  // ── Public API ────────────────────────────────────────────────────────────
package/src/encryption.ts CHANGED
@@ -228,6 +228,26 @@ export class CacheEncryption {
228
228
 
229
229
  get isEnabled(): boolean { return this._key !== null; }
230
230
 
231
+ /**
232
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
233
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
234
+ * cast in cache-service.ts — the worker pool reads these via this accessor
235
+ * instead of reaching into underscore-prefixed internals.
236
+ */
237
+ toWorkerInit(): {
238
+ keyBase64: string;
239
+ mode: EncryptionMode;
240
+ prevKeyBase64: string | undefined;
241
+ prevMode: EncryptionMode;
242
+ } {
243
+ return {
244
+ keyBase64: this._key ? this._key.toString('base64') : '',
245
+ mode: this._mode,
246
+ prevKeyBase64: this._prevKey ? this._prevKey.toString('base64') : undefined,
247
+ prevMode: this._prevMode,
248
+ };
249
+ }
250
+
231
251
  // ── String (Redis) ────────────────────────────────────────────────────────
232
252
 
233
253
  /**
@@ -273,18 +293,18 @@ export class CacheEncryption {
273
293
  */
274
294
  decrypt(value: string): string {
275
295
  try {
276
- return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
296
+ return this._decryptWithKey(value, this._key, this._keyObj);
277
297
  } catch (primaryErr) {
278
298
  if (this._prevKey) {
279
299
  try {
280
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
300
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
281
301
  } catch { /* ignore — fall through to re-throw primary */ }
282
302
  }
283
303
  throw primaryErr;
284
304
  }
285
305
  }
286
306
 
287
- private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null, mode: EncryptionMode): string {
307
+ private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null): string {
288
308
  if (value.startsWith(PREFIX_XOR)) {
289
309
  if (!key) throw new Error('Cannot decrypt: encryption key is not set');
290
310
  // WARNING: XOR is NOT cryptographic — obfuscation only.
@@ -321,7 +341,6 @@ export class CacheEncryption {
321
341
  const plain = d.update(ct); // GCM: final() emits no bytes
322
342
  d.final(); // verifies auth tag — throws on tamper
323
343
  return plain.toString('utf8');
324
- void mode; void key; // mode and raw key used implicitly (mode via prefix; key via keyObj for AES, directly for XOR)
325
344
  }
326
345
 
327
346
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
@@ -363,8 +363,8 @@ export class SmartMemoryCache {
363
363
  const lim = this.getCategoryLimit(category);
364
364
  const catCnt = this.categoryCount.get(category) ?? 0;
365
365
  const catSz = this.categorySize.get(category) ?? 0;
366
- const catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
367
- const glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
366
+ let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
367
+ let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
368
368
  if (!catOvf && !glbOvf) {
369
369
  // Proactive watermark: when either the global entry count OR total byte
370
370
  // usage crosses 90 % of its configured ceiling while there is still
@@ -381,7 +381,23 @@ export class SmartMemoryCache {
381
381
  }
382
382
  return;
383
383
  }
384
- this.smartEvict(category, catOvf);
384
+ // Hard overflow: evict until back under BOTH the category and global limits.
385
+ // A single smartEvict() pass removes at most EVICT_COUNT entries, which is not
386
+ // enough when one set() pushes the cache far past its ceiling (e.g. a large
387
+ // entry that itself dominates the byte budget). Loop until the overflow clears,
388
+ // bounded by MAX_EVICT_PASSES so a pathological key (larger than the limit
389
+ // cannot be evicted to fit itself) cannot spin forever.
390
+ const MAX_EVICT_PASSES = 64;
391
+ let passes = 0;
392
+ do {
393
+ this.smartEvict(category, catOvf);
394
+ const lim2 = this.getCategoryLimit(category);
395
+ const catCnt2 = this.categoryCount.get(category) ?? 0;
396
+ const catSz2 = this.categorySize.get(category) ?? 0;
397
+ catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
398
+ glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
399
+ passes++;
400
+ } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
385
401
  }
386
402
 
387
403
  private score(entry: SmartCacheEntry, catBonus: number, now: number, key: string): number {
package/src/types.ts CHANGED
@@ -182,6 +182,14 @@ export interface CacheMetrics {
182
182
  deletes: { total: number };
183
183
  revalidations: { total: number };
184
184
 
185
+ /** Rate-limit / singleton diagnostics */
186
+ counters: {
187
+ /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
188
+ errors: number;
189
+ /** Times a later `create(ns)` call passed options diverging from the live singleton. */
190
+ singletonDivergences: number;
191
+ };
192
+
185
193
  bloom: {
186
194
  /** Total bloom-filter checks (get() calls that passed prefix filter) */
187
195
  checksTotal: number;
@@ -700,4 +708,25 @@ export interface CacheOptions {
700
708
  name: string;
701
709
  sentinels: Array<{ host: string; port: number }>;
702
710
  };
711
+
712
+ /**
713
+ * When `true`, a second `CacheService.create()` call for an already-existing
714
+ * singleton (same namespace) whose options differ from the first call throws
715
+ * instead of silently returning the existing instance. Use in codebases where
716
+ * multiple init points could pass conflicting configuration (e.g. different
717
+ * Redis credentials or TTLs) and you want that class of bug to fail loudly.
718
+ *
719
+ * Default: `false` (warn once, return existing instance).
720
+ */
721
+ strictSingleton?: boolean;
722
+
723
+ /**
724
+ * `cache.increment()` distributed-rate-limit behaviour on a Redis error.
725
+ *
726
+ * Default: `false` (fail-open — on a Redis error the method returns `0`, so a
727
+ * caller's `if (count > LIMIT) reject()` guard never rejects during an outage).
728
+ * Set to `true` to instead re-throw the Redis error, letting the caller's limit
729
+ * guard enforce the limit even when Redis is unavailable.
730
+ */
731
+ failClosed?: boolean;
703
732
  }
@@ -94,8 +94,8 @@ export class WasmBloomFilter {
94
94
 
95
95
  /**
96
96
  * Maximum safe insertions before false-positive rate exceeds ~1 %.
97
- * Exact formula for k=7 hash rounds, m=100 000 bits:
98
- * n_max = -m * ln(1 - p^(1/k)) / k ≈ 18 169
97
+ * Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
98
+ * n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
99
99
  */
100
100
  get maxCapacity(): number { return this._maxCapacity; }
101
101
  }
@@ -26,6 +26,7 @@
26
26
  import { Worker } from 'worker_threads';
27
27
  import { fileURLToPath } from 'url';
28
28
  import { dirname, join } from 'path';
29
+ import os from 'os';
29
30
  import type { EncryptionMode } from './encryption.js';
30
31
 
31
32
  // Locate the serialize-worker entry point.
@@ -179,12 +180,6 @@ export class WorkerPool {
179
180
  }
180
181
 
181
182
  function availableCpus(): number {
182
- try {
183
- // Node.js 18.14+ provides `availableParallelism`; fall back to os.cpus().
184
- // eslint-disable-next-line @typescript-eslint/no-require-imports
185
- const os = require('os') as typeof import('os');
186
- return (os as unknown as { availableParallelism?: () => number }).availableParallelism?.() ?? os.cpus().length;
187
- } catch {
188
- return 2;
189
- }
183
+ // Node >= 22.13.0 (engines constraint) always has availableParallelism.
184
+ return os.availableParallelism?.() ?? os.cpus().length;
190
185
  }