X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fabstract-worker.ts;h=03d954fe62f1933594e4f556511e9762b7093fb5;hb=0e19141a4c860c96cde0eac21023cef79e6b22f5;hp=768c8d95ee3493267163b07ca7ff332f31caa152;hpb=3ec964d666b2ffa57b57a37a29542a727fc55ee6;p=poolifier.git diff --git a/src/worker/abstract-worker.ts b/src/worker/abstract-worker.ts index 768c8d95..03d954fe 100644 --- a/src/worker/abstract-worker.ts +++ b/src/worker/abstract-worker.ts @@ -1,12 +1,12 @@ import { AsyncResource } from 'async_hooks' import type { Worker } from 'cluster' import type { MessagePort } from 'worker_threads' -import type { MessageValue, KillBehavior } from '../utility-types' -import type { WorkerOptions } from './worker-options' +import type { MessageValue } from '../utility-types' +import type { KillBehavior, WorkerOptions } from './worker-options' +import { KillBehaviors } from './worker-options' -const defaultMaxInactiveTime = 1000 * 60 -// TODO fix this and avoid that SOFT/HARD words are replicated so much times into the project -const defaultKillBehavior: KillBehavior = 'SOFT' +const DEFAULT_MAX_INACTIVE_TIME = 1000 * 60 +const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT /** * Base class containing some shared logic for all poolifier workers. @@ -56,16 +56,17 @@ export abstract class AbstractWorker< fn: (data: Data) => Response, protected mainWorker?: MainWorker | null, public readonly opts: WorkerOptions = { - killBehavior: defaultKillBehavior, - maxInactiveTime: defaultMaxInactiveTime + killBehavior: DEFAULT_KILL_BEHAVIOR, + maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME } ) { super(type) - this.killBehavior = this.opts.killBehavior ?? defaultKillBehavior - this.maxInactiveTime = this.opts.maxInactiveTime ?? defaultMaxInactiveTime + 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') + this.checkFunctionInput(fn) // Keep the worker active if (!isMain) { this.interval = setInterval( @@ -95,6 +96,15 @@ export abstract class AbstractWorker< }) } + /** + * 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. *