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