X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fthread-worker.ts;h=7f3cd950a992269fb7917b7eda296419a501b6f8;hb=43f8444644bd23ed8b01e7bbb386a51a6144fff8;hp=2b3df58361eb28a9d0ccc2f694208bb0e4426c02;hpb=e8a4c3ea4d5123ff7c158d139ca142144ccc1117;p=poolifier.git diff --git a/src/worker/thread-worker.ts b/src/worker/thread-worker.ts index 2b3df583..7f3cd950 100644 --- a/src/worker/thread-worker.ts +++ b/src/worker/thread-worker.ts @@ -4,10 +4,10 @@ import { 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 { TaskFunctions, WorkerFunction } from './worker-functions' +import type { MessageValue } from '../utility-types.js' +import { AbstractWorker } from './abstract-worker.js' +import type { WorkerOptions } from './worker-options.js' +import type { TaskFunction, TaskFunctions } from './task-functions.js' /** * A thread worker used by a poolifier `ThreadPool`. @@ -27,6 +27,11 @@ export class ThreadWorker< Data = unknown, Response = unknown > extends AbstractWorker { + /** + * Message port used to communicate with the main worker. + */ + private port?: MessagePort + /** * Constructs a new poolifier thread worker. * @@ -34,26 +39,60 @@ export class ThreadWorker< * @param opts - Options for the worker. */ public constructor ( - taskFunctions: - | WorkerFunction - | TaskFunctions, + taskFunctions: TaskFunction | TaskFunctions, opts: WorkerOptions = {} ) { - super( - 'worker-thread-pool:poolifier', - isMainThread, - taskFunctions, - parentPort as MessagePort, - opts - ) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + super(isMainThread, parentPort!, taskFunctions, opts) + } + + /** @inheritDoc */ + protected handleReadyMessage (message: MessageValue): void { + if ( + message.workerId === this.id && + message.ready === false && + message.port != null + ) { + 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() + }) + } + } + } + + /** @inheritDoc */ + protected handleKillMessage (message: MessageValue): void { + super.handleKillMessage(message) + this.port?.unref() + this.port?.close() } + /** @inheritDoc */ protected get id (): number { return threadId } /** @inheritDoc */ - protected sendToMainWorker (message: MessageValue): void { - this.getMainWorker().postMessage(message) + protected readonly sendToMainWorker = ( + message: MessageValue + ): void => { + this.port?.postMessage({ ...message, workerId: this.id }) + } + + /** + * @inheritDoc + * @override + */ + protected handleError (error: Error | string): string { + return error as string } }