Only allow primitive JSON for transfer between worker and main worker (#128)
[poolifier.git] / src / pools / thread / dynamic.ts
1 import type { JSONValue, MessageValue } from '../../utility-types'
2 import type { PoolOptions } from '../abstract-pool'
3 import type { ThreadWorkerWithMessageChannel } from './fixed'
4 import { FixedThreadPool } from './fixed'
5
6 /**
7 * A thread pool with a min/max number of threads, is possible to execute tasks in sync or async mode as you prefer.
8 *
9 * This thread pool will create new workers when the other ones are busy, until the max number of threads,
10 * when the max number of threads is reached, an event will be emitted, if you want to listen this event use the emitter method.
11 *
12 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
13 * @since 0.0.1
14 */
15 export class DynamicThreadPool<
16 Data extends JSONValue = JSONValue,
17 Response extends JSONValue = JSONValue
18 > extends FixedThreadPool<Data, Response> {
19 /**
20 * @param min Min number of threads that will be always active
21 * @param max Max number of threads that will be active
22 * @param filename A file path with implementation of `ThreadWorker` class, relative path is fine.
23 * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
24 */
25 public constructor (
26 min: number,
27 public readonly max: number,
28 filename: string,
29 opts: PoolOptions<ThreadWorkerWithMessageChannel> = { maxTasks: 1000 }
30 ) {
31 super(min, filename, opts)
32 }
33
34 protected chooseWorker (): ThreadWorkerWithMessageChannel {
35 let worker: ThreadWorkerWithMessageChannel | undefined
36 for (const entry of this.tasks) {
37 if (entry[1] === 0) {
38 worker = entry[0]
39 break
40 }
41 }
42
43 if (worker) {
44 // a worker is free, use it
45 return worker
46 } else {
47 if (this.workers.length === this.max) {
48 this.emitter.emit('FullPool')
49 return super.chooseWorker()
50 }
51 // all workers are busy create a new worker
52 const worker = this.internalNewWorker()
53 worker.port2?.on('message', (message: MessageValue<Data>) => {
54 if (message.kill) {
55 this.sendToWorker(worker, { kill: 1 })
56 void this.destroyWorker(worker)
57 // clean workers from data structures
58 const workerIndex = this.workers.indexOf(worker)
59 this.workers.splice(workerIndex, 1)
60 this.tasks.delete(worker)
61 }
62 })
63 return worker
64 }
65 }
66 }