| 1 | import type { Worker } from 'node:cluster' |
| 2 | import cluster from 'node:cluster' |
| 3 | import type { |
| 4 | MessageValue, |
| 5 | TaskFunctions, |
| 6 | WorkerFunction |
| 7 | } from '../utility-types' |
| 8 | import { AbstractWorker } from './abstract-worker' |
| 9 | import type { WorkerOptions } from './worker-options' |
| 10 | |
| 11 | /** |
| 12 | * A cluster worker used by a poolifier `ClusterPool`. |
| 13 | * |
| 14 | * When this worker is inactive for more than the given `maxInactiveTime`, |
| 15 | * it will send a termination request to its main worker. |
| 16 | * |
| 17 | * If you use a `DynamicClusterPool` the extra workers that were created will be terminated, |
| 18 | * but the minimum number of workers will be guaranteed. |
| 19 | * |
| 20 | * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data. |
| 21 | * @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data. |
| 22 | * @author [Christopher Quadflieg](https://github.com/Shinigami92) |
| 23 | * @since 2.0.0 |
| 24 | */ |
| 25 | export class ClusterWorker< |
| 26 | Data = unknown, |
| 27 | Response = unknown |
| 28 | > extends AbstractWorker<Worker, Data, Response> { |
| 29 | /** |
| 30 | * Constructs a new poolifier cluster worker. |
| 31 | * |
| 32 | * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. |
| 33 | * @param opts - Options for the worker. |
| 34 | */ |
| 35 | public constructor ( |
| 36 | taskFunctions: |
| 37 | | WorkerFunction<Data, Response> |
| 38 | | TaskFunctions<Data, Response>, |
| 39 | opts: WorkerOptions = {} |
| 40 | ) { |
| 41 | super( |
| 42 | 'worker-cluster-pool:poolifier', |
| 43 | cluster.isPrimary, |
| 44 | taskFunctions, |
| 45 | cluster.worker, |
| 46 | opts |
| 47 | ) |
| 48 | } |
| 49 | |
| 50 | /** @inheritDoc */ |
| 51 | protected sendToMainWorker (message: MessageValue<Response>): void { |
| 52 | this.getMainWorker().send(message) |
| 53 | } |
| 54 | |
| 55 | /** @inheritDoc */ |
| 56 | protected handleError (e: Error | string): string { |
| 57 | return e instanceof Error ? e.message : e |
| 58 | } |
| 59 | } |