6d7f5569f75f9027cae94136eccc9f1dcb023c6a
1 import EventEmitter from
'events'
2 import type { MessageValue
} from
'../utility-types'
3 import type { IPool
} from
'./pool'
5 export type ErrorHandler
<Worker
> = (this: Worker
, e
: Error) => void
6 export type OnlineHandler
<Worker
> = (this: Worker
) => void
7 export type ExitHandler
<Worker
> = (this: Worker
, code
: number) => void
9 export interface IWorker
{
10 on(event
: 'error', handler
: ErrorHandler
<this>): void
11 on(event
: 'online', handler
: OnlineHandler
<this>): void
12 on(event
: 'exit', handler
: ExitHandler
<this>): void
15 export interface PoolOptions
<Worker
> {
17 * A function that will listen for error event on each worker.
19 errorHandler
?: ErrorHandler
<Worker
>
21 * A function that will listen for online event on each worker.
23 onlineHandler
?: OnlineHandler
<Worker
>
25 * A function that will listen for exit event on each worker.
27 exitHandler
?: ExitHandler
<Worker
>
29 * This is just to avoid not useful warnings message, is used to set `maxListeners` on event emitters (workers are event emitters).
36 class PoolEmitter
extends EventEmitter
{}
38 export abstract class AbstractPool
<
39 Worker
extends IWorker
,
42 > implements IPool
<Data
, Response
> {
43 public readonly workers
: Worker
[] = []
44 public nextWorker
: number = 0
47 * `workerId` as key and an integer value
49 public readonly tasks
: Map
<Worker
, number> = new Map
<Worker
, number>()
51 public readonly emitter
: PoolEmitter
53 protected id
: number = 0
56 public readonly numWorkers
: number,
57 public readonly filePath
: string,
58 public readonly opts
: PoolOptions
<Worker
> = { maxTasks
: 1000 }
61 throw new Error('Cannot start a pool from a worker!')
63 // TODO christopher 2021-02-07: Improve this check e.g. with a pattern or blank check
65 throw new Error('Please specify a file with a worker implementation')
70 for (let i
= 1; i
<= this.numWorkers
; i
++) {
71 this.internalNewWorker()
74 this.emitter
= new PoolEmitter()
77 protected setupHook (): void {
81 protected abstract isMain (): boolean
83 public async destroy (): Promise
<void> {
84 for (const worker
of this.workers
) {
85 await this.destroyWorker(worker
)
89 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
91 protected abstract sendToWorker (
93 message
: MessageValue
<Data
>
96 protected addWorker (worker
: Worker
): void {
97 const previousWorkerIndex
= this.tasks
.get(worker
)
98 if (previousWorkerIndex
!== undefined) {
99 this.tasks
.set(worker
, previousWorkerIndex
+ 1)
101 throw Error('Worker could not be found in tasks map')
106 * Execute the task specified into the constructor with the data parameter.
108 * @param data The input for the task specified.
109 * @returns Promise that is resolved when the task is done.
111 public execute (data
: Data
): Promise
<Response
> {
112 // configure worker to handle message with the specified task
113 const worker
= this.chooseWorker()
114 this.addWorker(worker
)
116 const res
= this.internalExecute(worker
, id
)
117 this.sendToWorker(worker
, { data
: data
|| ({} as Data
), id
: id
})
121 protected abstract registerWorkerMessageListener (
123 listener
: (message
: MessageValue
<Response
>) => void
126 protected abstract unregisterWorkerMessageListener (
128 listener
: (message
: MessageValue
<Response
>) => void
131 protected internalExecute (worker
: Worker
, id
: number): Promise
<Response
> {
132 return new Promise((resolve
, reject
) => {
133 const listener
: (message
: MessageValue
<Response
>) => void = message
=> {
134 if (message
.id
=== id
) {
135 this.unregisterWorkerMessageListener(worker
, listener
)
136 this.addWorker(worker
)
137 if (message
.error
) reject(message
.error
)
138 else resolve(message
.data
as Response
)
141 this.registerWorkerMessageListener(worker
, listener
)
145 protected chooseWorker (): Worker
{
146 if (this.workers
.length
- 1 === this.nextWorker
) {
148 return this.workers
[this.nextWorker
]
151 return this.workers
[this.nextWorker
]
155 protected abstract newWorker (): Worker
157 protected abstract afterNewWorkerPushed (worker
: Worker
): void
159 protected internalNewWorker (): Worker
{
160 const worker
: Worker
= this.newWorker()
161 worker
.on('error', this.opts
.errorHandler
?? (() => {}))
162 worker
.on('online', this.opts
.onlineHandler
?? (() => {}))
163 // TODO handle properly when a worker exit
164 worker
.on('exit', this.opts
.exitHandler
?? (() => {}))
165 this.workers
.push(worker
)
166 this.afterNewWorkerPushed(worker
)
168 this.tasks
.set(worker
, 0)