forked from poolifier/poolifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract-worker.ts
208 lines (196 loc) · 6.15 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
import { AsyncResource } from 'async_hooks'
import type { Worker } from 'cluster'
import type { MessagePort } from 'worker_threads'
import type { MessageValue } from '../utility-types'
import { EMPTY_FUNCTION } from '../utils'
import type { KillBehavior, WorkerOptions } from './worker-options'
import { KillBehaviors } from './worker-options'
const DEFAULT_MAX_INACTIVE_TIME = 1000 * 60
const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT
/**
* Base class containing some shared logic for all poolifier workers.
*
* @template MainWorker Type of main worker.
* @template Data Type of data this worker receives from pool's execution. This can only be serializable data.
* @template 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 {
/**
* 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
/**
* Options for the worker.
*/
public readonly opts: WorkerOptions
/**
* Constructs a new poolifier worker.
*
* @param type The type of async event.
* @param isMain Whether this is the main worker or not.
* @param fn Function processed by the worker when the pool's `execution` function is invoked.
* @param mainWorker Reference to main worker.
* @param opts Options for the worker.
*/
public constructor (
type: string,
isMain: boolean,
fn: (data: Data) => Response,
protected mainWorker: MainWorker | undefined | null,
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.opts = opts
this.checkFunctionInput(fn)
this.checkWorkerOptions(this.opts)
this.lastTaskTimestamp = Date.now()
// Keep the worker active
if (!isMain) {
this.aliveInterval = setInterval(
this.checkAlive.bind(this),
(this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
)
this.checkAlive.bind(this)()
}
this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
this.messageListener(value, fn)
})
}
protected messageListener (
value: MessageValue<Data, MainWorker>,
fn: (data: Data) => Response
): void {
if (value.data !== undefined && value.id !== undefined) {
// Here you will receive messages
if (this.opts.async) {
this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
} else {
this.runInAsyncScope(this.run.bind(this), this, fn, value)
}
} else if (value.parent !== undefined) {
// Save a reference of the main worker to communicate with it
// This will be received once
this.mainWorker = value.parent
} else if (value.kill !== undefined) {
// Here is time to kill this worker, just clearing the interval
if (this.aliveInterval) clearInterval(this.aliveInterval)
this.emitDestroy()
}
}
private checkWorkerOptions (opts: WorkerOptions) {
this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
this.opts.maxInactiveTime =
opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
/**
* Whether the worker is working asynchronously or not.
*/
this.opts.async = !!opts.async
}
/**
* Check if the `fn` parameter is passed to the constructor.
*
* @param fn The function that should be defined.
*/
private checkFunctionInput (fn: (data: Data) => Response): void {
if (!fn) throw new Error('fn parameter is mandatory')
}
/**
* Returns the main worker.
*
* @returns Reference to the main worker.
*/
protected getMainWorker (): MainWorker {
if (!this.mainWorker) {
throw new Error('Main worker was not set')
}
return this.mainWorker
}
/**
* Send a message to the main worker.
*
* @param message The response message.
*/
protected abstract sendToMainWorker (message: MessageValue<Response>): void
/**
* Check to see if the worker should be terminated, because its living too long.
*/
protected checkAlive (): void {
if (
Date.now() - this.lastTaskTimestamp >
(this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
) {
this.sendToMainWorker({ kill: this.opts.killBehavior })
}
}
/**
* Handle 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
}
/**
* Run the given function synchronously.
*
* @param fn Function that will be executed.
* @param value Input data for the given function.
*/
protected run (
fn: (data?: Data) => Response,
value: MessageValue<Data>
): void {
try {
const res = fn(value.data)
this.sendToMainWorker({ data: res, id: value.id })
} catch (e) {
const err = this.handleError(e as Error)
this.sendToMainWorker({ error: err, id: value.id })
} finally {
this.lastTaskTimestamp = Date.now()
}
}
/**
* Run the given function asynchronously.
*
* @param fn Function that will be executed.
* @param value Input data for the given function.
*/
protected runAsync (
fn: (data?: Data) => Promise<Response>,
value: MessageValue<Data>
): void {
fn(value.data)
.then(res => {
this.sendToMainWorker({ data: res, id: value.id })
return null
})
.catch(e => {
const err = this.handleError(e as Error)
this.sendToMainWorker({ error: err, id: value.id })
})
.finally(() => {
this.lastTaskTimestamp = Date.now()
})
.catch(EMPTY_FUNCTION)
}
}