-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
abstract-worker.ts
273 lines (260 loc) · 8.45 KB
/
abstract-worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { AsyncResource } from 'node:async_hooks'
import type { Worker } from 'node:cluster'
import type { MessagePort } from 'node:worker_threads'
import type {
MessageValue,
TaskFunctions,
WorkerAsyncFunction,
WorkerFunction,
WorkerSyncFunction
} from '../utility-types'
import { EMPTY_FUNCTION, isPlainObject } from '../utils'
import type { KillBehavior, WorkerOptions } from './worker-options'
import { KillBehaviors } from './worker-options'
const DEFAULT_FUNCTION_NAME = 'default'
const DEFAULT_MAX_INACTIVE_TIME = 60000
const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT
/**
* Base class that implements some shared logic for all poolifier workers.
*
* @typeParam MainWorker - Type of main worker.
* @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
* @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data.
*/
export abstract class AbstractWorker<
MainWorker extends Worker | MessagePort,
Data = unknown,
Response = unknown
> extends AsyncResource {
/**
* Task function(s) processed by the worker when the pool's `execution` function is invoked.
*/
protected taskFunctions!: Map<string, WorkerFunction<Data, Response>>
/**
* Timestamp of the last task processed by this worker.
*/
protected lastTaskTimestamp!: number
/**
* Handler id of the `aliveInterval` worker alive check.
*/
protected readonly aliveInterval?: NodeJS.Timeout
/**
* Constructs a new poolifier worker.
*
* @param type - The type of async event.
* @param isMain - Whether this is the main worker or not.
* @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
* @param mainWorker - Reference to main worker.
* @param opts - Options for the worker.
*/
public constructor (
type: string,
protected readonly isMain: boolean,
taskFunctions:
| WorkerFunction<Data, Response>
| TaskFunctions<Data, Response>,
protected mainWorker: MainWorker | undefined | null,
protected readonly opts: WorkerOptions = {
/**
* The kill behavior option on this worker or its default value.
*/
killBehavior: DEFAULT_KILL_BEHAVIOR,
/**
* The maximum time to keep this worker alive while idle.
* The pool automatically checks and terminates this worker when the time expires.
*/
maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME
}
) {
super(type)
this.checkWorkerOptions(this.opts)
this.checkTaskFunctions(taskFunctions)
if (!this.isMain) {
this.lastTaskTimestamp = performance.now()
this.aliveInterval = setInterval(
this.checkAlive.bind(this),
(this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
)
this.checkAlive.bind(this)()
}
this.mainWorker?.on('message', this.messageListener.bind(this))
}
private checkWorkerOptions (opts: WorkerOptions): void {
this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
this.opts.maxInactiveTime =
opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
delete this.opts.async
}
/**
* Checks if the `taskFunctions` parameter is passed to the constructor.
*
* @param taskFunctions - The task function(s) parameter that should be checked.
*/
private checkTaskFunctions (
taskFunctions:
| WorkerFunction<Data, Response>
| TaskFunctions<Data, Response>
): void {
if (taskFunctions == null) {
throw new Error('taskFunctions parameter is mandatory')
}
this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>()
if (typeof taskFunctions === 'function') {
this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this))
} else if (isPlainObject(taskFunctions)) {
let firstEntry = true
for (const [name, fn] of Object.entries(taskFunctions)) {
if (typeof fn !== 'function') {
throw new TypeError(
'A taskFunctions parameter object value is not a function'
)
}
this.taskFunctions.set(name, fn.bind(this))
if (firstEntry) {
this.taskFunctions.set(DEFAULT_FUNCTION_NAME, fn.bind(this))
firstEntry = false
}
}
if (firstEntry) {
throw new Error('taskFunctions parameter object is empty')
}
} else {
throw new TypeError(
'taskFunctions parameter is not a function or a plain object'
)
}
}
/**
* Worker message listener.
*
* @param message - Message received.
*/
protected messageListener (message: MessageValue<Data, MainWorker>): void {
if (message.id != null && message.data != null) {
// Task message received
const fn = this.getTaskFunction(message.name)
if (fn?.constructor.name === 'AsyncFunction') {
this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)
} else {
this.runInAsyncScope(this.runSync.bind(this), this, fn, message)
}
} else if (message.parent != null) {
// Main worker reference message received
this.mainWorker = message.parent
} else if (message.kill != null) {
// Kill message received
this.aliveInterval != null && clearInterval(this.aliveInterval)
this.emitDestroy()
}
}
/**
* Returns the main worker.
*
* @returns Reference to the main worker.
*/
protected getMainWorker (): MainWorker {
if (this.mainWorker == null) {
throw new Error('Main worker was not set')
}
return this.mainWorker
}
/**
* Sends a message to the main worker.
*
* @param message - The response message.
*/
protected abstract sendToMainWorker (message: MessageValue<Response>): void
/**
* Checks if the worker should be terminated, because its living too long.
*/
protected checkAlive (): void {
if (
performance.now() - this.lastTaskTimestamp >
(this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
) {
this.sendToMainWorker({ kill: this.opts.killBehavior })
}
}
/**
* Handles an error and convert it to a string so it can be sent back to the main worker.
*
* @param e - The error raised by the worker.
* @returns Message of the error.
*/
protected handleError (e: Error | string): string {
return e as string
}
/**
* Runs the given function synchronously.
*
* @param fn - Function that will be executed.
* @param message - Input data for the given function.
*/
protected runSync (
fn: WorkerSyncFunction<Data, Response>,
message: MessageValue<Data>
): void {
try {
const startTimestamp = performance.now()
const waitTime = startTimestamp - (message.submissionTimestamp ?? 0)
const res = fn(message.data)
const runTime = performance.now() - startTimestamp
this.sendToMainWorker({
data: res,
id: message.id,
runTime,
waitTime
})
} catch (e) {
const err = this.handleError(e as Error)
this.sendToMainWorker({ error: err, id: message.id })
} finally {
!this.isMain && (this.lastTaskTimestamp = performance.now())
}
}
/**
* Runs the given function asynchronously.
*
* @param fn - Function that will be executed.
* @param message - Input data for the given function.
*/
protected runAsync (
fn: WorkerAsyncFunction<Data, Response>,
message: MessageValue<Data>
): void {
const startTimestamp = performance.now()
const waitTime = startTimestamp - (message.submissionTimestamp ?? 0)
fn(message.data)
.then(res => {
const runTime = performance.now() - startTimestamp
this.sendToMainWorker({
data: res,
id: message.id,
runTime,
waitTime
})
return null
})
.catch(e => {
const err = this.handleError(e as Error)
this.sendToMainWorker({ error: err, id: message.id })
})
.finally(() => {
!this.isMain && (this.lastTaskTimestamp = performance.now())
})
.catch(EMPTY_FUNCTION)
}
/**
* Gets the task function in the given scope.
*
* @param name - Name of the function that will be returned.
*/
private getTaskFunction (name?: string): WorkerFunction<Data, Response> {
name = name ?? DEFAULT_FUNCTION_NAME
const fn = this.taskFunctions.get(name)
if (fn == null) {
throw new Error(`Task function '${name}' not found`)
}
return fn
}
}