- protected internalExecute (worker: Worker, id: number): Promise<Response> {
- return new Promise((resolve, reject) => {
- const listener: (message: MessageValue<Response>) => void = message => {
- if (message.id === id) {
- this.unregisterWorkerMessageListener(worker, listener)
- this.addWorker(worker)
- if (message.error) reject(message.error)
- else resolve(message.data as Response)
+ protected internalExecute (
+ worker: Worker,
+ messageId: number
+ ): Promise<Response> {
+ this.beforePromiseWorkerResponseHook(worker)
+ return new Promise<Response>((resolve, reject) => {
+ this.promiseMap.set(messageId, { resolve, reject, worker })
+ })
+ }
+
+ /**
+ * Returns a newly created worker.
+ */
+ protected abstract createWorker (): Worker
+
+ /**
+ * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
+ *
+ * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
+ *
+ * @param worker The newly created worker.
+ */
+ protected abstract afterWorkerSetup (worker: Worker): void
+
+ /**
+ * Creates a new worker for this pool and sets it up completely.
+ *
+ * @returns New, completely set up worker.
+ */
+ protected createAndSetupWorker (): Worker {
+ const worker = this.createWorker()
+
+ worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
+ worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
+ worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
+ worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
+ worker.once('exit', () => this.removeWorker(worker))
+
+ this.workers.push(worker)
+
+ // Init worker tasks usage map
+ this.workersTasksUsage.set(worker, {
+ run: 0,
+ running: 0,
+ runTime: 0,
+ avgRunTime: 0
+ })
+
+ this.afterWorkerSetup(worker)
+
+ return worker
+ }
+
+ /**
+ * This function is the listener registered for each worker.
+ *
+ * @returns The listener function to execute when a message is received from a worker.
+ */
+ protected workerListener (): (message: MessageValue<Response>) => void {
+ return message => {
+ if (message.id !== undefined) {
+ const promise = this.promiseMap.get(message.id)
+ if (promise !== undefined) {
+ this.afterPromiseWorkerResponseHook(message, promise)
+ if (message.error) promise.reject(message.error)
+ else promise.resolve(message.data as Response)
+ this.promiseMap.delete(message.id)