-import cluster, { type ClusterSettings, type Worker } from 'node:cluster'
+import cluster, { type Worker } from 'node:cluster'
import type { MessageValue } from '../../utility-types'
import { AbstractPool } from '../abstract-pool'
import { type PoolOptions, type PoolType, PoolTypes } from '../pool'
import { type WorkerType, WorkerTypes } from '../worker'
-/**
- * Options for a poolifier cluster pool.
- */
-export interface ClusterPoolOptions extends PoolOptions<Worker> {
- /**
- * Key/value pairs to add to worker process environment.
- *
- * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
- */
- env?: Record<string, unknown>
- /**
- * Cluster settings.
- *
- * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
- */
- settings?: ClusterSettings
-}
-
/**
* A cluster pool with a fixed number of workers.
*
public constructor (
numberOfWorkers: number,
filePath: string,
- protected readonly opts: ClusterPoolOptions = {}
+ protected readonly opts: PoolOptions<Worker> = {}
) {
super(numberOfWorkers, filePath, opts)
}
return cluster.isPrimary
}
- /** @inheritDoc */
- protected async destroyWorkerNode (workerNodeKey: number): Promise<void> {
- this.flushTasksQueue(workerNodeKey)
- // FIXME: wait for tasks to be finished
- const workerNode = this.workerNodes[workerNodeKey]
- const worker = workerNode.worker
- const waitWorkerExit = new Promise<void>(resolve => {
- worker.on('exit', () => {
- resolve()
- })
- })
- worker.on('disconnect', () => {
- worker.kill()
- })
- await this.sendKillMessageToWorker(workerNodeKey)
- worker.disconnect()
- await waitWorkerExit
- }
-
/** @inheritDoc */
protected sendToWorker (
workerNodeKey: number,
): void {
this.workerNodes[workerNodeKey].worker.send({
...message,
- workerId: this.workerNodes[workerNodeKey].info.id as number
+ workerId: this.getWorkerInfo(workerNodeKey).id as number
})
}
}
/** @inheritDoc */
- protected createWorker (): Worker {
- return cluster.fork(this.opts.env)
+ protected registerOnceWorkerMessageListener<Message extends Data | Response>(
+ workerNodeKey: number,
+ listener: (message: MessageValue<Message>) => void
+ ): void {
+ this.workerNodes[workerNodeKey].worker.once('message', listener)
+ }
+
+ /** @inheritDoc */
+ protected deregisterWorkerMessageListener<Message extends Data | Response>(
+ workerNodeKey: number,
+ listener: (message: MessageValue<Message>) => void
+ ): void {
+ this.workerNodes[workerNodeKey].worker.off('message', listener)
}
/** @inheritDoc */