Linting
[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, KillBehavior } from '../utility-types'
5 import type { WorkerOptions } from './worker-options'
6 // import { killBehaviorEnumeration } from './worker-options'
7
8 const defaultMaxInactiveTime = 1000 * 60
9 // TODO fix this and avoid that SOFT/HARD words are replicated so much times into the project
10 const defaultKillBehavior: KillBehavior = 'SOFT'
11
12 /**
13 * Base class containing 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.
17 * @template Response Type of response the worker sends back to the main worker.
18 */
19 export abstract class AbstractWorker<
20 MainWorker extends Worker | MessagePort,
21 Data = unknown,
22 Response = unknown
23 > extends AsyncResource {
24 /**
25 * The maximum time to keep this worker alive while idle. The pool automatically checks and terminates this worker when the time expires.
26 */
27 protected readonly maxInactiveTime: number
28 /**
29 * The kill behavior set as option on the Worker constructor or a default value.
30 */
31 protected readonly killBehavior: KillBehavior
32 /**
33 * Whether the worker is working asynchronously or not.
34 */
35 protected readonly async: boolean
36 /**
37 * Timestamp of the last task processed by this worker.
38 */
39 protected lastTask: number
40 /**
41 * Handler ID of the `interval` alive check.
42 */
43 protected readonly interval?: NodeJS.Timeout
44
45 /**
46 * Constructs a new poolifier worker.
47 *
48 * @param type The type of async event.
49 * @param isMain Whether this is the main worker or not.
50 * @param fn Function processed by the worker when the pool's `execution` function is invoked.
51 * @param mainWorker Reference to main worker.
52 * @param opts Options for the worker.
53 */
54 public constructor (
55 type: string,
56 isMain: boolean,
57 fn: (data: Data) => Response,
58 protected mainWorker?: MainWorker | null,
59 public readonly opts: WorkerOptions = {
60 killBehavior: defaultKillBehavior,
61 maxInactiveTime: defaultMaxInactiveTime
62 }
63 ) {
64 super(type)
65 this.killBehavior = this.opts.killBehavior ?? defaultKillBehavior
66 this.maxInactiveTime = this.opts.maxInactiveTime ?? defaultMaxInactiveTime
67 this.async = !!this.opts.async
68 this.lastTask = Date.now()
69 if (!fn) throw new Error('fn parameter is mandatory')
70 // Keep the worker active
71 if (!isMain) {
72 this.interval = setInterval(
73 this.checkAlive.bind(this),
74 this.maxInactiveTime / 2
75 )
76 this.checkAlive.bind(this)()
77 }
78
79 this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
80 if (value?.data && value.id) {
81 // Here you will receive messages
82 if (this.async) {
83 this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
84 } else {
85 this.runInAsyncScope(this.run.bind(this), this, fn, value)
86 }
87 } else if (value.parent) {
88 // Save a reference of the main worker to communicate with it
89 // This will be received once
90 this.mainWorker = value.parent
91 } else if (value.kill) {
92 // Here is time to kill this worker, just clearing the interval
93 if (this.interval) clearInterval(this.interval)
94 this.emitDestroy()
95 }
96 })
97 }
98
99 /**
100 * Returns the main worker.
101 *
102 * @returns Reference to the main worker.
103 */
104 protected getMainWorker (): MainWorker {
105 if (!this.mainWorker) {
106 throw new Error('Main worker was not set')
107 }
108 return this.mainWorker
109 }
110
111 /**
112 * Send a message to the main worker.
113 *
114 * @param message The response message.
115 */
116 protected abstract sendToMainWorker (message: MessageValue<Response>): void
117
118 /**
119 * Check to see if the worker should be terminated, because its living too long.
120 */
121 protected checkAlive (): void {
122 if (Date.now() - this.lastTask > this.maxInactiveTime) {
123 this.sendToMainWorker({ kill: this.killBehavior })
124 }
125 }
126
127 /**
128 * Handle an error and convert it to a string so it can be sent back to the main worker.
129 *
130 * @param e The error raised by the worker.
131 * @returns Message of the error.
132 */
133 protected handleError (e: Error | string): string {
134 return (e as unknown) as string
135 }
136
137 /**
138 * Run the given function synchronously.
139 *
140 * @param fn Function that will be executed.
141 * @param value Input data for the given function.
142 */
143 protected run (
144 fn: (data?: Data) => Response,
145 value: MessageValue<Data>
146 ): void {
147 try {
148 const res = fn(value.data)
149 this.sendToMainWorker({ data: res, id: value.id })
150 this.lastTask = Date.now()
151 } catch (e) {
152 const err = this.handleError(e)
153 this.sendToMainWorker({ error: err, id: value.id })
154 this.lastTask = Date.now()
155 }
156 }
157
158 /**
159 * Run the given function asynchronously.
160 *
161 * @param fn Function that will be executed.
162 * @param value Input data for the given function.
163 */
164 protected runAsync (
165 fn: (data?: Data) => Promise<Response>,
166 value: MessageValue<Data>
167 ): void {
168 fn(value.data)
169 .then(res => {
170 this.sendToMainWorker({ data: res, id: value.id })
171 this.lastTask = Date.now()
172 return null
173 })
174 .catch(e => {
175 const err = this.handleError(e)
176 this.sendToMainWorker({ error: err, id: value.id })
177 this.lastTask = Date.now()
178 })
179 }
180 }