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.
@@ -153,6 +153,20 @@ var CacheEncryption = class {
153
153
  get isEnabled() {
154
154
  return this._key !== null;
155
155
  }
156
+ /**
157
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
158
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
159
+ * cast in cache-service.ts — the worker pool reads these via this accessor
160
+ * instead of reaching into underscore-prefixed internals.
161
+ */
162
+ toWorkerInit() {
163
+ return {
164
+ keyBase64: this._key ? this._key.toString("base64") : "",
165
+ mode: this._mode,
166
+ prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
167
+ prevMode: this._prevMode
168
+ };
169
+ }
156
170
  // ── String (Redis) ────────────────────────────────────────────────────────
157
171
  /**
158
172
  * Encrypt a string for Redis storage.
@@ -195,18 +209,18 @@ var CacheEncryption = class {
195
209
  */
196
210
  decrypt(value) {
197
211
  try {
198
- return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
212
+ return this._decryptWithKey(value, this._key, this._keyObj);
199
213
  } catch (primaryErr) {
200
214
  if (this._prevKey) {
201
215
  try {
202
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
216
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
203
217
  } catch {
204
218
  }
205
219
  }
206
220
  throw primaryErr;
207
221
  }
208
222
  }
209
- _decryptWithKey(value, key, keyObj, mode2) {
223
+ _decryptWithKey(value, key, keyObj) {
210
224
  if (value.startsWith(PREFIX_XOR)) {
211
225
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
212
226
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -241,8 +255,6 @@ var CacheEncryption = class {
241
255
  const plain = d.update(ct);
242
256
  d.final();
243
257
  return plain.toString("utf8");
244
- void mode2;
245
- void key;
246
258
  }
247
259
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
248
260
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
@@ -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/serialize-worker.ts
6
6
  import { parentPort, workerData } from "worker_threads";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.6.5",
3
+ "version": "0.6.6",
4
4
  "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
@@ -18,7 +18,6 @@
18
18
  "nodejs"
19
19
  ],
20
20
  "license": "MIT",
21
- "packageManager": "pnpm@11.3.0",
22
21
  "type": "module",
23
22
  "main": "./dist/index.js",
24
23
  "module": "./dist/index.js",
@@ -36,18 +35,9 @@
36
35
  "README.md",
37
36
  "LICENSE"
38
37
  ],
39
- "scripts": {
40
- "build": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --clean",
41
- "postbuild": "node --input-type=module -e \"import{rmSync}from'fs';['dist/index.d.cts','dist/serialize-worker.d.cts'].forEach(f=>rmSync(f,{force:true}));\"",
42
- "dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
43
- "typecheck": "tsc --noEmit",
44
- "test": "vitest run",
45
- "test:watch": "vitest",
46
- "bench": "node --expose-gc --import tsx/esm bench/benchmark.ts"
47
- },
48
38
  "dependencies": {
49
- "ioredis": "^5.11.0",
50
- "msgpackr": "^2.0.2"
39
+ "ioredis": "5.11.1",
40
+ "msgpackr": "2.0.4"
51
41
  },
52
42
  "devDependencies": {
53
43
  "@types/node": "^24.0.0",
@@ -63,5 +53,14 @@
63
53
  "repository": {
64
54
  "type": "git",
65
55
  "url": "git+https://github.com/Kareem411/TriCache.git"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --clean",
59
+ "postbuild": "node --input-type=module -e \"import{rmSync}from'fs';['dist/index.d.cts','dist/serialize-worker.d.cts'].forEach(f=>rmSync(f,{force:true}));\"",
60
+ "dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
61
+ "typecheck": "tsc --noEmit",
62
+ "test": "vitest run",
63
+ "test:watch": "vitest",
64
+ "bench": "node --expose-gc --import tsx/esm bench/benchmark.ts"
66
65
  }
67
- }
66
+ }
@@ -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
@@ -19,6 +19,7 @@ import path from 'path';
19
19
  import crypto from 'crypto';
20
20
  import { pack, unpack } from 'msgpackr';
21
21
  import { DiskCacheEntry, ILogger } from './types.js';
22
+ import { CacheEncryption } from './encryption.js';
22
23
 
23
24
  // ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
24
25
  // Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
@@ -42,11 +43,12 @@ try {
42
43
  .getBuiltinModule('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB } | undefined;
43
44
  _SqliteDB = sqlite?.DatabaseSync ?? null;
44
45
  } catch { /* node:sqlite unavailable — file-only mode */ }
45
- // ── Encryption (self-contained to avoid circular import) ─────────────────────
46
-
47
- const AES_ALGO = 'aes-256-gcm' as const;
48
- const IV_BYTES = 12;
49
- 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.
50
52
  const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
51
53
  /**
52
54
  * V2 file format — expiresAt stored in plaintext outside the ciphertext so the
@@ -75,7 +77,10 @@ export interface DiskTierOptions {
75
77
  maxBytes: number;
76
78
  entryMaxBytes: number;
77
79
  forbiddenPrefixes: readonly string[];
78
- 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;
79
84
  logger: ILogger;
80
85
  }
81
86
 
@@ -261,57 +266,37 @@ export class DiskTier {
261
266
  }
262
267
 
263
268
  private encrypt(data: Buffer): Buffer {
264
- const key = this.opts.encryptionKey;
265
- if (!key) return data;
266
- const iv = crypto.randomBytes(IV_BYTES);
267
- const c = crypto.createCipheriv(AES_ALGO, key, iv);
268
- const enc = Buffer.concat([c.update(data), c.final()]);
269
- const tag = c.getAuthTag();
270
- 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)]);
271
272
  }
272
273
 
273
274
  private decrypt(data: Buffer): Buffer {
274
275
  const mLen = DISK_MAGIC.length;
275
276
  if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
276
- const key = this.opts.encryptionKey;
277
- if (!key) throw new Error('DiskTier: entry is encrypted but no key is set');
278
- const iv = data.subarray(mLen, mLen + IV_BYTES);
279
- const tag = data.subarray(mLen + IV_BYTES, mLen + IV_BYTES + TAG_BYTES);
280
- const ct = data.subarray(mLen + IV_BYTES + TAG_BYTES);
281
- const d = crypto.createDecipheriv(AES_ALGO, key, iv);
282
- d.setAuthTag(tag);
283
- 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));
284
279
  }
285
280
 
286
281
  /**
287
- * V2 encryption — returns IV+TAG+ciphertext (no magic prefix; magic lives in
288
- * the outer 16-byte header alongside the plaintext expiresAt).
289
- * 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.
290
285
  */
291
286
  private encryptV2(data: Buffer): Buffer {
292
- const key = this.opts.encryptionKey;
293
- if (!key) return data;
294
- const iv = crypto.randomBytes(IV_BYTES);
295
- const c = crypto.createCipheriv(AES_ALGO, key, iv);
296
- const enc = Buffer.concat([c.update(data), c.final()]);
297
- const tag = c.getAuthTag();
298
- return Buffer.concat([iv, tag, enc]);
287
+ if (!this.opts.encryption) return data;
288
+ return this.opts.encryption.encryptBuffer(data);
299
289
  }
300
290
 
301
291
  /**
302
292
  * V2 decryption — inner payload after stripping the 16-byte header.
303
- * When a key is configured the format is IV(12)+TAG(16)+ciphertext;
304
- * 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.
305
296
  */
306
297
  private decryptV2(inner: Buffer): Buffer {
307
- const key = this.opts.encryptionKey;
308
- if (!key) return inner;
309
- const iv = inner.subarray(0, IV_BYTES);
310
- const tag = inner.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
311
- const ct = inner.subarray(IV_BYTES + TAG_BYTES);
312
- const d = crypto.createDecipheriv(AES_ALGO, key, iv);
313
- d.setAuthTag(tag);
314
- return Buffer.concat([d.update(ct), d.final()]);
298
+ if (!this.opts.encryption) return inner;
299
+ return this.opts.encryption.decryptBuffer(inner);
315
300
  }
316
301
 
317
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) ──────────────────────────────────────────────