tricache 0.7.1 → 0.8.0

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.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -1,299 +1,299 @@
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 os from 'os';
30
- import type { EncryptionMode } from './encryption.js';
31
- import type { CompressionAlgorithm } from './compression.js';
32
-
33
- // Locate the serialize-worker entry point.
34
- // Production: tsup emits compile .js files as flat siblings → use .js path.
35
- // Development / test (tsx, Vitest): the .ts source is used directly with the
36
- // tsx ESM loader registered via execArgv so TypeScript is transpiled on-demand.
37
- import { existsSync } from 'fs';
38
-
39
- let _workerFile: string;
40
- let _workerExecArgv: string[] = [];
41
-
42
- try {
43
- const dir = dirname(fileURLToPath(import.meta.url));
44
- const jsPath = join(dir, 'serialize-worker.js');
45
- const tsPath = join(dir, 'serialize-worker.ts');
46
-
47
- if (existsSync(jsPath)) {
48
- // Compiled output present (dist/ after tsup, or src/ after manual compile)
49
- _workerFile = jsPath;
50
- } else if (existsSync(tsPath)) {
51
- // Source-only environment (Vitest, tsx dev runner) — run via tsx loader.
52
- // Use '--import tsx' (not 'tsx/esm') so that tsx registers both CJS and ESM
53
- // hooks, giving it full control over .js → .ts extension remapping for
54
- // sub-imports (encryption.js → encryption.ts, etc.). tsx/esm alone is
55
- // unreliable for this inside worker threads on Node 22.
56
- _workerFile = tsPath;
57
- _workerExecArgv = ['--import', 'tsx'];
58
- } else {
59
- _workerFile = jsPath; // will fail at runtime → pool marks itself unavailable
60
- }
61
- } catch {
62
- // CJS fallback — __dirname is available natively in CJS (and shimmed by tsup for ESM).
63
- _workerFile = join(__dirname, 'serialize-worker.js');
64
- }
65
-
66
- export interface WorkerPoolOptions {
67
- /** Base64-encoded raw key bytes. Empty string = no encryption (pool becomes a no-op pass-through). */
68
- keyBase64: string;
69
- mode: EncryptionMode;
70
- prevKeyBase64?: string;
71
- prevMode?: EncryptionMode;
72
- compression?: CompressionAlgorithm;
73
- compressionThresholdBytes?: number;
74
- /** Number of worker threads. Default: min(4, availableCPUs). */
75
- size?: number;
76
- }
77
-
78
- type PendingEntry = { resolve: (v: string) => void; reject: (e: Error) => void };
79
-
80
- /**
81
- * Safely extracts or allocates a transferable ArrayBuffer for worker_threads postMessage.
82
- *
83
- * Prevents detach corruption on Node's shared 8 KB internal Buffer pool (Buffer.poolSize):
84
- * - If the buffer owns the entire underlying ArrayBuffer (byteOffset === 0 && byteLength === buffer.byteLength),
85
- * it can be transferred directly with zero copies.
86
- * - For large pooled slices (>= 128 KB), copies to an isolated ArrayBuffer so transferring it
87
- * detaches only the copy and never the main-thread pooled slab.
88
- * - For smaller pooled slices (< 128 KB), returns null to let structured cloning handle it without transfer.
89
- */
90
- export function getTransferableArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffer | null {
91
- if (buf.buffer instanceof ArrayBuffer) {
92
- if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
93
- return buf.buffer;
94
- }
95
- }
96
-
97
- if (buf.byteLength >= 131_072) {
98
- const copy = new ArrayBuffer(buf.byteLength);
99
- new Uint8Array(copy).set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
100
- return copy;
101
- }
102
-
103
- return null;
104
- }
105
-
106
- export class WorkerPool {
107
- private workers: Worker[] = [];
108
- private pending: Map<number, PendingEntry>[] = [];
109
- private _nextId = 0;
110
- private _robin = 0;
111
- private _available = false;
112
-
113
- constructor(opts: WorkerPoolOptions) {
114
- try {
115
- const { workers, pending } = this._spawnWorkers(opts);
116
- this.workers = workers;
117
- this.pending = pending;
118
- this._available = true;
119
- } catch {
120
- // Worker creation failed (e.g., missing file, restricted runtime).
121
- // Callers check isAvailable before using the pool.
122
- this._destroy();
123
- }
124
- }
125
-
126
- private _spawnWorkers(opts: WorkerPoolOptions): { workers: Worker[]; pending: Map<number, PendingEntry>[] } {
127
- const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
128
- const workerData = {
129
- keyBase64: opts.keyBase64,
130
- mode: opts.mode,
131
- prevKeyBase64: opts.prevKeyBase64 ?? '',
132
- prevMode: opts.prevMode,
133
- compression: opts.compression ?? 'none',
134
- compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024,
135
- };
136
-
137
- const workers: Worker[] = [];
138
- const pendingList: Map<number, PendingEntry>[] = [];
139
-
140
- const createWorker = (index: number): Worker => {
141
- const worker = new Worker(_workerFile, {
142
- workerData,
143
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : undefined,
144
- });
145
- const pending = pendingList[index] ?? new Map<number, PendingEntry>();
146
- if (!pendingList[index]) pendingList[index] = pending;
147
-
148
- worker.on('message', (msg: { id: number; result?: string | Uint8Array; error?: string; isTransfer?: boolean }) => {
149
- const entry = pending.get(msg.id);
150
- if (!entry) return;
151
- pending.delete(msg.id);
152
- if (pending.size === 0) worker.unref();
153
- if (msg.error !== undefined) {
154
- entry.reject(new Error(msg.error));
155
- } else if (msg.result !== undefined) {
156
- if (typeof msg.result === 'string') {
157
- entry.resolve(msg.result);
158
- } else {
159
- entry.resolve(Buffer.from(msg.result.buffer, msg.result.byteOffset, msg.result.byteLength).toString('utf8'));
160
- }
161
- }
162
- });
163
-
164
- worker.on('error', (err: Error) => {
165
- for (const [, entry] of pending) entry.reject(err);
166
- pending.clear();
167
- worker.unref();
168
- });
169
-
170
- worker.on('exit', (exitCode: number) => {
171
- for (const [, entry] of pending) {
172
- entry.reject(new Error(`Worker thread exited unexpectedly with code ${exitCode}`));
173
- }
174
- pending.clear();
175
- worker.unref();
176
-
177
- // If pool is still active and worker exited with non-zero code, auto-replace
178
- if (this._available && exitCode !== 0 && workers[index] === worker) {
179
- try {
180
- workers[index] = createWorker(index);
181
- } catch { /* ok */ }
182
- }
183
- });
184
-
185
- worker.unref();
186
- return worker;
187
- };
188
-
189
- for (let i = 0; i < size; i++) {
190
- const worker = createWorker(i);
191
- workers.push(worker);
192
- }
193
-
194
- return { workers, pending: pendingList };
195
- }
196
-
197
- /**
198
- * Gracefully drain in-flight tasks and re-initialize workers with updated key material.
199
- * Atomically swaps workers so new requests immediately route to new workers,
200
- * while existing in-flight operations complete on old workers before termination.
201
- */
202
- async drainAndReinit(opts: WorkerPoolOptions): Promise<void> {
203
- const { workers: newWorkers, pending: newPending } = this._spawnWorkers(opts);
204
-
205
- // Atomically swap references
206
- const oldWorkers = this.workers;
207
- const oldPending = this.pending;
208
- this.workers = newWorkers;
209
- this.pending = newPending;
210
- this._robin = 0;
211
- this._available = true;
212
-
213
- // Await drain of in-flight tasks on old workers
214
- const start = Date.now();
215
- while (oldPending.some(m => m.size > 0)) {
216
- if (Date.now() - start > 5_000) break; // 5s timeout guard
217
- await new Promise(r => setTimeout(r, 10));
218
- }
219
-
220
- // Cleanly terminate old workers
221
- for (let i = 0; i < oldWorkers.length; i++) {
222
- for (const [, entry] of oldPending[i] ?? []) {
223
- entry.reject(new Error('WorkerPool replaced during key rotation'));
224
- }
225
- oldPending[i]?.clear();
226
- oldWorkers[i]?.terminate().catch(() => {});
227
- }
228
- }
229
-
230
- get isAvailable(): boolean { return this._available; }
231
-
232
- /** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
233
- encrypt(payload: string | Buffer | Uint8Array): Promise<string> {
234
- return this._dispatch('encrypt', payload);
235
- }
236
-
237
- /** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
238
- decrypt(payload: string | Buffer | Uint8Array): Promise<string> {
239
- return this._dispatch('decrypt', payload);
240
- }
241
-
242
- private _dispatch(type: 'encrypt' | 'decrypt', payload: string | Buffer | Uint8Array): Promise<string> {
243
- if (!this._available || this.workers.length === 0) {
244
- return Promise.reject(new Error('WorkerPool is not available'));
245
- }
246
- const id = this._nextId++;
247
- const idx = this._robin;
248
- const worker = this.workers[idx];
249
- const pending = this.pending[idx];
250
- this._robin = (this._robin + 1) % this.workers.length;
251
-
252
- let transferable: ArrayBuffer | null = null;
253
- let dataToSend: string | Uint8Array = typeof payload === 'string' ? payload : payload;
254
-
255
- if (typeof payload !== 'string') {
256
- transferable = getTransferableArrayBuffer(payload);
257
- if (transferable) {
258
- dataToSend = new Uint8Array(transferable);
259
- }
260
- } else if (payload.length >= 131_072) {
261
- const buf = Buffer.from(payload, 'utf8');
262
- transferable = getTransferableArrayBuffer(buf);
263
- if (transferable) {
264
- dataToSend = new Uint8Array(transferable);
265
- }
266
- }
267
-
268
- const transferList = transferable ? [transferable] : [];
269
-
270
- return new Promise<string>((resolve, reject) => {
271
- pending.set(id, { resolve, reject });
272
- // Re-ref the worker while this request is in flight so the event loop
273
- // stays alive even in short-lived scripts (benchmarks, CLI tools).
274
- worker.ref();
275
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
276
- });
277
- }
278
-
279
- /** Terminate all worker threads. In-flight promises are rejected. */
280
- async destroy(): Promise<void> {
281
- this._available = false;
282
- this._destroy();
283
- }
284
-
285
- private _destroy(): void {
286
- for (let i = 0; i < this.workers.length; i++) {
287
- for (const [, entry] of this.pending[i] ?? []) {
288
- entry.reject(new Error('WorkerPool destroyed'));
289
- }
290
- this.pending[i]?.clear();
291
- this.workers[i]?.terminate().catch(() => {});
292
- }
293
- }
294
- }
295
-
296
- function availableCpus(): number {
297
- // Node >= 22.13.0 (engines constraint) always has availableParallelism.
298
- return os.availableParallelism?.() ?? os.cpus().length;
299
- }
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 os from 'os';
30
+ import type { EncryptionMode } from './encryption.js';
31
+ import type { CompressionAlgorithm } from './compression.js';
32
+
33
+ // Locate the serialize-worker entry point.
34
+ // Production: tsup emits compile .js files as flat siblings → use .js path.
35
+ // Development / test (tsx, Vitest): the .ts source is used directly with the
36
+ // tsx ESM loader registered via execArgv so TypeScript is transpiled on-demand.
37
+ import { existsSync } from 'fs';
38
+
39
+ let _workerFile: string;
40
+ let _workerExecArgv: string[] = [];
41
+
42
+ try {
43
+ const dir = dirname(fileURLToPath(import.meta.url));
44
+ const jsPath = join(dir, 'serialize-worker.js');
45
+ const tsPath = join(dir, 'serialize-worker.ts');
46
+
47
+ if (existsSync(jsPath)) {
48
+ // Compiled output present (dist/ after tsup, or src/ after manual compile)
49
+ _workerFile = jsPath;
50
+ } else if (existsSync(tsPath)) {
51
+ // Source-only environment (Vitest, tsx dev runner) — run via tsx loader.
52
+ // Use '--import tsx' (not 'tsx/esm') so that tsx registers both CJS and ESM
53
+ // hooks, giving it full control over .js → .ts extension remapping for
54
+ // sub-imports (encryption.js → encryption.ts, etc.). tsx/esm alone is
55
+ // unreliable for this inside worker threads on Node 22.
56
+ _workerFile = tsPath;
57
+ _workerExecArgv = ['--import', 'tsx'];
58
+ } else {
59
+ _workerFile = jsPath; // will fail at runtime → pool marks itself unavailable
60
+ }
61
+ } catch {
62
+ // CJS fallback — __dirname is available natively in CJS (and shimmed by tsup for ESM).
63
+ _workerFile = join(__dirname, 'serialize-worker.js');
64
+ }
65
+
66
+ export interface WorkerPoolOptions {
67
+ /** Base64-encoded raw key bytes. Empty string = no encryption (pool becomes a no-op pass-through). */
68
+ keyBase64: string;
69
+ mode: EncryptionMode;
70
+ prevKeyBase64?: string;
71
+ prevMode?: EncryptionMode;
72
+ compression?: CompressionAlgorithm;
73
+ compressionThresholdBytes?: number;
74
+ /** Number of worker threads. Default: min(4, availableCPUs). */
75
+ size?: number;
76
+ }
77
+
78
+ type PendingEntry = { resolve: (v: string) => void; reject: (e: Error) => void };
79
+
80
+ /**
81
+ * Safely extracts or allocates a transferable ArrayBuffer for worker_threads postMessage.
82
+ *
83
+ * Prevents detach corruption on Node's shared 8 KB internal Buffer pool (Buffer.poolSize):
84
+ * - If the buffer owns the entire underlying ArrayBuffer (byteOffset === 0 && byteLength === buffer.byteLength),
85
+ * it can be transferred directly with zero copies.
86
+ * - For large pooled slices (>= 128 KB), copies to an isolated ArrayBuffer so transferring it
87
+ * detaches only the copy and never the main-thread pooled slab.
88
+ * - For smaller pooled slices (< 128 KB), returns null to let structured cloning handle it without transfer.
89
+ */
90
+ export function getTransferableArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffer | null {
91
+ if (buf.buffer instanceof ArrayBuffer) {
92
+ if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
93
+ return buf.buffer;
94
+ }
95
+ }
96
+
97
+ if (buf.byteLength >= 131_072) {
98
+ const copy = new ArrayBuffer(buf.byteLength);
99
+ new Uint8Array(copy).set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
100
+ return copy;
101
+ }
102
+
103
+ return null;
104
+ }
105
+
106
+ export class WorkerPool {
107
+ private workers: Worker[] = [];
108
+ private pending: Map<number, PendingEntry>[] = [];
109
+ private _nextId = 0;
110
+ private _robin = 0;
111
+ private _available = false;
112
+
113
+ constructor(opts: WorkerPoolOptions) {
114
+ try {
115
+ const { workers, pending } = this._spawnWorkers(opts);
116
+ this.workers = workers;
117
+ this.pending = pending;
118
+ this._available = true;
119
+ } catch {
120
+ // Worker creation failed (e.g., missing file, restricted runtime).
121
+ // Callers check isAvailable before using the pool.
122
+ this._destroy();
123
+ }
124
+ }
125
+
126
+ private _spawnWorkers(opts: WorkerPoolOptions): { workers: Worker[]; pending: Map<number, PendingEntry>[] } {
127
+ const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
128
+ const workerData = {
129
+ keyBase64: opts.keyBase64,
130
+ mode: opts.mode,
131
+ prevKeyBase64: opts.prevKeyBase64 ?? '',
132
+ prevMode: opts.prevMode,
133
+ compression: opts.compression ?? 'none',
134
+ compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024,
135
+ };
136
+
137
+ const workers: Worker[] = [];
138
+ const pendingList: Map<number, PendingEntry>[] = [];
139
+
140
+ const createWorker = (index: number): Worker => {
141
+ const worker = new Worker(_workerFile, {
142
+ workerData,
143
+ execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : undefined,
144
+ });
145
+ const pending = pendingList[index] ?? new Map<number, PendingEntry>();
146
+ if (!pendingList[index]) pendingList[index] = pending;
147
+
148
+ worker.on('message', (msg: { id: number; result?: string | Uint8Array; error?: string; isTransfer?: boolean }) => {
149
+ const entry = pending.get(msg.id);
150
+ if (!entry) return;
151
+ pending.delete(msg.id);
152
+ if (pending.size === 0) worker.unref();
153
+ if (msg.error !== undefined) {
154
+ entry.reject(new Error(msg.error));
155
+ } else if (msg.result !== undefined) {
156
+ if (typeof msg.result === 'string') {
157
+ entry.resolve(msg.result);
158
+ } else {
159
+ entry.resolve(Buffer.from(msg.result.buffer, msg.result.byteOffset, msg.result.byteLength).toString('utf8'));
160
+ }
161
+ }
162
+ });
163
+
164
+ worker.on('error', (err: Error) => {
165
+ for (const [, entry] of pending) entry.reject(err);
166
+ pending.clear();
167
+ worker.unref();
168
+ });
169
+
170
+ worker.on('exit', (exitCode: number) => {
171
+ for (const [, entry] of pending) {
172
+ entry.reject(new Error(`Worker thread exited unexpectedly with code ${exitCode}`));
173
+ }
174
+ pending.clear();
175
+ worker.unref();
176
+
177
+ // If pool is still active and worker exited with non-zero code, auto-replace
178
+ if (this._available && exitCode !== 0 && workers[index] === worker) {
179
+ try {
180
+ workers[index] = createWorker(index);
181
+ } catch { /* ok */ }
182
+ }
183
+ });
184
+
185
+ worker.unref();
186
+ return worker;
187
+ };
188
+
189
+ for (let i = 0; i < size; i++) {
190
+ const worker = createWorker(i);
191
+ workers.push(worker);
192
+ }
193
+
194
+ return { workers, pending: pendingList };
195
+ }
196
+
197
+ /**
198
+ * Gracefully drain in-flight tasks and re-initialize workers with updated key material.
199
+ * Atomically swaps workers so new requests immediately route to new workers,
200
+ * while existing in-flight operations complete on old workers before termination.
201
+ */
202
+ async drainAndReinit(opts: WorkerPoolOptions): Promise<void> {
203
+ const { workers: newWorkers, pending: newPending } = this._spawnWorkers(opts);
204
+
205
+ // Atomically swap references
206
+ const oldWorkers = this.workers;
207
+ const oldPending = this.pending;
208
+ this.workers = newWorkers;
209
+ this.pending = newPending;
210
+ this._robin = 0;
211
+ this._available = true;
212
+
213
+ // Await drain of in-flight tasks on old workers
214
+ const start = Date.now();
215
+ while (oldPending.some(m => m.size > 0)) {
216
+ if (Date.now() - start > 5_000) break; // 5s timeout guard
217
+ await new Promise(r => setTimeout(r, 10));
218
+ }
219
+
220
+ // Cleanly terminate old workers
221
+ for (let i = 0; i < oldWorkers.length; i++) {
222
+ for (const [, entry] of oldPending[i] ?? []) {
223
+ entry.reject(new Error('WorkerPool replaced during key rotation'));
224
+ }
225
+ oldPending[i]?.clear();
226
+ oldWorkers[i]?.terminate().catch(() => {});
227
+ }
228
+ }
229
+
230
+ get isAvailable(): boolean { return this._available; }
231
+
232
+ /** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
233
+ encrypt(payload: string | Buffer | Uint8Array): Promise<string> {
234
+ return this._dispatch('encrypt', payload);
235
+ }
236
+
237
+ /** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
238
+ decrypt(payload: string | Buffer | Uint8Array): Promise<string> {
239
+ return this._dispatch('decrypt', payload);
240
+ }
241
+
242
+ private _dispatch(type: 'encrypt' | 'decrypt', payload: string | Buffer | Uint8Array): Promise<string> {
243
+ if (!this._available || this.workers.length === 0) {
244
+ return Promise.reject(new Error('WorkerPool is not available'));
245
+ }
246
+ const id = this._nextId++;
247
+ const idx = this._robin;
248
+ const worker = this.workers[idx];
249
+ const pending = this.pending[idx];
250
+ this._robin = (this._robin + 1) % this.workers.length;
251
+
252
+ let transferable: ArrayBuffer | null = null;
253
+ let dataToSend: string | Uint8Array = typeof payload === 'string' ? payload : payload;
254
+
255
+ if (typeof payload !== 'string') {
256
+ transferable = getTransferableArrayBuffer(payload);
257
+ if (transferable) {
258
+ dataToSend = new Uint8Array(transferable);
259
+ }
260
+ } else if (payload.length >= 131_072) {
261
+ const buf = Buffer.from(payload, 'utf8');
262
+ transferable = getTransferableArrayBuffer(buf);
263
+ if (transferable) {
264
+ dataToSend = new Uint8Array(transferable);
265
+ }
266
+ }
267
+
268
+ const transferList = transferable ? [transferable] : [];
269
+
270
+ return new Promise<string>((resolve, reject) => {
271
+ pending.set(id, { resolve, reject });
272
+ // Re-ref the worker while this request is in flight so the event loop
273
+ // stays alive even in short-lived scripts (benchmarks, CLI tools).
274
+ worker.ref();
275
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
276
+ });
277
+ }
278
+
279
+ /** Terminate all worker threads. In-flight promises are rejected. */
280
+ async destroy(): Promise<void> {
281
+ this._available = false;
282
+ this._destroy();
283
+ }
284
+
285
+ private _destroy(): void {
286
+ for (let i = 0; i < this.workers.length; i++) {
287
+ for (const [, entry] of this.pending[i] ?? []) {
288
+ entry.reject(new Error('WorkerPool destroyed'));
289
+ }
290
+ this.pending[i]?.clear();
291
+ this.workers[i]?.terminate().catch(() => {});
292
+ }
293
+ }
294
+ }
295
+
296
+ function availableCpus(): number {
297
+ // Node >= 22.13.0 (engines constraint) always has availableParallelism.
298
+ return os.availableParallelism?.() ?? os.cpus().length;
299
+ }