@travetto/worker 8.0.0-alpha.19 → 8.0.0-alpha.20

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 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. 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.
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#L14) 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.
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
@@ -1,3 +1,3 @@
1
1
  export * from './src/ipc.ts';
2
2
  export * from './src/pool.ts';
3
- export * from './src/types.ts';
3
+ export * from './src/types.ts';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@travetto/worker",
3
- "version": "8.0.0-alpha.19",
3
+ "version": "8.0.0-alpha.20",
4
4
  "type": "module",
5
5
  "description": "Process management utilities, with a focus on inter-process communication",
6
6
  "keywords": [
@@ -26,7 +26,7 @@
26
26
  "directory": "module/worker"
27
27
  },
28
28
  "dependencies": {
29
- "@travetto/runtime": "^8.0.0-alpha.19",
29
+ "@travetto/runtime": "^8.0.0-alpha.20",
30
30
  "generic-pool": "^3.9.0"
31
31
  },
32
32
  "travetto": {
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 (this.subProcess instanceof ChildProcess) ? !this.subProcess.killed : !!this.subProcess.connected;
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, (error) => error && console.error(error));
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,20 +1,26 @@
1
1
  import os from 'node:os';
2
- import { type Pool, createPool } from 'generic-pool';
3
2
 
4
- import { Env, Util, AsyncQueue } from '@travetto/runtime';
3
+ import { createPool, type Pool } from 'generic-pool';
4
+
5
+ import { AsyncQueue, Env, Util } from '@travetto/runtime';
5
6
 
6
7
  import {
7
- isWorkerFactory, WorkPoolResultError, type IterableSource, type Worker, type WorkerInput,
8
- type WorkPoolCompleteEvent, type WorkPoolConfig, type WorkPoolProgress
8
+ type IterableSource,
9
+ isWorkerFactory,
10
+ type Worker,
11
+ type WorkerInput,
12
+ type WorkPoolCompleteEvent,
13
+ type WorkPoolConfig,
14
+ type WorkPoolProgress,
15
+ WorkPoolResultError
9
16
  } from './types.ts';
10
17
 
11
18
  /**
12
19
  * Work pool support
13
20
  */
14
21
  export class WorkPool {
15
-
16
22
  static MAX_SIZE = os.availableParallelism();
17
- 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);
18
24
 
19
25
  static #shouldTrace(): boolean {
20
26
  return (Env.DEBUG.value ?? '').includes('@travetto/worker');
@@ -27,35 +33,38 @@ export class WorkPool {
27
33
  const trace = this.#shouldTrace();
28
34
 
29
35
  // Create the pool
30
- const pool = createPool({
31
- async create() {
32
- try {
33
- pendingAcquires += 1;
34
- const factoryInput = isWorkerFactory(input) ? await input() : { execute: input };
35
- const worker: Worker<I, O> = {
36
- id: Util.uuid(),
37
- active: true,
38
- ...factoryInput,
39
- };
40
- await worker.init?.();
41
- return worker;
42
- } finally {
43
- pendingAcquires -= 1;
44
- }
45
- },
46
- async destroy(worker) {
47
- if (trace) {
48
- console.debug('Destroying', { pid: process.pid, worker: worker.id });
49
- }
50
- return worker.destroy?.();
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
51
60
  },
52
- validate: async (worker: Worker<I, O>) => worker.active
53
- }, {
54
- evictionRunIntervalMillis: 5000,
55
- ...(options ?? {}),
56
- max: options?.max ?? WorkPool.DEFAULT_SIZE,
57
- min: options?.min ?? 1,
58
- });
61
+ {
62
+ evictionRunIntervalMillis: 5000,
63
+ ...(options ?? {}),
64
+ max: options?.max ?? WorkPool.DEFAULT_SIZE,
65
+ min: options?.min ?? 1
66
+ }
67
+ );
59
68
 
60
69
  // Listen for shutdown
