@travetto/worker 8.0.0-alpha.8 → 8.0.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/README.md +2 -2
- package/__index__.ts +2 -1
- package/package.json +12 -12
- package/src/ipc.ts +4 -5
- package/src/pool.ts +85 -91
- package/src/types.ts +62 -0
package/README.md
CHANGED
|
@@ -13,10 +13,10 @@ npm install @travetto/worker
|
|
|
13
13
|
yarn add @travetto/worker
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
This module provides the necessary primitives for handling dependent workers.
|
|
16
|
+
This module provides the necessary primitives for handling dependent workers. A worker can be an individual actor or could be a pool of workers. Node provides ipc (inter-process communication) functionality out of the box. This module builds upon that by providing enhanced event management, richer process management, as well as constructs for orchestrating a conversation between two processes.
|
|
17
17
|
|
|
18
18
|
## Execution Pools
|
|
19
|
-
With respect to managing multiple executions, [WorkPool](https://github.com/travetto/travetto/tree/main/module/worker/src/pool.ts#
|
|
19
|
+
With respect to managing multiple executions, [WorkPool](https://github.com/travetto/travetto/tree/main/module/worker/src/pool.ts#L21) is provided to allow for concurrent operation, and processing of jobs concurrently. To manage the flow of jobs, [AsyncQueue](https://github.com/travetto/travetto/tree/main/module/runtime/src/queue.ts#L4) is used to support a wide range of use cases. [AsyncQueue](https://github.com/travetto/travetto/tree/main/module/runtime/src/queue.ts#L4) allows for manual control of iteration, which is useful for event driven work loads.
|
|
20
20
|
|
|
21
21
|
## IPC Support
|
|
22
22
|
To handle communication between processes, [IpcChannel](https://github.com/travetto/travetto/tree/main/module/worker/src/ipc.ts#L9) is provided. This class abstracts the underlying IPC mechanism and provides a simple interface for sending and receiving messages. It also includes event management capabilities, allowing for easy handling of different message types. By default the class assumes it is running in a child process, but it can also be used in a parent process (by passing in the child process) to communicate with child processes.
|
package/__index__.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@travetto/worker",
|
|
3
|
-
"version": "8.0.0
|
|
4
|
-
"type": "module",
|
|
3
|
+
"version": "8.0.0",
|
|
5
4
|
"description": "Process management utilities, with a focus on inter-process communication",
|
|
6
5
|
"keywords": [
|
|
7
|
-
"exec",
|
|
8
6
|
"child-process",
|
|
7
|
+
"exec",
|
|
9
8
|
"ipc",
|
|
10
9
|
"travetto",
|
|
11
10
|
"typescript"
|
|
@@ -13,26 +12,27 @@
|
|
|
13
12
|
"homepage": "https://travetto.io",
|
|
14
13
|
"license": "MIT",
|
|
15
14
|
"author": {
|
|
16
|
-
"
|
|
17
|
-
"
|
|
15
|
+
"name": "Travetto Framework",
|
|
16
|
+
"email": "travetto.framework@gmail.com"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"url": "git+https://github.com/travetto/travetto.git",
|
|
20
|
+
"directory": "module/worker"
|
|
18
21
|
},
|
|
19
22
|
"files": [
|
|
20
23
|
"__index__.ts",
|
|
21
24
|
"src"
|
|
22
25
|
],
|
|
26
|
+
"type": "module",
|
|
23
27
|
"main": "__index__.ts",
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"directory": "module/worker"
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
27
30
|
},
|
|
28
31
|
"dependencies": {
|
|
29
|
-
"@travetto/runtime": "^8.0.0
|
|
32
|
+
"@travetto/runtime": "^8.0.0",
|
|
30
33
|
"generic-pool": "^3.9.0"
|
|
31
34
|
},
|
|
32
35
|
"travetto": {
|
|
33
36
|
"displayName": "Worker"
|
|
34
|
-
},
|
|
35
|
-
"publishConfig": {
|
|
36
|
-
"access": "public"
|
|
37
37
|
}
|
|
38
38
|
}
|
package/src/ipc.ts
CHANGED
|
@@ -7,7 +7,6 @@ import { ShutdownManager, Util } from '@travetto/runtime';
|
|
|
7
7
|
* Channel that represents ipc communication
|
|
8
8
|
*/
|
|
9
9
|
export class IpcChannel<V = unknown> {
|
|
10
|
-
|
|
11
10
|
#emitter = new EventEmitter();
|
|
12
11
|
subProcess: NodeJS.Process | ChildProcess;
|
|
13
12
|
parentId: number;
|
|
@@ -37,7 +36,7 @@ export class IpcChannel<V = unknown> {
|
|
|
37
36
|
* Determines if channel is active
|
|
38
37
|
*/
|
|
39
38
|
get active(): boolean {
|
|
40
|
-
return
|
|
39
|
+
return this.subProcess instanceof ChildProcess ? !this.subProcess.killed : !!this.subProcess.connected;
|
|
41
40
|
}
|
|
42
41
|
|
|
43
42
|
/**
|
|
@@ -48,7 +47,7 @@ export class IpcChannel<V = unknown> {
|
|
|
48
47
|
if (!this.active) {
|
|
49
48
|
throw new Error('Cannot send message to inactive process');
|
|
50
49
|
} else if (this.subProcess.send && this.subProcess.connected) {
|
|
51
|
-
this.subProcess.send({ ...(data ?? {}), type: eventType }, undefined, undefined,
|
|
50
|
+
this.subProcess.send({ ...(data ?? {}), type: eventType }, undefined, undefined, error => error && console.error(error));
|
|
52
51
|
} else {
|
|
53
52
|
throw new Error('this.subProcess.send was not defined');
|
|
54
53
|
}
|
|
@@ -88,7 +87,7 @@ export class IpcChannel<V = unknown> {
|
|
|
88
87
|
this.subProcess.kill();
|
|
89
88
|
await Promise.race([complete, Util.nonBlockingTimeout(1000)]);
|
|
90
89
|
}
|
|
91
|
-
} catch {
|
|
90
|
+
} catch {}
|
|
92
91
|
}
|
|
93
92
|
this.release();
|
|
94
93
|
}
|
|
@@ -101,4 +100,4 @@ export class IpcChannel<V = unknown> {
|
|
|
101
100
|
this.subProcess.removeAllListeners();
|
|
102
101
|
this.#emitter.removeAllListeners();
|
|
103
102
|
}
|
|
104
|
-
}
|
|
103
|
+
}
|
package/src/pool.ts
CHANGED
|
@@ -1,76 +1,70 @@
|
|
|
1
1
|
import os from 'node:os';
|
|
2
|
-
import { type Options, type Pool, createPool } from 'generic-pool';
|
|
3
2
|
|
|
4
|
-
import {
|
|
3
|
+
import { createPool, type Pool } from 'generic-pool';
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
type WorkerExecutor<I, O> = (input: I, idx: number) => Promise<O>;
|
|
5
|
+
import { AsyncQueue, Env, Util } from '@travetto/runtime';
|
|
8
6
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
type WorkerFactoryInput<I, O = unknown> = Partial<Worker<I, O>> & { execute: WorkerExecutor<I, O> };
|
|
22
|
-
type WorkerInput<I, O> = (() => WorkerFactoryInput<I, O>) | WorkerExecutor<I, O>;
|
|
23
|
-
type WorkPoolConfig<I, O> = Options & {
|
|
24
|
-
onComplete?: (output: O, input: I, finishIdx: number) => void;
|
|
25
|
-
onError?(event: Error, input: I, finishIdx: number): (unknown | Promise<unknown>);
|
|
26
|
-
shutdown?: AbortSignal;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
const isWorkerFactory = <I, O>(value: WorkerInput<I, O>): value is (() => WorkerFactoryInput<I, O>) => value.length === 0;
|
|
7
|
+
import {
|
|
8
|
+
type IterableSource,
|
|
9
|
+
isWorkerFactory,
|
|
10
|
+
type Worker,
|
|
11
|
+
type WorkerInput,
|
|
12
|
+
type WorkPoolCompleteEvent,
|
|
13
|
+
type WorkPoolConfig,
|
|
14
|
+
type WorkPoolProgress,
|
|
15
|
+
WorkPoolResultError
|
|
16
|
+
} from './types.ts';
|
|
30
17
|
|
|
31
18
|
/**
|
|
32
19
|
* Work pool support
|
|
33
20
|
*/
|
|
34
21
|
export class WorkPool {
|
|
35
|
-
|
|
36
22
|
static MAX_SIZE = os.availableParallelism();
|
|
37
|
-
static DEFAULT_SIZE = Math.max(Math.trunc(WorkPool.MAX_SIZE * .75), 4);
|
|
23
|
+
static DEFAULT_SIZE = Math.max(Math.trunc(WorkPool.MAX_SIZE * 0.75), 4);
|
|
24
|
+
|
|
25
|
+
static #shouldTrace(): boolean {
|
|
26
|
+
return (Env.DEBUG.value ?? '').includes('@travetto/worker');
|
|
27
|
+
}
|
|
38
28
|
|
|
39
29
|
/** Build worker pool */
|
|
40
30
|
static #buildPool<I, O>(input: WorkerInput<I, O>, options?: WorkPoolConfig<I, O>): Pool<Worker<I, O>> {
|
|
41
31
|
let pendingAcquires = 0;
|
|
42
32
|
|
|
43
|
-
const trace =
|
|
33
|
+
const trace = this.#shouldTrace();
|
|
44
34
|
|
|
45
35
|
// Create the pool
|
|
46
|
-
const pool = createPool(
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
36
|
+
const pool = createPool(
|
|
37
|
+
{
|
|
38
|
+
async create() {
|
|
39
|
+
try {
|
|
40
|
+
pendingAcquires += 1;
|
|
41
|
+
const factoryInput = isWorkerFactory(input) ? await input() : { execute: input };
|
|
42
|
+
const worker: Worker<I, O> = {
|
|
43
|
+
id: Util.uuid(),
|
|
44
|
+
active: true,
|
|
45
|
+
...factoryInput
|
|
46
|
+
};
|
|
47
|
+
await worker.init?.();
|
|
48
|
+
return worker;
|
|
49
|
+
} finally {
|
|
50
|
+
pendingAcquires -= 1;
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
async destroy(worker) {
|
|
54
|
+
if (trace) {
|
|
55
|
+
console.debug('Destroying', { pid: process.pid, worker: worker.id });
|
|
56
|
+
}
|
|
57
|
+
return worker.destroy?.();
|
|
58
|
+
},
|
|
59
|
+
validate: async (worker: Worker<I, O>) => worker.active
|
|
66
60
|
},
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
61
|
+
{
|
|
62
|
+
evictionRunIntervalMillis: 5000,
|
|
63
|
+
...(options ?? {}),
|
|
64
|
+
max: options?.max ?? WorkPool.DEFAULT_SIZE,
|
|
65
|
+
min: options?.min ?? 1
|
|
66
|
+
}
|
|
67
|
+
);
|
|
74
68
|
|
|
75
69
|
// Listen for shutdown
|
|
76
70
|
options?.shutdown?.addEventListener('abort', async () => {
|
|
@@ -88,27 +82,42 @@ export class WorkPool {
|
|
|
88
82
|
* Process a given input source and worker, and fire on completion
|
|
89
83
|
*/
|
|
90
84
|
static async run<I, O>(workerFactory: WorkerInput<I, O>, source: IterableSource<I>, options: WorkPoolConfig<I, O> = {}): Promise<void> {
|
|
91
|
-
|
|
92
|
-
const trace = /@travetto\/worker/.test(Env.DEBUG.value ?? '');
|
|
85
|
+
const trace = this.#shouldTrace();
|
|
93
86
|
const pending = new Set<Promise<unknown>>();
|
|
94
87
|
const errors: Error[] = [];
|
|
95
88
|
let inputIdx = 0;
|
|
96
|
-
let finishIdx = 0;
|
|
97
89
|
|
|
98
90
|
const pool = this.#buildPool(workerFactory, options);
|
|
99
91
|
|
|
92
|
+
const progress: WorkPoolProgress = {
|
|
93
|
+
completed: 0,
|
|
94
|
+
total: options.total ?? 0,
|
|
95
|
+
failed: 0
|
|
96
|
+
};
|
|
97
|
+
|
|
100
98
|
for await (const nextInput of source) {
|
|
101
99
|
const worker = await pool.acquire()!;
|
|
102
100
|
|
|
103
101
|
if (trace) {
|
|
104
102
|
console.debug('Acquired', { pid: process.pid, worker: worker.id });
|
|
105
103
|
}
|
|
104
|
+
if (!options.total) {
|
|
105
|
+
progress.total = inputIdx + 1;
|
|
106
|
+
}
|
|
106
107
|
|
|
107
|
-
const completion = worker
|
|
108
|
-
.
|
|
108
|
+
const completion = worker
|
|
109
|
+
.execute(nextInput, (inputIdx += 1))
|
|
110
|
+
.then(output => {
|
|
111
|
+
const success = options.isSuccess?.(output) ?? true;
|
|
112
|
+
progress.failed += +!success;
|
|
113
|
+
progress.completed += 1;
|
|
114
|
+
return options.onComplete?.({ output, input: nextInput, success, progress });
|
|
115
|
+
})
|
|
109
116
|
.catch(error => {
|
|
110
117
|
errors.push(error);
|
|
111
|
-
|
|
118
|
+
progress.failed += 1;
|
|
119
|
+
progress.completed += 1;
|
|
120
|
+
options?.onError?.({ error, input: nextInput, progress });
|
|
112
121
|
}) // Catch error
|
|
113
122
|
.finally(async () => {
|
|
114
123
|
if (trace) {
|
|
@@ -118,12 +127,12 @@ export class WorkPool {
|
|
|
118
127
|
if (worker.active) {
|
|
119
128
|
try {
|
|
120
129
|
await worker.release?.();
|
|
121
|
-
} catch {
|
|
130
|
+
} catch {}
|
|
122
131
|
await pool.release(worker);
|
|
123
132
|
} else {
|
|
124
133
|
await pool.destroy(worker);
|
|
125
134
|
}
|
|
126
|
-
} catch {
|
|
135
|
+
} catch {}
|
|
127
136
|
});
|
|
128
137
|
|
|
129
138
|
completion.finally(() => pending.delete(completion));
|
|
@@ -133,43 +142,28 @@ export class WorkPool {
|
|
|
133
142
|
await Promise.all(Array.from(pending));
|
|
134
143
|
|
|
135
144
|
if (errors.length) {
|
|
136
|
-
throw errors
|
|
145
|
+
throw new WorkPoolResultError(errors);
|
|
137
146
|
}
|
|
138
147
|
}
|
|
139
148
|
|
|
140
|
-
/**
|
|
141
|
-
* Process a given input source as an async iterable
|
|
142
|
-
*/
|
|
143
|
-
static runStream<I, O>(worker: WorkerInput<I, O>, input: IterableSource<I>, options?: WorkPoolConfig<I, O>): AsyncIterable<O> {
|
|
144
|
-
const queue = new AsyncQueue<O>();
|
|
145
|
-
const result = this.run(worker, input, {
|
|
146
|
-
...options,
|
|
147
|
-
onComplete: (event, value, finishIdx) => {
|
|
148
|
-
queue.add(event);
|
|
149
|
-
options?.onComplete?.(event, value, finishIdx);
|
|
150
|
-
}
|
|
151
|
-
});
|
|
152
|
-
result.finally(() => queue.close());
|
|
153
|
-
return queue;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
149
|
/**
|
|
157
150
|
* Process a given input source as an async iterable with progress information
|
|
158
151
|
*/
|
|
159
|
-
static
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
const queue = new AsyncQueue<
|
|
165
|
-
const result = this.run(worker,
|
|
152
|
+
static runStream<I, O>(
|
|
153
|
+
worker: WorkerInput<I, O>,
|
|
154
|
+
source: IterableSource<I>,
|
|
155
|
+
options?: WorkPoolConfig<I, O>
|
|
156
|
+
): AsyncIterable<WorkPoolCompleteEvent<I, O>> {
|
|
157
|
+
const queue = new AsyncQueue<WorkPoolCompleteEvent<I, O>>();
|
|
158
|
+
const result = this.run(worker, source, {
|
|
166
159
|
...options,
|
|
167
|
-
onComplete:
|
|
168
|
-
|
|
169
|
-
|
|
160
|
+
onComplete: async event => {
|
|
161
|
+
await options?.onComplete?.(event);
|
|
162
|
+
queue.add(event);
|
|
163
|
+
return;
|
|
170
164
|
}
|
|
171
165
|
});
|
|
172
166
|
result.finally(() => queue.close());
|
|
173
167
|
return queue;
|
|
174
168
|
}
|
|
175
|
-
}
|
|
169
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Options } from 'generic-pool';
|
|
2
|
+
|
|
3
|
+
import { RuntimeError } from '@travetto/runtime';
|
|
4
|
+
|
|
5
|
+
export type IterableSource<I> = Iterable<I> | AsyncIterable<I>;
|
|
6
|
+
export type WorkerExecutor<I, O> = (input: I, idx: number) => Promise<O>;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* WorkPool results error.
|
|
10
|
+
*
|
|
11
|
+
* Hold all the errors for a given work pool execution
|
|
12
|
+
*/
|
|
13
|
+
export class WorkPoolResultError extends RuntimeError<{ errors: Error[] }> {
|
|
14
|
+
constructor(errors: Error[]) {
|
|
15
|
+
super('WorkPool errors have occurred', { category: 'data', details: { errors } });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Worker definition
|
|
21
|
+
*/
|
|
22
|
+
export interface Worker<I, O = unknown> {
|
|
23
|
+
active: boolean;
|
|
24
|
+
id: unknown;
|
|
25
|
+
init?(): Promise<unknown>;
|
|
26
|
+
execute: WorkerExecutor<I, O>;
|
|
27
|
+
destroy?(): Promise<void>;
|
|
28
|
+
release?(): unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type WorkPoolProgress = {
|
|
32
|
+
total: number;
|
|
33
|
+
completed: number;
|
|
34
|
+
failed: number;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type WorkPoolCompleteEvent<I, O> = {
|
|
38
|
+
output: O;
|
|
39
|
+
input: I;
|
|
40
|
+
success: boolean;
|
|
41
|
+
progress: WorkPoolProgress;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export type WorkPoolErrorEvent<I> = {
|
|
45
|
+
error: Error;
|
|
46
|
+
input: I;
|
|
47
|
+
progress: WorkPoolProgress;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export type WorkerFactoryInput<I, O = unknown> = Partial<Worker<I, O>> & { execute: WorkerExecutor<I, O> };
|
|
51
|
+
export type WorkerInput<I, O> = (() => WorkerFactoryInput<I, O> | Promise<WorkerFactoryInput<I, O>>) | WorkerExecutor<I, O>;
|
|
52
|
+
export type WorkPoolConfig<I, O> = Options & {
|
|
53
|
+
isSuccess?: (output: O) => boolean;
|
|
54
|
+
onComplete?: (event: WorkPoolCompleteEvent<I, O>) => void | Promise<void>;
|
|
55
|
+
onError?<R = unknown>(event: WorkPoolErrorEvent<I>): R | Promise<R>;
|
|
56
|
+
shutdown?: AbortSignal;
|
|
57
|
+
total?: number;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export const isWorkerFactory = <I, O>(
|
|
61
|
+
value: WorkerInput<I, O>
|
|
62
|
+
): value is () => WorkerFactoryInput<I, O> | Promise<WorkerFactoryInput<I, O>> => value.length === 0;
|