-
Notifications
You must be signed in to change notification settings - Fork 0
/
spawn-worker.ts
87 lines (77 loc) · 2.11 KB
/
spawn-worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { lazyValue, noop } from '@proc7ts/primitives';
import type { Worker } from 'node:worker_threads';
import { AbortedZExecutionError } from './aborted-execution-error.js';
import { execZ } from './exec.js';
import type { ZExecution } from './execution.js';
/**
* Spawned worker thread configuration.
*/
export interface SpawnZWorkerConfig {
/**
* Stops worker thread.
*
* @param worker - The worker to stop.
*
* @default Invokes `Worker.terminate()`
*/
stop?(worker: Worker): void;
}
/**
* Spawns worker thread.
*
* @param spawn - Starter function returning started worker instance.
* @param config - Spawned worker thread configuration.
*
* @returns New worker thread execution instance stopping the thread on abort.
*/
export function spawnZWorker(
spawn: (this: void) => Worker,
config: SpawnZWorkerConfig = {},
): ZExecution {
const { stop } = config;
const stopWorker = stop ? stop.bind(config) : (worker: Worker) => worker.terminate();
return execZ(() => {
let abort: () => void;
let start: () => void;
let dontStart: (error: unknown) => void;
const whenStarted = new Promise<void>((resolve, reject) => {
start = resolve;
dontStart = reject;
});
let whenDone = (): Promise<void> => new Promise<void>((resolve, reject) => {
const worker = spawn();
abort = (): void => {
stopWorker(worker);
};
const reportError = (error: Error): void => {
abort = noop;
dontStart(error);
reject(error);
};
worker.on('online', start);
worker.on('error', reportError);
worker.on('exit', code => {
if (code) {
reportError(new AbortedZExecutionError(code));
} else {
abort = noop;
resolve();
}
});
});
abort = (): void => {
whenDone = lazyValue(() => Promise.reject(new AbortedZExecutionError()));
};
return {
whenStarted() {
return whenStarted;
},
whenDone() {
return whenDone();
},
abort() {
abort();
},
};
});
}