- protected messageListener (message: MessageValue<Data, Data>): void {
- if (message.workerId === this.id) {
- if (message.ready != null) {
- // Startup message received
- this.workerReady()
- } else if (message.statistics != null) {
- // Statistics message received
- this.statistics = message.statistics
- } else if (message.checkAlive != null) {
- // Check alive message received
- message.checkAlive ? this.startCheckAlive() : this.stopCheckAlive()
- } else if (message.id != null && message.data != null) {
- // Task message received
- const fn = this.getTaskFunction(message.name)
- if (isAsyncFunction(fn)) {
- this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)
- } else {
- this.runInAsyncScope(this.runSync.bind(this), this, fn, message)
- }
- } else if (message.kill === true) {
- // Kill message received
- this.stopCheckAlive()
+ protected messageListener (message: MessageValue<Data>): void {
+ this.checkMessageWorkerId(message)
+ if (message.statistics != null) {
+ // Statistics message received
+ this.statistics = message.statistics
+ } else if (message.checkActive != null) {
+ // Check active message received
+ message.checkActive ? this.startCheckActive() : this.stopCheckActive()
+ } else if (message.taskId != null && message.data != null) {
+ // Task message received
+ this.run(message)
+ } else if (message.kill === true) {
+ // Kill message received
+ this.handleKillMessage(message)
+ }
+ }
+
+ /**
+ * Handles a kill message sent by the main worker.
+ *
+ * @param message - The kill message.
+ */
+ protected handleKillMessage (message: MessageValue<Data>): void {
+ this.stopCheckActive()
+ if (isAsyncFunction(this.opts.killHandler)) {
+ (this.opts.killHandler?.() as Promise<void>)
+ .then(() => {
+ this.sendToMainWorker({ kill: 'success', workerId: this.id })
+ return null
+ })
+ .catch(() => {
+ this.sendToMainWorker({ kill: 'failure', workerId: this.id })
+ })
+ .finally(() => {
+ this.emitDestroy()
+ })
+ .catch(EMPTY_FUNCTION)
+ } else {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
+ this.opts.killHandler?.() as void
+ this.sendToMainWorker({ kill: 'success', workerId: this.id })
+ } catch {
+ this.sendToMainWorker({ kill: 'failure', workerId: this.id })
+ } finally {