fix: add missing crypto import
[poolifier.git] / src / worker / abstract-worker.ts
CommitLineData
fc3e6586
JB
1import { AsyncResource } from 'node:async_hooks'
2import type { Worker } from 'node:cluster'
3import type { MessagePort } from 'node:worker_threads'
1a81f8af 4import type { MessageValue } from '../utility-types'
6e9d10db 5import { EMPTY_FUNCTION } from '../utils'
a9d9ea34
JB
6import {
7 isKillBehavior,
8 type KillBehavior,
9 type WorkerOptions
10} from './worker-options'
1a81f8af 11import { KillBehaviors } from './worker-options'
4c35177b 12
978aad6f 13const DEFAULT_MAX_INACTIVE_TIME = 60000
1a81f8af 14const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT
c97c7edb 15
729c563d 16/**
ea7a90d3 17 * Base class that implements some shared logic for all poolifier workers.
729c563d 18 *
38e795c1
JB
19 * @typeParam MainWorker - Type of main worker.
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.
729c563d 22 */
c97c7edb 23export abstract class AbstractWorker<
838898f1 24 MainWorker extends Worker | MessagePort,
d3c8a1a8
S
25 Data = unknown,
26 Response = unknown
c97c7edb 27> extends AsyncResource {
729c563d
S
28 /**
29 * Timestamp of the last task processed by this worker.
30 */
a9d9ea34 31 protected lastTaskTimestamp!: number
729c563d 32 /**
e088a00c 33 * Handler Id of the `aliveInterval` worker alive check.
729c563d 34 */
e088a00c 35 protected readonly aliveInterval?: NodeJS.Timeout
dc5d0cb3
JB
36 /**
37 * Options for the worker.
38 */
39 public readonly opts: WorkerOptions
c97c7edb 40 /**
729c563d 41 * Constructs a new poolifier worker.
c97c7edb 42 *
38e795c1
JB
43 * @param type - The type of async event.
44 * @param isMain - Whether this is the main worker or not.
45 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
46 * @param mainWorker - Reference to main worker.
47 * @param opts - Options for the worker.
c97c7edb
S
48 */
49 public constructor (
50 type: string,
51 isMain: boolean,
52 fn: (data: Data) => Response,
7e0d447f 53 protected mainWorker: MainWorker | undefined | null,
59a11fd2 54 opts: WorkerOptions = {
e088a00c
JB
55 /**
56 * The kill behavior option on this Worker or its default value.
57 */
1a81f8af 58 killBehavior: DEFAULT_KILL_BEHAVIOR,
e088a00c
JB
59 /**
60 * The maximum time to keep this worker alive while idle.
61 * The pool automatically checks and terminates this worker when the time expires.
62 */
1a81f8af 63 maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME
4c35177b 64 }
c97c7edb
S
65 ) {
66 super(type)
59a11fd2 67 this.opts = opts
c510fea7 68 this.checkFunctionInput(fn)
e088a00c 69 this.checkWorkerOptions(this.opts)
a9d9ea34
JB
70 if (!isMain && isKillBehavior(KillBehaviors.HARD, this.opts.killBehavior)) {
71 this.lastTaskTimestamp = Date.now()
e088a00c 72 this.aliveInterval = setInterval(
c97c7edb 73 this.checkAlive.bind(this),
e088a00c 74 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
c97c7edb
S
75 )
76 this.checkAlive.bind(this)()
77 }
838898f1
S
78
79 this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
cf597bc5 80 this.messageListener(value, fn)
838898f1 81 })
c97c7edb
S
82 }
83
cf597bc5
JB
84 protected messageListener (
85 value: MessageValue<Data, MainWorker>,
86 fn: (data: Data) => Response
87 ): void {
88 if (value.data !== undefined && value.id !== undefined) {
89 // Here you will receive messages
6bd72cd0 90 if (this.opts.async === true) {
cf597bc5
JB
91 this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
92 } else {
93 this.runInAsyncScope(this.run.bind(this), this, fn, value)
94 }
95 } else if (value.parent !== undefined) {
96 // Save a reference of the main worker to communicate with it
97 // This will be received once
98 this.mainWorker = value.parent
99 } else if (value.kill !== undefined) {
100 // Here is time to kill this worker, just clearing the interval
78cea37e 101 if (this.aliveInterval != null) clearInterval(this.aliveInterval)
cf597bc5
JB
102 this.emitDestroy()
103 }
104 }
105
78cea37e 106 private checkWorkerOptions (opts: WorkerOptions): void {
e088a00c
JB
107 this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
108 this.opts.maxInactiveTime =
109 opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
78cea37e 110 this.opts.async = opts.async ?? false
e088a00c
JB
111 }
112
c510fea7 113 /**
8accb8d5 114 * Checks if the `fn` parameter is passed to the constructor.
c510fea7 115 *
38e795c1 116 * @param fn - The function that should be defined.
c510fea7 117 */
a35560ba 118 private checkFunctionInput (fn: (data: Data) => Response): void {
78cea37e 119 if (fn == null) throw new Error('fn parameter is mandatory')
af5204ed
JB
120 if (typeof fn !== 'function') {
121 throw new TypeError('fn parameter is not a function')
122 }
c510fea7
APA
123 }
124
729c563d
S
125 /**
126 * Returns the main worker.
838898f1
S
127 *
128 * @returns Reference to the main worker.
729c563d 129 */
838898f1 130 protected getMainWorker (): MainWorker {
78cea37e 131 if (this.mainWorker == null) {
838898f1
S
132 throw new Error('Main worker was not set')
133 }
134 return this.mainWorker
135 }
c97c7edb 136
729c563d 137 /**
8accb8d5 138 * Sends a message to the main worker.
729c563d 139 *
38e795c1 140 * @param message - The response message.
729c563d 141 */
c97c7edb
S
142 protected abstract sendToMainWorker (message: MessageValue<Response>): void
143
729c563d 144 /**
a05c10de 145 * Checks if the worker should be terminated, because its living too long.
729c563d 146 */
c97c7edb 147 protected checkAlive (): void {
e088a00c
JB
148 if (
149 Date.now() - this.lastTaskTimestamp >
150 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
151 ) {
152 this.sendToMainWorker({ kill: this.opts.killBehavior })
c97c7edb
S
153 }
154 }
155
729c563d 156 /**
8accb8d5 157 * Handles an error and convert it to a string so it can be sent back to the main worker.
729c563d 158 *
38e795c1 159 * @param e - The error raised by the worker.
50eceb07 160 * @returns Message of the error.
729c563d 161 */
c97c7edb 162 protected handleError (e: Error | string): string {
4a34343d 163 return e as string
c97c7edb
S
164 }
165
729c563d 166 /**
8accb8d5 167 * Runs the given function synchronously.
729c563d 168 *
38e795c1
JB
169 * @param fn - Function that will be executed.
170 * @param value - Input data for the given function.
729c563d 171 */
c97c7edb
S
172 protected run (
173 fn: (data?: Data) => Response,
174 value: MessageValue<Data>
175 ): void {
176 try {
bf9549ae 177 const startTaskTimestamp = Date.now()
c97c7edb 178 const res = fn(value.data)
bf9549ae
JB
179 const taskRunTime = Date.now() - startTaskTimestamp
180 this.sendToMainWorker({ data: res, id: value.id, taskRunTime })
c97c7edb 181 } catch (e) {
0a23f635 182 const err = this.handleError(e as Error)
c97c7edb 183 this.sendToMainWorker({ error: err, id: value.id })
6e9d10db 184 } finally {
a9d9ea34
JB
185 isKillBehavior(KillBehaviors.HARD, this.opts.killBehavior) &&
186 (this.lastTaskTimestamp = Date.now())
c97c7edb
S
187 }
188 }
189
729c563d 190 /**
8accb8d5 191 * Runs the given function asynchronously.
729c563d 192 *
38e795c1
JB
193 * @param fn - Function that will be executed.
194 * @param value - Input data for the given function.
729c563d 195 */
c97c7edb
S
196 protected runAsync (
197 fn: (data?: Data) => Promise<Response>,
198 value: MessageValue<Data>
199 ): void {
bf9549ae 200 const startTaskTimestamp = Date.now()
c97c7edb
S
201 fn(value.data)
202 .then(res => {
bf9549ae
JB
203 const taskRunTime = Date.now() - startTaskTimestamp
204 this.sendToMainWorker({ data: res, id: value.id, taskRunTime })
c97c7edb
S
205 return null
206 })
207 .catch(e => {
f3636726 208 const err = this.handleError(e as Error)
c97c7edb 209 this.sendToMainWorker({ error: err, id: value.id })
6e9d10db
JB
210 })
211 .finally(() => {
a9d9ea34
JB
212 isKillBehavior(KillBehaviors.HARD, this.opts.killBehavior) &&
213 (this.lastTaskTimestamp = Date.now())
c97c7edb 214 })
6e9d10db 215 .catch(EMPTY_FUNCTION)
c97c7edb
S
216 }
217}