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