X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fthread-worker.ts;h=7115d71568a6fc0664ba6f74b17085b35bc50655;hb=b358c8aca5934f7d5dc4bd234d1909ba13850ea9;hp=4666fbc7590dda3974df88770b874703c0189e17;hpb=82ea6492d3318a170559bb57501dc16023bb18d8;p=poolifier.git diff --git a/src/worker/thread-worker.ts b/src/worker/thread-worker.ts index 4666fbc7..7115d715 100644 --- a/src/worker/thread-worker.ts +++ b/src/worker/thread-worker.ts @@ -1,13 +1,14 @@ import { - type MessagePort, isMainThread, + type MessagePort, parentPort, threadId } from 'node:worker_threads' -import type { MessageValue } from '../utility-types' -import { AbstractWorker } from './abstract-worker' -import type { WorkerOptions } from './worker-options' -import type { TaskFunction, TaskFunctions } from './task-functions' + +import type { MessageValue } from '../utility-types.js' +import { AbstractWorker } from './abstract-worker.js' +import type { TaskFunction, TaskFunctions } from './task-functions.js' +import type { WorkerOptions } from './worker-options.js' /** * A thread worker used by a poolifier `ThreadPool`. @@ -30,7 +31,8 @@ export class ThreadWorker< /** * Message port used to communicate with the main worker. */ - private port!: MessagePort + private port?: MessagePort + /** * Constructs a new poolifier thread worker. * @@ -41,26 +43,29 @@ export class ThreadWorker< taskFunctions: TaskFunction | TaskFunctions, opts: WorkerOptions = {} ) { - super( - 'worker-thread-pool:poolifier', - isMainThread, - parentPort as MessagePort, - taskFunctions, - opts - ) + super(isMainThread, parentPort, taskFunctions, opts) } /** @inheritDoc */ protected handleReadyMessage (message: MessageValue): void { if ( - !this.isMain && message.workerId === this.id && - message.ready != null && + message.ready === false && message.port != null ) { - this.port = message.port - this.port.on('message', this.messageListener.bind(this)) - this.sendToMainWorker({ ready: true, workerId: this.id }) + try { + this.port = message.port + this.port.on('message', this.messageListener.bind(this)) + this.sendToMainWorker({ + ready: true, + taskFunctionNames: this.listTaskFunctionNames() + }) + } catch { + this.sendToMainWorker({ + ready: false, + taskFunctionNames: this.listTaskFunctionNames() + }) + } } } @@ -77,12 +82,20 @@ export class ThreadWorker< } /** @inheritDoc */ - protected sendToMainWorker (message: MessageValue): void { - this.port.postMessage(message) + protected readonly sendToMainWorker = ( + message: MessageValue + ): void => { + this.port?.postMessage({ + ...message, + workerId: this.id + } satisfies MessageValue) } - /** @inheritDoc */ - protected handleError (e: Error | string): string { - return e as string + /** + * @inheritDoc + * @override + */ + protected handleError (error: Error | string): string { + return error as string } }