X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fabstract-worker.ts;h=c50cfbb081599ed955561edea56a634c93d885ef;hb=4c35177b63cac8a87aa6de389e1232e94c59b8c9;hp=fd163547a78eb08c7ca0c0a93519374530ed5c8f;hpb=729c563db85562dd7d0f7733b1a3e2d98467134b;p=poolifier.git diff --git a/src/worker/abstract-worker.ts b/src/worker/abstract-worker.ts index fd163547..c50cfbb0 100644 --- a/src/worker/abstract-worker.ts +++ b/src/worker/abstract-worker.ts @@ -1,6 +1,12 @@ import { AsyncResource } from 'async_hooks' +import type { Worker } from 'cluster' +import type { MessagePort } from 'worker_threads' import type { MessageValue } from '../utility-types' import type { WorkerOptions } from './worker-options' +import { killBehaviorEnumeration } from './worker-options' + +const defaultMaxInactiveTime = 1000 * 60 +const defaultKillBehavior = killBehaviorEnumeration.SOFT /** * Base class containing some shared logic for all poolifier workers. @@ -10,7 +16,7 @@ import type { WorkerOptions } from './worker-options' * @template Response Type of response the worker sends back to the main worker. */ export abstract class AbstractWorker< - MainWorker, + MainWorker extends Worker | MessagePort, Data = unknown, Response = unknown > extends AsyncResource { @@ -18,6 +24,10 @@ export abstract class AbstractWorker< * The maximum time to keep this worker alive while idle. The pool automatically checks and terminates this worker when the time expires. */ protected readonly maxInactiveTime: number + /** + * The kill behavior set as option on the Worker constructor or a default value. + */ + protected readonly killBehavior: string /** * Whether the worker is working asynchronously or not. */ @@ -37,21 +47,26 @@ export abstract class AbstractWorker< * @param type The type of async event. * @param isMain Whether this is the main worker or not. * @param fn Function processed by the worker when the pool's `execution` function is invoked. + * @param mainWorker Reference to main worker. * @param opts Options for the worker. */ public constructor ( type: string, isMain: boolean, fn: (data: Data) => Response, - public readonly opts: WorkerOptions = {} + protected mainWorker?: MainWorker | null, + public readonly opts: WorkerOptions = { + killBehavior: defaultKillBehavior, + maxInactiveTime: defaultMaxInactiveTime + } ) { super(type) - - this.maxInactiveTime = this.opts.maxInactiveTime ?? 1000 * 60 + this.killBehavior = this.opts.killBehavior ?? defaultKillBehavior + this.maxInactiveTime = this.opts.maxInactiveTime ?? defaultMaxInactiveTime this.async = !!this.opts.async this.lastTask = Date.now() if (!fn) throw new Error('fn parameter is mandatory') - // keep the worker active + // Keep the worker active if (!isMain) { this.interval = setInterval( this.checkAlive.bind(this), @@ -59,12 +74,38 @@ export abstract class AbstractWorker< ) this.checkAlive.bind(this)() } + + this.mainWorker?.on('message', (value: MessageValue) => { + if (value?.data && value.id) { + // Here you will receive messages + if (this.async) { + this.runInAsyncScope(this.runAsync.bind(this), this, fn, value) + } else { + this.runInAsyncScope(this.run.bind(this), this, fn, value) + } + } else if (value.parent) { + // Save a reference of the main worker to communicate with it + // This will be received once + this.mainWorker = value.parent + } else if (value.kill) { + // Here is time to kill this worker, just clearing the interval + if (this.interval) clearInterval(this.interval) + this.emitDestroy() + } + }) } /** * Returns the main worker. + * + * @returns Reference to the main worker. */ - protected abstract getMainWorker (): MainWorker + protected getMainWorker (): MainWorker { + if (!this.mainWorker) { + throw new Error('Main worker was not set') + } + return this.mainWorker + } /** * Send a message to the main worker. @@ -78,7 +119,7 @@ export abstract class AbstractWorker< */ protected checkAlive (): void { if (Date.now() - this.lastTask > this.maxInactiveTime) { - this.sendToMainWorker({ kill: 1 }) + this.sendToMainWorker({ kill: this.killBehavior }) } } @@ -86,6 +127,7 @@ export abstract class AbstractWorker< * Handle an error and convert it to a string so it can be sent back to the main worker. * * @param e The error raised by the worker. + * @returns Message of the error. */ protected handleError (e: Error | string): string { return (e as unknown) as string