61
70
  options?.shutdown?.addEventListener('abort', async () => {
@@ -73,7 +82,6 @@ export class WorkPool {
73
82
  * Process a given input source and worker, and fire on completion
74
83
  */
75
84
  static async run<I, O>(workerFactory: WorkerInput<I, O>, source: IterableSource<I>, options: WorkPoolConfig<I, O> = {}): Promise<void> {
76
-
77
85
  const trace = this.#shouldTrace();
78
86
  const pending = new Set<Promise<unknown>>();
79
87
  const errors: Error[] = [];
@@ -84,7 +92,7 @@ export class WorkPool {
84
92
  const progress: WorkPoolProgress = {
85
93
  completed: 0,
86
94
  total: options.total ?? 0,
87
- failed: 0,
95
+ failed: 0
88
96
  };
89
97
 
90
98
  for await (const nextInput of source) {
@@ -97,7 +105,8 @@ export class WorkPool {
97
105
  progress.total = inputIdx + 1;
98
106
  }
99
107
 
100
- const completion = worker.execute(nextInput, inputIdx += 1)
108
+ const completion = worker
109
+ .execute(nextInput, (inputIdx += 1))
101
110
  .then(output => {
102
111
  const success = options.isSuccess?.(output) ?? true;
103
112
  progress.failed += +!success;
@@ -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));
@@ -140,11 +149,15 @@ export class WorkPool {
140
149
  /**
141
150
  * Process a given input source as an async iterable with progress information
142
151
  */
143
- static runStream<I, O>(worker: WorkerInput<I, O>, source: IterableSource<I>, options?: WorkPoolConfig<I, O>): AsyncIterable<WorkPoolCompleteEvent<I, O>> {
152
+ static runStream<I, O>(
153
+ worker: WorkerInput<I, O>,
154
+ source: IterableSource<I>,
155
+ options?: WorkPoolConfig<I, O>
156
+ ): AsyncIterable<WorkPoolCompleteEvent<I, O>> {
144
157
  const queue = new AsyncQueue<WorkPoolCompleteEvent<I, O>>();
145
158
  const result = this.run(worker, source, {
146
159
  ...options,
147
- onComplete: async (event) => {
160
+ onComplete: async event => {
148
161
  await options?.onComplete?.(event);
149
162
  queue.add(event);
150
163
  return;
@@ -153,4 +166,4 @@ export class WorkPool {
153
166
  result.finally(() => queue.close());
154
167
  return queue;
155
168
  }
156
- }
169
+ }
package/src/types.ts CHANGED
@@ -48,13 +48,15 @@ export type WorkPoolErrorEvent<I> = {
48
48
  };
49
49
 
50
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>;
51
+ export type WorkerInput<I, O> = (() => WorkerFactoryInput<I, O> | Promise<WorkerFactoryInput<I, O>>) | WorkerExecutor<I, O>;
52
52
  export type WorkPoolConfig<I, O> = Options & {
53
53
  isSuccess?: (output: O) => boolean;
54
54
  onComplete?: (event: WorkPoolCompleteEvent<I, O>) => void | Promise<void>;
55
- onError?<R = unknown>(event: WorkPoolErrorEvent<I>): (R | Promise<R>);
55
+ onError?<R = unknown>(event: WorkPoolErrorEvent<I>): R | Promise<R>;
56
56
  shutdown?: AbortSignal;
57
57
  total?: number;
58
58
  };
59
59
 
60
- export const isWorkerFactory = <I, O>(value: WorkerInput<I, O>): value is (() => (WorkerFactoryInput<I, O> | Promise<WorkerFactoryInput<I, O>>)) => value.length === 0;
60
+ export const isWorkerFactory = <I, O>(
61
+ value: WorkerInput<I, O>
62
+ ): value is () => WorkerFactoryInput<I, O> | Promise<WorkerFactoryInput<I, O>> => value.length === 0;