tricache 0.7.1 → 0.9.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.
- package/LICENSE +21 -21
- package/README.md +89 -1371
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-DVvroyqA.d.ts +886 -0
- package/dist/cache-service-KI5ACF3F.js +12 -0
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/cli.cjs +3122 -495
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +121 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2846 -494
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1559 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono/index.cjs +7760 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/hono-VA9A1m0I.d.ts +371 -0
- package/dist/http/index.cjs +3281 -587
- package/dist/http/index.d.ts +85 -23
- package/dist/http/index.js +176 -78
- package/dist/index.cjs +7212 -2505
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2787 -487
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2804 -501
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +48 -10
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1619 -415
- package/src/cli.ts +137 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +284 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/hono/index.ts +316 -0
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +44 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +509 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +315 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
package/src/worker-pool.ts
CHANGED
|
@@ -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
|
+
}
|