X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fabstract-worker.ts;h=d41115bc390b26f63eeaa9ae4500d678cb1bd7b4;hb=934f09c6fe1a3e6e36ba76f9a8e9320311a7636f;hp=fd163547a78eb08c7ca0c0a93519374530ed5c8f;hpb=729c563db85562dd7d0f7733b1a3e2d98467134b;p=poolifier.git diff --git a/src/worker/abstract-worker.ts b/src/worker/abstract-worker.ts index fd163547..d41115bc 100644 --- a/src/worker/abstract-worker.ts +++ b/src/worker/abstract-worker.ts @@ -1,16 +1,22 @@ 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 type { KillBehavior, WorkerOptions } from './worker-options' +import { KillBehaviors } from './worker-options' + +const DEFAULT_MAX_INACTIVE_TIME = 1000 * 60 +const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT /** * Base class containing some shared logic for all poolifier workers. * * @template MainWorker Type of main worker. - * @template Data Type of data this worker receives from pool's execution. - * @template Response Type of response the worker sends back to the main worker. + * @template Data Type of data this worker receives from pool's execution. This can only be serializable data. + * @template Response Type of response the worker sends back to the main worker. This can only be serializable data. */ 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: KillBehavior /** * Whether the worker is working asynchronously or not. */ @@ -37,21 +47,27 @@ 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: DEFAULT_KILL_BEHAVIOR, + maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME + } ) { super(type) - - this.maxInactiveTime = this.opts.maxInactiveTime ?? 1000 * 60 + this.killBehavior = this.opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR + this.maxInactiveTime = + this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME this.async = !!this.opts.async this.lastTask = Date.now() - if (!fn) throw new Error('fn parameter is mandatory') - // keep the worker active + this.checkFunctionInput(fn) + // Keep the worker active if (!isMain) { this.interval = setInterval( this.checkAlive.bind(this), @@ -59,12 +75,47 @@ 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() + } + }) + } + + /** + * Check if the `fn` parameter is passed to the constructor. + * + * @param fn The function that should be defined. + */ + private checkFunctionInput (fn: (data: Data) => Response) { + if (!fn) throw new Error('fn parameter is mandatory') } /** * 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 +129,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 +137,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