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