tricache 0.6.0 → 0.6.2
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 +119 -0
- package/dist/chunk-F24NEZGQ.js +342 -0
- package/dist/index.cjs +494 -164
- package/dist/index.d.cts +125 -0
- package/dist/index.d.ts +1552 -18
- package/dist/index.js +3524 -25
- package/dist/serialize-worker.cjs +366 -0
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.d.ts +2 -0
- package/dist/serialize-worker.js +35 -0
- package/package.json +5 -5
- package/src/cache-service.ts +310 -93
- package/src/serialize-worker.ts +56 -0
- package/src/smart-memory-cache.ts +42 -1
- package/src/types.ts +99 -1
- package/src/worker-pool.ts +190 -0
- package/dist/cache-service.d.ts +0 -419
- package/dist/cache-service.d.ts.map +0 -1
- package/dist/cache-service.js +0 -1788
- package/dist/cache-service.js.map +0 -1
- package/dist/disk-tier.d.ts +0 -150
- package/dist/disk-tier.d.ts.map +0 -1
- package/dist/disk-tier.js +0 -808
- package/dist/disk-tier.js.map +0 -1
- package/dist/encryption.d.ts +0 -90
- package/dist/encryption.d.ts.map +0 -1
- package/dist/encryption.js +0 -393
- package/dist/encryption.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/smart-memory-cache.d.ts +0 -208
- package/dist/smart-memory-cache.d.ts.map +0 -1
- package/dist/smart-memory-cache.js +0 -933
- package/dist/smart-memory-cache.js.map +0 -1
- package/dist/types.d.ts +0 -537
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -20
- package/dist/types.js.map +0 -1
- package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
- package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
- package/dist/wasm/bloom-filter-wasm.js +0 -83
- package/dist/wasm/bloom-filter-wasm.js.map +0 -1
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption.
|
|
3
|
+
*
|
|
4
|
+
* Receives messages from WorkerPool:
|
|
5
|
+
* { id: number; type: 'encrypt'; payload: string }
|
|
6
|
+
* { id: number; type: 'decrypt'; payload: string }
|
|
7
|
+
*
|
|
8
|
+
* Posts back:
|
|
9
|
+
* { id: number; result: string } — on success
|
|
10
|
+
* { id: number; error: string } — on failure
|
|
11
|
+
*
|
|
12
|
+
* The encryption key and mode are received once via workerData at thread creation,
|
|
13
|
+
* so no key material travels with every per-message IPC call.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { parentPort, workerData } from 'worker_threads';
|
|
17
|
+
import { CacheEncryption } from './encryption';
|
|
18
|
+
import type { EncryptionMode } from './encryption';
|
|
19
|
+
import type { ILogger } from './types';
|
|
20
|
+
|
|
21
|
+
interface WorkerInit {
|
|
22
|
+
keyBase64: string;
|
|
23
|
+
mode: EncryptionMode;
|
|
24
|
+
prevKeyBase64: string | undefined;
|
|
25
|
+
prevMode: EncryptionMode | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
|
|
29
|
+
const silentLogger: ILogger = {
|
|
30
|
+
debug: () => {},
|
|
31
|
+
info: () => {},
|
|
32
|
+
warn: () => {},
|
|
33
|
+
error: () => {},
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const { keyBase64, mode, prevKeyBase64, prevMode } = workerData as WorkerInit;
|
|
37
|
+
|
|
38
|
+
const enc = new CacheEncryption(
|
|
39
|
+
keyBase64 || undefined,
|
|
40
|
+
silentLogger,
|
|
41
|
+
mode,
|
|
42
|
+
prevKeyBase64 || undefined,
|
|
43
|
+
prevMode,
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
parentPort!.on('message', ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string }) => {
|
|
47
|
+
try {
|
|
48
|
+
if (type === 'encrypt') {
|
|
49
|
+
parentPort!.postMessage({ id, result: enc.encrypt(payload) });
|
|
50
|
+
} else {
|
|
51
|
+
parentPort!.postMessage({ id, result: enc.decrypt(payload) });
|
|
52
|
+
}
|
|
53
|
+
} catch (e) {
|
|
54
|
+
parentPort!.postMessage({ id, error: (e as Error).message });
|
|
55
|
+
}
|
|
56
|
+
});
|
|
@@ -729,7 +729,48 @@ export class SmartMemoryCache {
|
|
|
729
729
|
return cleaned;
|
|
730
730
|
}
|
|
731
731
|
|
|
732
|
-
|
|
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
|
+
|
|
733
774
|
|
|
734
775
|
exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
|
|
735
776
|
const now = Date.now();
|
package/src/types.ts
CHANGED
|
@@ -221,7 +221,7 @@ 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
225
|
|
|
226
226
|
/** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
|
|
227
227
|
adaptiveTtl?: {
|
|
@@ -595,4 +595,102 @@ export interface CacheOptions {
|
|
|
595
595
|
* Default: `5000`.
|
|
596
596
|
*/
|
|
597
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
|
+
};
|
|
598
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
|
+
}
|