Use prettierx and eslint native (#85)
[poolifier.git] / src / workers.ts
CommitLineData
4ade5f1f 1import { isMainThread, parentPort } from 'worker_threads'
f045358d 2
4ade5f1f
S
3import { AsyncResource } from 'async_hooks'
4
5export interface ThreadWorkerOptions {
6 /**
7 * Max time to wait tasks to work on (in ms), after this period the new worker threads will die.
8 *
9 * @default 60.000 ms
10 */
11 maxInactiveTime?: number
12 /**
13 * `true` if your function contains async pieces, else `false`.
14 *
15 * @default false
16 */
17 async?: boolean
18}
a32e02ba 19
a32e02ba 20/**
4ade5f1f
S
21 * An example worker that will be always alive, you just need to **extend** this class if you want a static pool.
22 *
23 * When this worker is inactive for more than 1 minute, it will send this info to the main thread,
24 * if you are using DynamicThreadPool, the workers created after will be killed, the min num of thread will be guaranteed.
25 *
26 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
a32e02ba 27 * @since 0.0.1
28 */
777b7824 29// eslint-disable-next-line @typescript-eslint/no-explicit-any
4ade5f1f
S
30export class ThreadWorker<Data = any, Response = any> extends AsyncResource {
31 protected readonly maxInactiveTime: number
32 protected readonly async: boolean
33 protected lastTask: number
ee99693b
S
34 protected readonly interval?: NodeJS.Timeout
35 protected parent?: MessagePort
4ade5f1f
S
36
37 public constructor (
38 fn: (data: Data) => Response,
39 public readonly opts: ThreadWorkerOptions = {}
40 ) {
50811da2 41 super('worker-thread-pool:pioardi')
4ade5f1f 42
ee99693b 43 this.maxInactiveTime = this.opts.maxInactiveTime ?? 1000 * 60
7784f548 44 this.async = !!this.opts.async
a32e02ba 45 this.lastTask = Date.now()
46 if (!fn) throw new Error('Fn parameter is mandatory')
47 // keep the worker active
48 if (!isMainThread) {
cf9aa6c3 49 this.interval = setInterval(
fa0f5b28 50 this.checkAlive.bind(this),
cf9aa6c3 51 this.maxInactiveTime / 2
52 )
fa0f5b28 53 this.checkAlive.bind(this)()
a32e02ba 54 }
ee99693b
S
55 parentPort?.on(
56 'message',
57 (value: {
58 data?: Response
fa0f5b28 59 id?: number
ee99693b
S
60 parent?: MessagePort
61 kill?: number
62 }) => {
fa0f5b28 63 if (value?.data && value.id) {
ee99693b
S
64 // here you will receive messages
65 // console.log('This is the main thread ' + isMainThread)
66 if (this.async) {
fa0f5b28 67 this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
ee99693b 68 } else {
fa0f5b28 69 this.runInAsyncScope(this.run.bind(this), this, fn, value)
ee99693b
S
70 }
71 } else if (value.parent) {
72 // save the port to communicate with the main thread
73 // this will be received once
74 this.parent = value.parent
75 } else if (value.kill) {
76 // here is time to kill this thread, just clearing the interval
77 if (this.interval) clearInterval(this.interval)
78 this.emitDestroy()
7784f548 79 }
a32e02ba 80 }
ee99693b 81 )
a32e02ba 82 }
83
fa0f5b28 84 protected checkAlive (): void {
cf9aa6c3 85 if (Date.now() - this.lastTask > this.maxInactiveTime) {
ee99693b 86 this.parent?.postMessage({ kill: 1 })
a32e02ba 87 }
88 }
106744f7 89
fa0f5b28 90 protected run (
4ade5f1f 91 fn: (data: Data) => Response,
777b7824 92 value: { readonly data: Data; readonly id: number }
4ade5f1f 93 ): void {
106744f7 94 try {
8950a941 95 const res = fn(value.data)
fa0f5b28 96 this.parent?.postMessage({ data: res, id: value.id })
106744f7 97 this.lastTask = Date.now()
98 } catch (e) {
fa0f5b28 99 this.parent?.postMessage({ error: e, id: value.id })
106744f7 100 this.lastTask = Date.now()
101 }
102 }
7784f548 103
fa0f5b28 104 protected runAsync (
4ade5f1f 105 fn: (data: Data) => Promise<Response>,
777b7824 106 value: { readonly data: Data; readonly id: number }
4ade5f1f 107 ): void {
cf9aa6c3 108 fn(value.data)
ee99693b 109 .then(res => {
fa0f5b28 110 this.parent?.postMessage({ data: res, id: value.id })
cf9aa6c3 111 this.lastTask = Date.now()
112 })
ee99693b 113 .catch(e => {
fa0f5b28 114 this.parent?.postMessage({ error: e, id: value.id })
cf9aa6c3 115 this.lastTask = Date.now()
116 })
7784f548 117 }
a32e02ba 118}