Only allow primitive JSON for transfer between worker and main worker (#128)
[poolifier.git] / src / pools / thread / dynamic.ts
CommitLineData
d3c8a1a8 1import type { JSONValue, MessageValue } from '../../utility-types'
c97c7edb
S
2import type { PoolOptions } from '../abstract-pool'
3import type { ThreadWorkerWithMessageChannel } from './fixed'
325f50bc 4import { FixedThreadPool } from './fixed'
f045358d 5
4ade5f1f
S
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 */
60fbd6d6 15export class DynamicThreadPool<
d3c8a1a8
S
16 Data extends JSONValue = JSONValue,
17 Response extends JSONValue = JSONValue
4ade5f1f 18> extends FixedThreadPool<Data, Response> {
4ade5f1f
S
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 (
c97c7edb 26 min: number,
4ade5f1f 27 public readonly max: number,
c97c7edb
S
28 filename: string,
29 opts: PoolOptions<ThreadWorkerWithMessageChannel> = { maxTasks: 1000 }
4ade5f1f
S
30 ) {
31 super(min, filename, opts)
4ade5f1f
S
32 }
33
c97c7edb
S
34 protected chooseWorker (): ThreadWorkerWithMessageChannel {
35 let worker: ThreadWorkerWithMessageChannel | undefined
4ade5f1f
S
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')
fa0f5b28 49 return super.chooseWorker()
4ade5f1f
S
50 }
51 // all workers are busy create a new worker
c97c7edb
S
52 const worker = this.internalNewWorker()
53 worker.port2?.on('message', (message: MessageValue<Data>) => {
4ade5f1f 54 if (message.kill) {
c97c7edb
S
55 this.sendToWorker(worker, { kill: 1 })
56 void this.destroyWorker(worker)
68b2f517
S
57 // clean workers from data structures
58 const workerIndex = this.workers.indexOf(worker)
59 this.workers.splice(workerIndex, 1)
60 this.tasks.delete(worker)
4ade5f1f
S
61 }
62 })
63 return worker
64 }
65 }
66}