tricache 0.5.1 → 0.6.1

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.
@@ -24,6 +24,10 @@ import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
24
24
 
25
25
  /** Fraction of candidates evicted in one pass when a limit is exceeded */
26
26
  const EVICTION_BATCH_PERCENT = 0.2;
27
+ /** Reservoir sample window for smartEvict() — Redis-style. */
28
+ const EVICTION_SAMPLE = 16;
29
+ /** Number of lowest-scored candidates evicted per smartEvict() call. */
30
+ const EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT)); // 4
27
31
 
28
32
  // ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
29
33
 
@@ -242,12 +246,14 @@ function globMatch(pattern: string, key: string): boolean {
242
246
  // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
243
247
 
244
248
  export interface SmartMemoryCacheOptions {
245
- maxBytes: number;
246
- maxEntries: number;
247
- categories: Record<string, CategoryLimit>;
248
- diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
249
- onEviction?: (key: string, reason: EvictionReason) => void;
250
- logger: ILogger;
249
+ maxBytes: number;
250
+ maxEntries: number;
251
+ categories: Record<string, CategoryLimit>;
252
+ diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
253
+ onEviction?: (key: string, reason: EvictionReason) => void;
254
+ logger: ILogger;
255
+ /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
256
+ evictionWatermark?: number;
251
257
  }
252
258
 
253
259
  export class SmartMemoryCache {
@@ -271,6 +277,18 @@ export class SmartMemoryCache {
271
277
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
272
278
  private _bloomDirtyCount = 0;
273
279
 
280
+ /**
281
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
282
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
283
+ * that is overwritten in-place rather than replaced with a new object literal.
284
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
285
+ * any other code can observe the pool state.
286
+ */
287
+ private readonly _evictPool: Array<{ key: string; score: number }> =
288
+ Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
289
+ private readonly _evictGPool: Array<{ key: string; score: number }> =
290
+ Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
291
+
274
292
  constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
275
293
  this.opts = opts;
276
294
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
@@ -342,8 +360,9 @@ export class SmartMemoryCache {
342
360
  // capacity become uncommon. Both dimensions are guarded so that
343
361
  // large-payload workloads (where maxBytes is the binding constraint)
344
362
  // benefit equally alongside entry-count-bound workloads.
345
- const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * 0.9);
346
- const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * 0.9);
363
+ const wm = this.opts.evictionWatermark ?? 0.9;
364
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
365
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
347
366
  if (entryWatermark || byteWatermark) {
348
367
  this.smartEvict(category, false);
349
368
  }
@@ -396,16 +415,15 @@ export class SmartMemoryCache {
396
415
 
397
416
  private smartEvict(targetCat: string, catOvf: boolean): void {
398
417
  const now = Date.now();
399
- const SAMPLE = 16; // Redis-style sample window
400
- const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT)); // ~4
401
-
402
- const pool: Array<{ key: string; score: number }> = [];
418
+ const pool = this._evictPool;
419
+ const gPool = this._evictGPool;
420
+ let poolLen = 0;
403
421
 
404
422
  if (catOvf) {
405
423
  // Phase 1 — O(catSize) category-local reservoir sample.
406
424
  // Uses the categoryKeys index to iterate only the overflowing category's keys,
407
425
  // avoiding an O(N) scan of the entire cache. Guarantees at least
408
- // min(catSize, EVICT) entries from the overflowing category in the pool so
426
+ // min(catSize, EVICT_COUNT) entries from the overflowing category in the pool so
409
427
  // the priority score ordering is always deterministic in practice.
410
428
  const catKeySet = this.categoryKeys.get(targetCat);
411
429
  if (catKeySet) {
@@ -415,44 +433,59 @@ export class SmartMemoryCache {
415
433
  if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
416
434
  catSeen++;
417
435
  const s = this.score(entry, 100, now, key);
418
- if (pool.length < EVICT) {
419
- pool.push({ key, score: s });
436
+ if (poolLen < EVICT_COUNT) {
437
+ pool[poolLen].key = key; pool[poolLen].score = s; poolLen++;
420
438
  } else {
421
439
  const j = Math.floor(Math.random() * catSeen);
422
- if (j < EVICT) pool[j] = { key, score: s };
440
+ if (j < EVICT_COUNT) { pool[j].key = key; pool[j].score = s; }
423
441
  }
424
442
  }
425
443
  }
426
444
  }
427
445
 
428
- // Phase 2 — global reservoir sample fills remaining SAMPLE-pool.length slots.
429
- // Skipped entirely when Phase 1 already collected a full EVICT-sized pool
430
- // (the common catOvf case — overflowing categories always have ≥ EVICT entries).
446
+ // Phase 2 — global reservoir sample fills remaining EVICTION_SAMPLE-poolLen slots.
447
+ // Skipped entirely when Phase 1 already collected a full EVICT_COUNT-sized pool
448
+ // (the common catOvf case — overflowing categories always have ≥ EVICT_COUNT entries).
431
449
  // Also the sole phase when !catOvf (global over-capacity, no preferred category).
432
- if (pool.length < EVICT) {
433
- const remaining = SAMPLE - pool.length;
450
+ if (poolLen < EVICT_COUNT) {
451
+ const remaining = EVICTION_SAMPLE - poolLen;
434
452
  let globalSeen = 0;
435
- const globalPool: Array<{ key: string; score: number }> = [];
453
+ let gLen = 0;
436
454
  for (const [key, entry] of this.cache) {
437
455
  if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
438
456
  if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
439
457
  globalSeen++;
440
458
  const s = this.score(entry, 0, now, key);
441
- if (globalPool.length < remaining) {
442
- globalPool.push({ key, score: s });
459
+ if (gLen < remaining) {
460
+ gPool[gLen].key = key; gPool[gLen].score = s; gLen++;
443
461
  } else {
444
462
  const j = Math.floor(Math.random() * globalSeen);
445
- if (j < remaining) globalPool[j] = { key, score: s };
463
+ if (j < remaining) { gPool[j].key = key; gPool[j].score = s; }
446
464
  }
447
465
  }
448
- pool.push(...globalPool);
466
+ // Manual merge — no spread, no new array
467
+ for (let i = 0; i < gLen; i++) {
468
+ pool[poolLen].key = gPool[i].key; pool[poolLen].score = gPool[i].score; poolLen++;
469
+ }
449
470
  }
450
471
 
451
- if (pool.length === 0) return;
472
+ if (poolLen === 0) return;
473
+
474
+ // Insertion sort — O(poolLen²) but poolLen ≤ EVICTION_SAMPLE=16 (max 256 comparisons).
475
+ // Faster than Array.sort() at this scale: no comparator closure call overhead,
476
+ // no timsort startup, no allocation. Sorts in-place within the pre-allocated pool.
477
+ for (let i = 1; i < poolLen; i++) {
478
+ const sk = pool[i].key, ss = pool[i].score;
479
+ let j = i - 1;
480
+ while (j >= 0 && pool[j].score > ss) {
481
+ pool[j + 1].key = pool[j].key; pool[j + 1].score = pool[j].score; j--;
482
+ }
483
+ pool[j + 1].key = sk; pool[j + 1].score = ss;
484
+ }
452
485
 
453
- // Sort only the tiny merged pool (O(SAMPLE * log(SAMPLE)) ≈ 64 comparisons)
454
- pool.sort((a, b) => a.score - b.score);
455
- for (const { key } of pool.slice(0, EVICT)) {
486
+ const toEvict = Math.min(EVICT_COUNT, poolLen);
487
+ for (let i = 0; i < toEvict; i++) {
488
+ const key = pool[i].key;
456
489
  const entry = this.cache.get(key);
457
490
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
458
491
  this._delete(key, 'capacity');
@@ -696,7 +729,48 @@ export class SmartMemoryCache {
696
729
  return cleaned;
697
730
  }
698
731
 
699
- // ── Snapshot import/export ────────────────────────────────────────────────
732
+ /**
733
+ * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
734
+ *
735
+ * Called by the backplane staleness fence when the Pub/Sub subscriber
736
+ * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
737
+ * Entries written before the disconnect started may have been invalidated by
738
+ * peers while the backplane was down; evicting them forces a controlled
739
+ * cold-start re-fetch from L2 rather than serving silently stale data.
740
+ *
741
+ * Write-time is approximated as `entry.expiresAt - entry.ttlMs`.
742
+ * Entries with no stored `ttlMs` (e.g. legacy snapshot imports) are evicted
743
+ * conservatively.
744
+ *
745
+ * @param cutoffMs - Unix timestamp in milliseconds; entries written before
746
+ * this time are evicted.
747
+ * @returns Number of entries evicted.
748
+ */
749
+ evictSetBefore(cutoffMs: number): number {
750
+ let evicted = 0;
751
+ for (const [key, entry] of this.cache) {
752
+ // Never evict live CRITICAL entries — auth tokens, active sessions, etc.
753
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > Date.now()) continue;
754
+
755
+ // Approximate write-time from the stored TTL. When ttlMs is missing
756
+ // (legacy import), treat the entry as potentially stale.
757
+ const setAt = (entry.ttlMs != null)
758
+ ? entry.expiresAt - entry.ttlMs
759
+ : 0; // unknown → assume stale
760
+
761
+ if (setAt < cutoffMs) {
762
+ this._delete(key, 'manual');
763
+ evicted++;
764
+ }
765
+ }
766
+ if (evicted > 0) {
767
+ this.bloom.rebuild(this.cache.keys());
768
+ this._bloomDirtyCount = 0;
769
+ }
770
+ return evicted;
771
+ }
772
+
773
+
700
774
 
701
775
  exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
702
776
  const now = Date.now();
package/src/types.ts CHANGED
@@ -221,7 +221,20 @@ export interface CacheMetrics {
221
221
  };
222
222
 
223
223
  l1: { entries: number; sizeBytes: number; maxBytes: number };
224
- disk: { files: number; sizeKB: number; maxKB: number };
224
+ disk: { files: number; sizeKB: number; maxKB: number; disabled: boolean };
225
+
226
+ /** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
227
+ adaptiveTtl?: {
228
+ enabled: true;
229
+ /** Number of unique keys currently tracked in the latency ring buffers */
230
+ trackedKeys: number;
231
+ /**
232
+ * Top-20 slowest keys by p95 fetch latency, sorted descending.
233
+ * Keys are shown without the instance namespace prefix.
234
+ * Only keys with ≥ 5 recorded samples appear here.
235
+ */
236
+ slowestKeys: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }>;
237
+ };
225
238
  }
226
239
 
227
240
  // ─── Configuration ───────────────────────────────────────────────────────────
@@ -249,6 +262,12 @@ export interface CacheOptions {
249
262
  l1MaxBytes?: number;
250
263
  /** Max total entries in L1. Default: 2000 */
251
264
  l1MaxEntries?: number;
265
+ /**
266
+ * Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
267
+ * before the hard limit is reached. Range: 0–1. Default: 0.9.
268
+ * Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
269
+ */
270
+ l1EvictionWatermark?: number;
252
271
  /**
253
272
  * Per-category limits keyed by the key prefix (e.g. `'org:'`).
254
273
  * Merged over the built-in defaults.
@@ -515,4 +534,163 @@ export interface CacheOptions {
515
534
  * frozen: process.env.NODE_ENV !== 'production'
516
535
  */
517
536
  frozen?: boolean;
537
+
538
+ // ── Adaptive TTL ──────────────────────────────────────────────────────────
539
+
540
+ /**
541
+ * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
542
+ * and automatically derives an optimal TTL from the p95 fetch duration:
543
+ *
544
+ * ```
545
+ * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
546
+ * ```
547
+ *
548
+ * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
549
+ * for a key, then the library takes over TTL management autonomously.
550
+ *
551
+ * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
552
+ * their base TTL. Callers no longer need to reason about individual TTL values.
553
+ *
554
+ * Default: `false`.
555
+ */
556
+ adaptiveTtl?: boolean;
557
+
558
+ /**
559
+ * Minimum TTL (seconds) the adaptive tuner will ever assign.
560
+ * Guards against extremely fast fetches producing near-zero TTLs.
561
+ * Default: `10`.
562
+ */
563
+ adaptiveTtlMin?: number;
564
+
565
+ /**
566
+ * Maximum TTL (seconds) the adaptive tuner will ever assign.
567
+ * Guards against pathologically slow fetches producing indefinite caching.
568
+ * Default: `86400` (24 hours).
569
+ */
570
+ adaptiveTtlMax?: number;
571
+
572
+ /**
573
+ * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
574
+ *
575
+ * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
576
+ * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
577
+ * if you want the cache to absorb more upstream pressure.
578
+ *
579
+ * Default: `20`.
580
+ */
581
+ adaptiveTtlMultiplier?: number;
582
+
583
+ /**
584
+ * Number of fetch duration samples kept per key in the ring buffer.
585
+ * Larger values smooth out latency spikes but use slightly more memory
586
+ * (~8 bytes × samples per tracked key).
587
+ * Default: `32`.
588
+ */
589
+ adaptiveTtlSamples?: number;
590
+
591
+ /**
592
+ * Maximum number of distinct keys tracked by the adaptive TTL system.
593
+ * When the cap is reached, the oldest-tracked key is evicted from the
594
+ * ring-buffer store to make room for the new key.
595
+ * Default: `5000`.
596
+ */
597
+ adaptiveTtlMaxKeys?: number;
598
+
599
+ // ── Worker-thread serialization offload ────────────────────────────────────
600
+ /**
601
+ * When `true`, tricache spawns a pool of worker threads and offloads AES-GCM
602
+ * encryption and decryption for large payloads to those threads, keeping the
603
+ * V8 main event loop free for concurrent HTTP requests.
604
+ *
605
+ * Only takes effect when `encryptionKey` is set — plaintext payloads are never
606
+ * serialized off-thread because `JSON.stringify/parse` is already fast.
607
+ *
608
+ * Default: `false`. Enable in long-running servers that write multi-megabyte
609
+ * encrypted payloads and observe event-loop latency spikes.
610
+ */
611
+ workerThreads?: boolean;
612
+ /**
613
+ * Byte threshold above which an L2 payload is offloaded to a worker thread
614
+ * for encryption / decryption. Payloads smaller than this are processed
615
+ * synchronously (IPC overhead would exceed the savings).
616
+ * Default: `131072` (128 KB).
617
+ */
618
+ workerThresholdBytes?: number;
619
+ /**
620
+ * Number of worker threads in the pool.
621
+ * Default: `Math.min(4, os.availableParallelism())`.
622
+ */
623
+ workerPoolSize?: number;
624
+
625
+ // ── Backplane staleness fence ───────────────────────────────────────────────
626
+ /**
627
+ * Maximum milliseconds the Redis Pub/Sub subscriber is allowed to be
628
+ * disconnected before tricache considers its L1 entries potentially stale.
629
+ *
630
+ * When the subscriber reconnects after a gap longer than this value, all L1
631
+ * entries that were written *before* the disconnect started are evicted.
632
+ * This prevents the instance from silently serving data that peers may have
633
+ * invalidated while the backplane connection was down.
634
+ *
635
+ * Set to `0` to disable the fence entirely (accept eventual-consistency drift).
636
+ * Default: `5000` (5 seconds).
637
+ */
638
+ backplaneMaxStalenessMs?: number;
639
+
640
+ // ── Disk tier ─────────────────────────────────────────────────────────────
641
+ /**
642
+ * Explicitly disable the L1.5 disk spill tier and cold-start snapshots.
643
+ *
644
+ * Tricache auto-detects common serverless / ephemeral-filesystem runtimes
645
+ * (AWS Lambda, Google Cloud Run, Google Cloud Functions, Azure Functions,
646
+ * Fly.io) and disables the disk tier automatically. Set this to `false` to
647
+ * override that detection and force the disk tier on regardless of runtime.
648
+ *
649
+ * When disabled:
650
+ * - L1 evictions are dropped instead of being spilled to disk.
651
+ * - Cold-start snapshot persistence is skipped.
652
+ * - The `disk` metrics field still appears but shows zeroed counters.
653
+ *
654
+ * Default: `undefined` (auto-detect).
655
+ */
656
+ disableDisk?: boolean;
657
+
658
+ // ── Redis Cluster / Sentinel ───────────────────────────────────────────────
659
+ /**
660
+ * Redis Cluster node list. When provided, tricache connects using ioredis
661
+ * `Cluster` mode with automatic slot routing and multi-node connection
662
+ * pooling — no external proxy required.
663
+ *
664
+ * Takes precedence over `redisHost`/`redisPort`.
665
+ *
666
+ * @example
667
+ * redisClusterNodes: [
668
+ * { host: 'redis-1.internal', port: 6379 },
669
+ * { host: 'redis-2.internal', port: 6379 },
670
+ * { host: 'redis-3.internal', port: 6379 },
671
+ * ]
672
+ */
673
+ redisClusterNodes?: Array<{ host: string; port: number }>;
674
+
675
+ /**
676
+ * Redis Sentinel configuration for high-availability setups.
677
+ * When provided, tricache connects through Sentinel for automatic
678
+ * primary failover — no static `redisHost` / `redisPort` needed.
679
+ *
680
+ * Takes precedence over `redisHost`/`redisPort` (but not over `redisClusterNodes`).
681
+ *
682
+ * @example
683
+ * redisSentinel: {
684
+ * name: 'mymaster',
685
+ * sentinels: [
686
+ * { host: 'sentinel-1.internal', port: 26379 },
687
+ * { host: 'sentinel-2.internal', port: 26379 },
688
+ * ],
689
+ * }
690
+ */
691
+ redisSentinel?: {
692
+ /** Logical name of the monitored master. Must match the Sentinel `monitor` config. */
693
+ name: string;
694
+ sentinels: Array<{ host: string; port: number }>;
695
+ };
518
696
  }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * WorkerPool — a fixed-size pool of worker threads for off-main-thread
3
+ * encryption and decryption of large cache payloads.
4
+ *
5
+ * Design goals:
6
+ * - Zero-allocation hot path: pending Promises are stored in a pre-keyed Map.
7
+ * - Round-robin dispatch: tasks fan out evenly across all workers.
8
+ * - Auto-fallback: if the pool fails to initialize, `isAvailable` is false and
9
+ * the caller falls through to the synchronous path without any error.
10
+ * - Graceful drain: `destroy()` terminates all workers after in-flight
11
+ * Promises have settled.
12
+ *
13
+ * Memory model:
14
+ * - The encryption key is passed once via `workerData` at thread creation.
15
+ * Per-message IPC carries only the plaintext/ciphertext string — no key material.
16
+ * - All message payloads are structured-cloned (strings are fast to clone).
17
+ *
18
+ * Usage:
19
+ * const pool = new WorkerPool({ keyBase64, mode, size: 2 });
20
+ * if (pool.isAvailable) {
21
+ * const cipher = await pool.encrypt(jsonString);
22
+ * const plain = await pool.decrypt(cipher);
23
+ * }
24
+ */
25
+
26
+ import { Worker } from 'worker_threads';
27
+ import { fileURLToPath } from 'url';
28
+ import { dirname, join } from 'path';
29
+ import type { EncryptionMode } from './encryption.js';
30
+
31
+ // Locate the serialize-worker entry point.
32
+ // Production: tsup emits compile .js files as flat siblings → use .js path.
33
+ // Development / test (tsx, Vitest): the .ts source is used directly with the
34
+ // tsx ESM loader registered via execArgv so TypeScript is transpiled on-demand.
35
+ import { existsSync } from 'fs';
36
+
37
+ let _workerFile: string;
38
+ let _workerExecArgv: string[] = [];
39
+
40
+ try {
41
+ const dir = dirname(fileURLToPath(import.meta.url));
42
+ const jsPath = join(dir, 'serialize-worker.js');
43
+ const tsPath = join(dir, 'serialize-worker.ts');
44
+
45
+ if (existsSync(jsPath)) {
46
+ // Compiled output present (dist/ after tsup, or src/ after manual compile)
47
+ _workerFile = jsPath;
48
+ } else if (existsSync(tsPath)) {
49
+ // Source-only environment (Vitest, tsx dev runner) — run via tsx loader.
50
+ // Use '--import tsx' (not 'tsx/esm') so that tsx registers both CJS and ESM
51
+ // hooks, giving it full control over .js → .ts extension remapping for
52
+ // sub-imports (encryption.js → encryption.ts, etc.). tsx/esm alone is
53
+ // unreliable for this inside worker threads on Node 22.
54
+ _workerFile = tsPath;
55
+ _workerExecArgv = ['--import', 'tsx'];
56
+ } else {
57
+ _workerFile = jsPath; // will fail at runtime → pool marks itself unavailable
58
+ }
59
+ } catch {
60
+ // CJS fallback — __dirname is available natively in CJS (and shimmed by tsup for ESM).
61
+ _workerFile = join(__dirname, 'serialize-worker.js');
62
+ }
63
+
64
+ export interface WorkerPoolOptions {
65
+ /** Base64-encoded raw key bytes. Empty string = no encryption (pool becomes a no-op pass-through). */
66
+ keyBase64: string;
67
+ mode: EncryptionMode;
68
+ prevKeyBase64?: string;
69
+ prevMode?: EncryptionMode;
70
+ /** Number of worker threads. Default: min(4, availableCPUs). */
71
+ size?: number;
72
+ }
73
+
74
+ type PendingEntry = { resolve: (v: string) => void; reject: (e: Error) => void };
75
+
76
+ export class WorkerPool {
77
+ private readonly workers: Worker[] = [];
78
+ private readonly pending: Map<number, PendingEntry>[] = [];
79
+ private _nextId = 0;
80
+ private _robin = 0;
81
+ private _available = false;
82
+
83
+ constructor(opts: WorkerPoolOptions) {
84
+ const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
85
+ const workerData = {
86
+ keyBase64: opts.keyBase64,
87
+ mode: opts.mode,
88
+ prevKeyBase64: opts.prevKeyBase64 ?? '',
89
+ prevMode: opts.prevMode,
90
+ };
91
+
92
+ try {
93
+ for (let i = 0; i < size; i++) {
94
+ const worker = new Worker(_workerFile, {
95
+ workerData,
96
+ execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : undefined,
97
+ });
98
+ const pending = new Map<number, PendingEntry>();
99
+
100
+ worker.on('message', (msg: { id: number; result?: string; error?: string }) => {
101
+ const entry = pending.get(msg.id);
102
+ if (!entry) return;
103
+ pending.delete(msg.id);
104
+ // Unref the worker once its queue is empty so idle workers don't
105
+ // prevent the process from exiting (e.g. CLI scripts, benchmarks).
106
+ if (pending.size === 0) worker.unref();
107
+ if (msg.error !== undefined) {
108
+ entry.reject(new Error(msg.error));
109
+ } else {
110
+ entry.resolve(msg.result!);
111
+ }
112
+ });
113
+
114
+ worker.on('error', (err: Error) => {
115
+ // On unhandled worker error, reject all in-flight requests for this worker.
116
+ for (const [, entry] of pending) entry.reject(err);
117
+ pending.clear();
118
+ worker.unref();
119
+ });
120
+
121
+ // Workers start unreffed; they are re-reffed in _dispatch while a task
122
+ // is in flight, then unreffed again once the pending queue drains.
123
+ worker.unref();
124
+
125
+ this.workers.push(worker);
126
+ this.pending.push(pending);
127
+ }
128
+ this._available = true;
129
+ } catch {
130
+ // Worker creation failed (e.g., missing file, restricted runtime).
131
+ // Callers check isAvailable before using the pool.
132
+ this._destroy();
133
+ }
134
+ }
135
+
136
+ get isAvailable(): boolean { return this._available; }
137
+
138
+ /** Encrypt a JSON string in a worker thread. Returns the same encrypted envelope string as CacheEncryption.encrypt(). */
139
+ encrypt(payload: string): Promise<string> {
140
+ return this._dispatch('encrypt', payload);
141
+ }
142
+
143
+ /** Decrypt an encrypted envelope string in a worker thread. Returns the original JSON string. */
144
+ decrypt(payload: string): Promise<string> {
145
+ return this._dispatch('decrypt', payload);
146
+ }
147
+
148
+ private _dispatch(type: 'encrypt' | 'decrypt', payload: string): Promise<string> {
149
+ const id = this._nextId++;
150
+ const idx = this._robin;
151
+ const worker = this.workers[idx];
152
+ const pending = this.pending[idx];
153
+ this._robin = (this._robin + 1) % this.workers.length;
154
+
155
+ return new Promise<string>((resolve, reject) => {
156
+ pending.set(id, { resolve, reject });
157
+ // Re-ref the worker while this request is in flight so the event loop
158
+ // stays alive even in short-lived scripts (benchmarks, CLI tools).
159
+ worker.ref();
160
+ worker.postMessage({ id, type, payload });
161
+ });
162
+ }
163
+
164
+ /** Terminate all worker threads. In-flight promises are rejected. */
165
+ async destroy(): Promise<void> {
166
+ this._available = false;
167
+ this._destroy();
168
+ }
169
+
170
+ private _destroy(): void {
171
+ for (let i = 0; i < this.workers.length; i++) {
172
+ for (const [, entry] of this.pending[i] ?? []) {
173
+ entry.reject(new Error('WorkerPool destroyed'));
174
+ }
175
+ this.pending[i]?.clear();
176
+ this.workers[i]?.terminate().catch(() => {});
177
+ }
178
+ }
179
+ }
180
+
181
+ 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
+ }
190
+ }