Properly integrate standard JS tools for JS and TS code
[poolifier.git] / src / worker / abstract-worker.ts
1 import { AsyncResource } from 'async_hooks'
2 import type { Worker } from 'cluster'
3 import type { MessagePort } from '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 * @template MainWorker Type of main worker.
16 * @template Data Type of data this worker receives from pool's execution. This can only be serializable data.
17 * @template 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 * Options for the worker.
34 */
35 public readonly opts: WorkerOptions
36 /**
37 * Constructs a new poolifier worker.
38 *
39 * @param type The type of async event.
40 * @param isMain Whether this is the main worker or not.
41 * @param fn Function processed by the worker when the pool's `execution` function is invoked.
42 * @param mainWorker Reference to main worker.
43 * @param opts Options for the worker.
44 */
45 public constructor (
46 type: string,
47 isMain: boolean,
48 fn: (data: Data) => Response,
49 protected mainWorker: MainWorker | undefined | null,
50 opts: WorkerOptions = {
51 /**
52 * The kill behavior option on this Worker or its default value.
53 */
54 killBehavior: DEFAULT_KILL_BEHAVIOR,
55 /**
56 * The maximum time to keep this worker alive while idle.
57 * The pool automatically checks and terminates this worker when the time expires.
58 */
59 maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME
60 }
61 ) {
62 super(type)
63 this.opts = opts
64 this.checkFunctionInput(fn)
65 this.checkWorkerOptions(this.opts)
66 this.lastTaskTimestamp = Date.now()
67 // Keep the worker active
68 if (!isMain) {
69 this.aliveInterval = setInterval(
70 this.checkAlive.bind(this),
71 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
72 )
73 this.checkAlive.bind(this)()
74 }
75
76 this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
77 this.messageListener(value, fn)
78 })
79 }
80
81 protected messageListener (
82 value: MessageValue<Data, MainWorker>,
83 fn: (data: Data) => Response
84 ): void {
85 if (value.data !== undefined && value.id !== undefined) {
86 // Here you will receive messages
87 if (this.opts.async === true) {
88 this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
89 } else {
90 this.runInAsyncScope(this.run.bind(this), this, fn, value)
91 }
92 } else if (value.parent !== undefined) {
93 // Save a reference of the main worker to communicate with it
94 // This will be received once
95 this.mainWorker = value.parent
96 } else if (value.kill !== undefined) {
97 // Here is time to kill this worker, just clearing the interval
98 if (this.aliveInterval != null) clearInterval(this.aliveInterval)
99 this.emitDestroy()
100 }
101 }
102
103 private checkWorkerOptions (opts: WorkerOptions): void {
104 this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
105 this.opts.maxInactiveTime =
106 opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
107 this.opts.async = opts.async ?? false
108 }
109
110 /**
111 * Checks if the `fn` parameter is passed to the constructor.
112 *
113 * @param fn The function that should be defined.
114 */
115 private checkFunctionInput (fn: (data: Data) => Response): void {
116 if (fn == null) throw new Error('fn parameter is mandatory')
117 if (typeof fn !== 'function') { throw new TypeError('fn parameter is not a function') }
118 }
119
120 /**
121 * Returns the main worker.
122 *
123 * @returns Reference to the main worker.
124 */
125 protected getMainWorker (): MainWorker {
126 if (this.mainWorker == null) {
127 throw new Error('Main worker was not set')
128 }
129 return this.mainWorker
130 }
131
132 /**
133 * Sends a message to the main worker.
134 *
135 * @param message The response message.
136 */
137 protected abstract sendToMainWorker (message: MessageValue<Response>): void
138
139 /**
140 * Checks if the worker should be terminated, because its living too long.
141 */
142 protected checkAlive (): void {
143 if (
144 Date.now() - this.lastTaskTimestamp >
145 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
146 ) {
147 this.sendToMainWorker({ kill: this.opts.killBehavior })
148 }
149 }
150
151 /**
152 * Handles an error and convert it to a string so it can be sent back to the main worker.
153 *
154 * @param e The error raised by the worker.
155 * @returns Message of the error.
156 */
157 protected handleError (e: Error | string): string {
158 return e as string
159 }
160
161 /**
162 * Runs the given function synchronously.
163 *
164 * @param fn Function that will be executed.
165 * @param value Input data for the given function.
166 */
167 protected run (
168 fn: (data?: Data) => Response,
169 value: MessageValue<Data>
170 ): void {
171 try {
172 const startTaskTimestamp = Date.now()
173 const res = fn(value.data)
174 const taskRunTime = Date.now() - startTaskTimestamp
175 this.sendToMainWorker({ data: res, id: value.id, taskRunTime })
176 } catch (e) {
177 const err = this.handleError(e as Error)
178 this.sendToMainWorker({ error: err, id: value.id })
179 } finally {
180 this.lastTaskTimestamp = Date.now()
181 }
182 }
183
184 /**
185 * Runs the given function asynchronously.
186 *
187 * @param fn Function that will be executed.
188 * @param value Input data for the given function.
189 */
190 protected runAsync (
191 fn: (data?: Data) => Promise<Response>,
192 value: MessageValue<Data>
193 ): void {
194 const startTaskTimestamp = Date.now()
195 fn(value.data)
196 .then(res => {
197 const taskRunTime = Date.now() - startTaskTimestamp
198 this.sendToMainWorker({ data: res, id: value.id, taskRunTime })
199 return null
200 })
201 .catch(e => {
202 const err = this.handleError(e as Error)
203 this.sendToMainWorker({ error: err, id: value.id })
204 })
205 .finally(() => {
206 this.lastTaskTimestamp = Date.now()
207 })
208 .catch(EMPTY_FUNCTION)
209 }
210 }