node-worker-pool-lite 0.1.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 -0
- package/README.md +223 -0
- package/examples/basic.js +24 -0
- package/examples/prime-worker.js +36 -0
- package/examples/promise.js +17 -0
- package/lib/index.d.ts +41 -0
- package/lib/index.js +1 -0
- package/lib/promise-worker-pool.js +18 -0
- package/lib/promise.d.ts +24 -0
- package/lib/promise.js +1 -0
- package/lib/worker-pool.js +243 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Arman Mikoyan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# Worker Pool
|
|
2
|
+
|
|
3
|
+
A lightweight Node.js `worker_threads` pool with callback and Promise APIs.
|
|
4
|
+
|
|
5
|
+
Worker Pool helps you move CPU-heavy work off the main event loop while keeping a small, predictable API. It supports named worker tasks, a fixed-size worker pool, queued jobs, worker replacement after failures, and TypeScript declarations.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Callback-first API from the main package entrypoint.
|
|
10
|
+
- Promise API from `worker-pool/promise`.
|
|
11
|
+
- Named task handlers inside worker files.
|
|
12
|
+
- Automatic task queueing when all workers are busy.
|
|
13
|
+
- Worker error propagation to callbacks or rejected promises.
|
|
14
|
+
- Graceful shutdown with `pool.destroy()`.
|
|
15
|
+
- ESM and TypeScript declaration support.
|
|
16
|
+
|
|
17
|
+
## Requirements
|
|
18
|
+
|
|
19
|
+
- Node.js 18 or newer.
|
|
20
|
+
- ESM projects, or files using `.mjs` / `"type": "module"`.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
npm install worker-pool
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
If you publish this under a scoped package name, install it with your final package name instead:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npm install @your-username/worker-pool
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
Create a worker file with named task handlers:
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
// worker.js
|
|
40
|
+
import { createWorkerHandler } from 'worker-pool';
|
|
41
|
+
|
|
42
|
+
createWorkerHandler({
|
|
43
|
+
double(value) {
|
|
44
|
+
return value * 2;
|
|
45
|
+
},
|
|
46
|
+
|
|
47
|
+
async hashPassword(input) {
|
|
48
|
+
return runExpensiveHash(input);
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Run tasks with the callback API:
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
// index.js
|
|
57
|
+
import { WorkerPool } from 'worker-pool';
|
|
58
|
+
|
|
59
|
+
const pool = new WorkerPool(new URL('./worker.js', import.meta.url), {
|
|
60
|
+
size: 4,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
pool.run('double', 21, async (error, result) => {
|
|
64
|
+
if (error) {
|
|
65
|
+
console.error(error);
|
|
66
|
+
await pool.destroy();
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
console.log(result); // 42
|
|
71
|
+
await pool.destroy();
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Promise API
|
|
76
|
+
|
|
77
|
+
Import from `worker-pool/promise` when you prefer `async` / `await`:
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
import { WorkerPool } from 'worker-pool/promise';
|
|
81
|
+
|
|
82
|
+
const pool = new WorkerPool(new URL('./worker.js', import.meta.url), {
|
|
83
|
+
size: 4,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
const result = await pool.run('double', 21);
|
|
88
|
+
console.log(result); // 42
|
|
89
|
+
} finally {
|
|
90
|
+
await pool.destroy();
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Worker Tasks
|
|
95
|
+
|
|
96
|
+
Workers are registered with `createWorkerHandler()`. Each key is the task name used by `pool.run()`.
|
|
97
|
+
|
|
98
|
+
```js
|
|
99
|
+
import { createWorkerHandler } from 'worker-pool';
|
|
100
|
+
|
|
101
|
+
createWorkerHandler({
|
|
102
|
+
resizeImage(payload) {
|
|
103
|
+
return resizeImage(payload);
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
generateReport(payload) {
|
|
107
|
+
return generateReport(payload);
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Handlers may be synchronous or asynchronous. If a handler throws, the error is passed to the callback API or rejects the Promise API.
|
|
113
|
+
|
|
114
|
+
## API
|
|
115
|
+
|
|
116
|
+
### `new WorkerPool(workerUrl, options)`
|
|
117
|
+
|
|
118
|
+
Creates a fixed-size pool of worker threads.
|
|
119
|
+
|
|
120
|
+
- `workerUrl`: a worker file URL or path passed to Node.js `new Worker()`.
|
|
121
|
+
- `options.size`: number of workers to start. Defaults to one less than the available CPU count.
|
|
122
|
+
- `options.workerOptions`: extra options passed to Node.js `new Worker()`.
|
|
123
|
+
|
|
124
|
+
```js
|
|
125
|
+
const pool = new WorkerPool(new URL('./worker.js', import.meta.url), {
|
|
126
|
+
size: 4,
|
|
127
|
+
workerOptions: {
|
|
128
|
+
resourceLimits: {
|
|
129
|
+
maxOldGenerationSizeMb: 128,
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### `pool.run(name, payload, callback)`
|
|
136
|
+
|
|
137
|
+
Queues a named task and calls `callback(error, result)` when the task completes.
|
|
138
|
+
|
|
139
|
+
```js
|
|
140
|
+
pool.run('double', 21, (error, result) => {
|
|
141
|
+
if (error) {
|
|
142
|
+
console.error(error);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
console.log(result);
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
You can omit `payload` for tasks that do not need input:
|
|
151
|
+
|
|
152
|
+
```js
|
|
153
|
+
pool.run('refreshCache', error => {
|
|
154
|
+
if (error) {
|
|
155
|
+
console.error(error);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### `pool.run(name, payload)` from `worker-pool/promise`
|
|
161
|
+
|
|
162
|
+
Queues a named task and returns a promise.
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
const result = await pool.run('double', 21);
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### `pool.destroy()`
|
|
169
|
+
|
|
170
|
+
Terminates all workers and rejects queued work.
|
|
171
|
+
|
|
172
|
+
```js
|
|
173
|
+
await pool.destroy();
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### `createWorkerHandler(handlers)`
|
|
177
|
+
|
|
178
|
+
Registers named task handlers inside a worker file.
|
|
179
|
+
|
|
180
|
+
```js
|
|
181
|
+
createWorkerHandler({
|
|
182
|
+
taskName(payload) {
|
|
183
|
+
return doWork(payload);
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## Examples
|
|
189
|
+
|
|
190
|
+
This repository includes runnable examples:
|
|
191
|
+
|
|
192
|
+
```sh
|
|
193
|
+
node examples/basic.js
|
|
194
|
+
node examples/promise.js
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## Development
|
|
198
|
+
|
|
199
|
+
Run the test suite:
|
|
200
|
+
|
|
201
|
+
```sh
|
|
202
|
+
npm test
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Preview the package contents before publishing:
|
|
206
|
+
|
|
207
|
+
```sh
|
|
208
|
+
npm pack --dry-run
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Publishing Notes
|
|
212
|
+
|
|
213
|
+
Before publishing to npm:
|
|
214
|
+
|
|
215
|
+
- Choose a unique package name and update `package.json`.
|
|
216
|
+
- Add `author`, `repository`, `homepage`, and `bugs` fields to `package.json`.
|
|
217
|
+
- Update `LICENSE` with your name.
|
|
218
|
+
- Run `npm test` and `npm pack --dry-run`.
|
|
219
|
+
- Publish scoped public packages with `npm publish --access public`.
|
|
220
|
+
|
|
221
|
+
## License
|
|
222
|
+
|
|
223
|
+
MIT
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { WorkerPool } from '../lib/index.js';
|
|
2
|
+
|
|
3
|
+
const pool = new WorkerPool(new URL('./prime-worker.js', import.meta.url), {
|
|
4
|
+
size: 3,
|
|
5
|
+
});
|
|
6
|
+
|
|
7
|
+
let pendingTasks = 2;
|
|
8
|
+
|
|
9
|
+
pool.run('primes', { count: 10 }, handleResult);
|
|
10
|
+
pool.run('primes', { count: 20 }, handleResult);
|
|
11
|
+
|
|
12
|
+
async function handleResult(error, primes) {
|
|
13
|
+
pendingTasks -= 1;
|
|
14
|
+
|
|
15
|
+
if (error) {
|
|
16
|
+
console.error(error);
|
|
17
|
+
} else {
|
|
18
|
+
console.log(primes);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (pendingTasks === 0) {
|
|
22
|
+
await pool.destroy();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { createWorkerHandler } from '../lib/index.js';
|
|
2
|
+
|
|
3
|
+
createWorkerHandler({
|
|
4
|
+
primes({ count = 1 } = {}) {
|
|
5
|
+
return generatePrimes(count);
|
|
6
|
+
},
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
function generatePrimes(count) {
|
|
10
|
+
const primes = [];
|
|
11
|
+
let candidate = 2;
|
|
12
|
+
|
|
13
|
+
while (primes.length < count) {
|
|
14
|
+
if (isPrime(candidate)) {
|
|
15
|
+
primes.push(candidate);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
candidate += 1;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return primes;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function isPrime(value) {
|
|
25
|
+
if (value < 2) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
for (let divisor = 2; divisor * divisor <= value; divisor += 1) {
|
|
30
|
+
if (value % divisor === 0) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { WorkerPool } from '../lib/promise.js';
|
|
2
|
+
|
|
3
|
+
const pool = new WorkerPool(new URL('./prime-worker.js', import.meta.url), {
|
|
4
|
+
size: 3,
|
|
5
|
+
});
|
|
6
|
+
|
|
7
|
+
try {
|
|
8
|
+
const [firstBatch, secondBatch] = await Promise.all([
|
|
9
|
+
pool.run('primes', { count: 10 }),
|
|
10
|
+
pool.run('primes', { count: 20 }),
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
console.log(firstBatch);
|
|
14
|
+
console.log(secondBatch);
|
|
15
|
+
} finally {
|
|
16
|
+
await pool.destroy();
|
|
17
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { WorkerOptions } from 'node:worker_threads';
|
|
2
|
+
|
|
3
|
+
export interface WorkerPoolOptions {
|
|
4
|
+
size?: number;
|
|
5
|
+
workerOptions?: WorkerOptions;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type WorkerTaskHandler<TPayload = unknown, TResult = unknown> = (
|
|
9
|
+
payload: TPayload,
|
|
10
|
+
) => TResult | Promise<TResult>;
|
|
11
|
+
|
|
12
|
+
export type WorkerTaskCallback<TResult = unknown> = (
|
|
13
|
+
error: Error | null,
|
|
14
|
+
result?: TResult,
|
|
15
|
+
) => void;
|
|
16
|
+
|
|
17
|
+
export class WorkerPool {
|
|
18
|
+
constructor(workerUrl: URL | string, options?: WorkerPoolOptions);
|
|
19
|
+
|
|
20
|
+
readonly size: number;
|
|
21
|
+
readonly queuedTaskCount: number;
|
|
22
|
+
readonly busyWorkerCount: number;
|
|
23
|
+
readonly idleWorkerCount: number;
|
|
24
|
+
|
|
25
|
+
run<TPayload = unknown, TResult = unknown>(
|
|
26
|
+
name: string,
|
|
27
|
+
payload: TPayload,
|
|
28
|
+
callback: WorkerTaskCallback<TResult>,
|
|
29
|
+
): void;
|
|
30
|
+
|
|
31
|
+
run<TResult = unknown>(
|
|
32
|
+
name: string,
|
|
33
|
+
callback: WorkerTaskCallback<TResult>,
|
|
34
|
+
): void;
|
|
35
|
+
|
|
36
|
+
destroy(): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function createWorkerHandler(
|
|
40
|
+
handlers: Record<string, WorkerTaskHandler>,
|
|
41
|
+
): void;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { WorkerPool, createWorkerHandler } from './worker-pool.js';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { WorkerPool as CallbackWorkerPool, createWorkerHandler } from './worker-pool.js';
|
|
2
|
+
|
|
3
|
+
export { createWorkerHandler };
|
|
4
|
+
|
|
5
|
+
export class WorkerPool extends CallbackWorkerPool {
|
|
6
|
+
run(name, payload) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
super.run(name, payload, (error, result) => {
|
|
9
|
+
if (error) {
|
|
10
|
+
reject(error);
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
resolve(result);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}
|
package/lib/promise.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { WorkerPoolOptions } from './index.js';
|
|
2
|
+
|
|
3
|
+
export type {
|
|
4
|
+
WorkerPoolOptions,
|
|
5
|
+
WorkerTaskHandler,
|
|
6
|
+
} from './index.js';
|
|
7
|
+
|
|
8
|
+
export { createWorkerHandler } from './index.js';
|
|
9
|
+
|
|
10
|
+
export class WorkerPool {
|
|
11
|
+
constructor(workerUrl: URL | string, options?: WorkerPoolOptions);
|
|
12
|
+
|
|
13
|
+
readonly size: number;
|
|
14
|
+
readonly queuedTaskCount: number;
|
|
15
|
+
readonly busyWorkerCount: number;
|
|
16
|
+
readonly idleWorkerCount: number;
|
|
17
|
+
|
|
18
|
+
run<TPayload = unknown, TResult = unknown>(
|
|
19
|
+
name: string,
|
|
20
|
+
payload?: TPayload,
|
|
21
|
+
): Promise<TResult>;
|
|
22
|
+
|
|
23
|
+
destroy(): Promise<void>;
|
|
24
|
+
}
|
package/lib/promise.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { WorkerPool, createWorkerHandler } from './promise-worker-pool.js';
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import { Worker, parentPort as defaultParentPort } from 'node:worker_threads';
|
|
3
|
+
|
|
4
|
+
export class WorkerPool {
|
|
5
|
+
#idleWorkers = [];
|
|
6
|
+
#isDestroyed = false;
|
|
7
|
+
#queue = [];
|
|
8
|
+
#runningTasks = new Map();
|
|
9
|
+
#workerOptions;
|
|
10
|
+
#workerUrl;
|
|
11
|
+
#workers = new Set();
|
|
12
|
+
|
|
13
|
+
constructor(workerUrl, options = {}) {
|
|
14
|
+
if (!workerUrl) {
|
|
15
|
+
throw new TypeError('WorkerPool requires a worker file URL or path.');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const size = options.size ?? defaultPoolSize();
|
|
19
|
+
if (!Number.isInteger(size) || size < 1) {
|
|
20
|
+
throw new RangeError('WorkerPool size must be a positive integer.');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
this.size = size;
|
|
24
|
+
this.#workerUrl = workerUrl;
|
|
25
|
+
this.#workerOptions = options.workerOptions ?? {};
|
|
26
|
+
|
|
27
|
+
for (let index = 0; index < this.size; index += 1) {
|
|
28
|
+
this.#spawnWorker();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
get queuedTaskCount() {
|
|
33
|
+
return this.#queue.length;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get busyWorkerCount() {
|
|
37
|
+
return this.#runningTasks.size;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
get idleWorkerCount() {
|
|
41
|
+
return this.#idleWorkers.length;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
run(name, payload, callback) {
|
|
45
|
+
if (typeof payload === 'function') {
|
|
46
|
+
callback = payload;
|
|
47
|
+
payload = undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (typeof callback !== 'function') {
|
|
51
|
+
throw new TypeError('WorkerPool.run requires a callback function.');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (this.#isDestroyed) {
|
|
55
|
+
queueMicrotask(() => callback(new Error('WorkerPool has been destroyed.')));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (typeof name !== 'string' || name.length === 0) {
|
|
60
|
+
queueMicrotask(() => callback(new TypeError('Task name must be a non-empty string.')));
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
this.#queue.push({
|
|
65
|
+
callback,
|
|
66
|
+
message: { name, payload },
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
this.#dispatch();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async destroy() {
|
|
73
|
+
if (this.#isDestroyed) {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
this.#isDestroyed = true;
|
|
78
|
+
|
|
79
|
+
const destroyError = new Error('WorkerPool was destroyed before the task completed.');
|
|
80
|
+
for (const task of this.#queue.splice(0)) {
|
|
81
|
+
this.#completeTask(task, destroyError);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const terminations = [...this.#workers].map(worker => worker.terminate());
|
|
85
|
+
this.#idleWorkers = [];
|
|
86
|
+
|
|
87
|
+
await Promise.allSettled(terminations);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#dispatch() {
|
|
91
|
+
while (!this.#isDestroyed && this.#idleWorkers.length > 0 && this.#queue.length > 0) {
|
|
92
|
+
const worker = this.#idleWorkers.shift();
|
|
93
|
+
|
|
94
|
+
if (!this.#workers.has(worker)) {
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const task = this.#queue.shift();
|
|
99
|
+
this.#runningTasks.set(worker, task);
|
|
100
|
+
|
|
101
|
+
try {
|
|
102
|
+
worker.postMessage(task.message);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
this.#runningTasks.delete(worker);
|
|
105
|
+
this.#idleWorkers.push(worker);
|
|
106
|
+
this.#completeTask(task, error);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#handleMessage(worker, message) {
|
|
112
|
+
const task = this.#runningTasks.get(worker);
|
|
113
|
+
if (!task) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
this.#runningTasks.delete(worker);
|
|
118
|
+
|
|
119
|
+
if (isWorkerResult(message)) {
|
|
120
|
+
if (message.ok) {
|
|
121
|
+
this.#completeTask(task, null, message.value);
|
|
122
|
+
} else {
|
|
123
|
+
this.#completeTask(task, createWorkerError(message.error));
|
|
124
|
+
}
|
|
125
|
+
} else {
|
|
126
|
+
this.#completeTask(task, null, message);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (!this.#isDestroyed && this.#workers.has(worker)) {
|
|
130
|
+
this.#idleWorkers.push(worker);
|
|
131
|
+
this.#dispatch();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
#retireWorker(worker, error) {
|
|
136
|
+
if (!this.#workers.has(worker)) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
this.#workers.delete(worker);
|
|
141
|
+
this.#idleWorkers = this.#idleWorkers.filter(idleWorker => idleWorker !== worker);
|
|
142
|
+
|
|
143
|
+
const task = this.#runningTasks.get(worker);
|
|
144
|
+
if (task) {
|
|
145
|
+
this.#runningTasks.delete(worker);
|
|
146
|
+
this.#completeTask(task, error);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (!this.#isDestroyed) {
|
|
150
|
+
this.#spawnWorker();
|
|
151
|
+
this.#dispatch();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#spawnWorker() {
|
|
156
|
+
const worker = new Worker(this.#workerUrl, this.#workerOptions);
|
|
157
|
+
|
|
158
|
+
worker.on('message', message => {
|
|
159
|
+
this.#handleMessage(worker, message);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
worker.on('error', error => {
|
|
163
|
+
this.#retireWorker(worker, error);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
worker.on('exit', code => {
|
|
167
|
+
const error = code === 0
|
|
168
|
+
? new Error('Worker exited before completing its current task.')
|
|
169
|
+
: new Error(`Worker exited with code ${code}.`);
|
|
170
|
+
|
|
171
|
+
this.#retireWorker(worker, error);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
this.#workers.add(worker);
|
|
175
|
+
this.#idleWorkers.push(worker);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
#completeTask(task, error, result) {
|
|
179
|
+
queueMicrotask(() => {
|
|
180
|
+
task.callback(error, result);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function createWorkerHandler(handlers, options = {}) {
|
|
186
|
+
const port = options.parentPort ?? defaultParentPort;
|
|
187
|
+
|
|
188
|
+
if (!port) {
|
|
189
|
+
throw new Error('createWorkerHandler must be called inside a worker thread.');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (!handlers || typeof handlers !== 'object') {
|
|
193
|
+
throw new TypeError('Task handlers must be provided as an object.');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
port.on('message', async ({ name, payload }) => {
|
|
197
|
+
try {
|
|
198
|
+
const handler = handlers[name];
|
|
199
|
+
|
|
200
|
+
if (typeof handler !== 'function') {
|
|
201
|
+
throw new Error(`Unknown task: ${String(name)}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const value = await handler(payload);
|
|
205
|
+
port.postMessage({ ok: true, value });
|
|
206
|
+
} catch (error) {
|
|
207
|
+
port.postMessage({ ok: false, error: serializeError(error) });
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function defaultPoolSize() {
|
|
213
|
+
const availableParallelism = os.availableParallelism?.() ?? os.cpus().length;
|
|
214
|
+
return Math.max(1, availableParallelism - 1);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function isWorkerResult(message) {
|
|
218
|
+
return Boolean(
|
|
219
|
+
message
|
|
220
|
+
&& typeof message === 'object'
|
|
221
|
+
&& Object.hasOwn(message, 'ok')
|
|
222
|
+
&& typeof message.ok === 'boolean',
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function serializeError(error) {
|
|
227
|
+
return {
|
|
228
|
+
message: error instanceof Error ? error.message : String(error),
|
|
229
|
+
name: error instanceof Error ? error.name : 'Error',
|
|
230
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function createWorkerError(error) {
|
|
235
|
+
const workerError = new Error(error?.message ?? 'Worker task failed.');
|
|
236
|
+
workerError.name = error?.name ?? 'WorkerTaskError';
|
|
237
|
+
|
|
238
|
+
if (error?.stack) {
|
|
239
|
+
workerError.stack = error.stack;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return workerError;
|
|
243
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "node-worker-pool-lite",
|
|
3
|
+
"author": "Arman Mikoyan <arman@mikoyan1@gmail.com>",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "A lightweight callback and promise worker_threads pool for Node.js.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./lib/index.js",
|
|
8
|
+
"types": "./lib/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./lib/index.d.ts",
|
|
12
|
+
"import": "./lib/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./promise": {
|
|
15
|
+
"types": "./lib/promise.d.ts",
|
|
16
|
+
"import": "./lib/promise.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"lib",
|
|
21
|
+
"examples",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "node --test test/*.test.js"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"worker_threads",
|
|
30
|
+
"worker-pool",
|
|
31
|
+
"thread-pool",
|
|
32
|
+
"concurrency",
|
|
33
|
+
"pool",
|
|
34
|
+
"parallelism",
|
|
35
|
+
"cpu-intensive"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18"
|
|
39
|
+
},
|
|
40
|
+
"license": "MIT"
|
|
41
|
+
}
|