+ const { taskFunctionOperation, taskFunctionProperties, taskFunction } =
+ message
+ if (taskFunctionProperties == null) {
+ throw new Error(
+ 'Cannot handle task function operation message without task function properties'
+ )
+ }
+ let response: TaskFunctionOperationResult
+ switch (taskFunctionOperation) {
+ case 'add':
+ response = this.addTaskFunction(taskFunctionProperties.name, {
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
+ taskFunction: new Function(
+ `return ${taskFunction}`
+ )() as TaskFunction<Data, Response>,
+ ...(taskFunctionProperties.priority != null && {
+ priority: taskFunctionProperties.priority
+ }),
+ ...(taskFunctionProperties.strategy != null && {
+ strategy: taskFunctionProperties.strategy
+ })
+ })
+ break
+ case 'remove':
+ response = this.removeTaskFunction(taskFunctionProperties.name)
+ break
+ case 'default':
+ response = this.setDefaultTaskFunction(taskFunctionProperties.name)
+ break
+ default:
+ response = { status: false, error: new Error('Unknown task operation') }
+ break
+ }
+ this.sendToMainWorker({
+ taskFunctionOperation,
+ taskFunctionOperationStatus: response.status,
+ taskFunctionProperties,
+ ...(!response.status &&
+ response.error != null && {
+ workerError: {
+ name: taskFunctionProperties.name,
+ message: this.handleError(response.error as Error | string)
+ }
+ })
+ })
+ }
+
+ /**
+ * 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' })
+ return undefined
+ })
+ .catch(() => {
+ this.sendToMainWorker({ kill: 'failure' })
+ })
+ } else {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
+ this.opts.killHandler?.() as void
+ this.sendToMainWorker({ kill: 'success' })
+ } catch {
+ this.sendToMainWorker({ kill: 'failure' })
+ }
+ }
+ }
+
+ /**
+ * Check if the message worker id is set and matches the worker id.
+ *
+ * @param message - The message to check.
+ * @throws {@link https://nodejs.org/api/errors.html#class-error} If the message worker id is not set or does not match the worker id.
+ */
+ private checkMessageWorkerId (message: MessageValue<Data>): void {
+ if (message.workerId == null) {
+ throw new Error('Message worker id is not set')
+ } else if (message.workerId !== this.id) {
+ throw new Error(
+ `Message worker id ${message.workerId} does not match the worker id ${this.id}`
+ )
+ }
+ }
+
+ /**
+ * Starts the worker check active interval.
+ */
+ private startCheckActive (): void {
+ this.lastTaskTimestamp = performance.now()
+ this.activeInterval = setInterval(
+ this.checkActive.bind(this),
+ (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
+ )
+ }
+
+ /**
+ * Stops the worker check active interval.
+ */
+ private stopCheckActive (): void {
+ if (this.activeInterval != null) {
+ clearInterval(this.activeInterval)
+ delete this.activeInterval
+ }
+ }
+
+ /**
+ * Checks if the worker should be terminated, because its living too long.
+ */
+ private checkActive (): void {
+ if (
+ performance.now() - this.lastTaskTimestamp >
+ (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
+ ) {
+ this.sendToMainWorker({ kill: this.opts.killBehavior })
+ }
+ }
+
+ /**
+ * Returns the main worker.
+ *
+ * @returns Reference to the main worker.
+ * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
+ */
+ protected getMainWorker (): MainWorker {
+ if (this.mainWorker == null) {
+ throw new Error('Main worker not set')
+ }
+ return this.mainWorker
+ }
+
+ /**
+ * Sends a message to main worker.
+ *
+ * @param message - The response message.
+ */
+ protected abstract sendToMainWorker (
+ message: MessageValue<Response, Data>
+ ): void
+
+ /**
+ * Sends task functions properties to the main worker.
+ */
+ protected sendTaskFunctionsPropertiesToMainWorker (): void {
+ this.sendToMainWorker({
+ taskFunctionsProperties: this.listTaskFunctionsProperties()
+ })
+ }
+
+ /**
+ * Handles an error and convert it to a string so it can be sent back to the main worker.
+ *
+ * @param error - The error raised by the worker.
+ * @returns The error message.
+ */
+ protected handleError (error: Error | string): string {
+ return error instanceof Error ? error.message : error
+ }
+
+ /**
+ * Runs the given task.
+ *
+ * @param task - The task to execute.
+ */
+ protected readonly run = (task: Task<Data>): void => {
+ const { name, taskId, data } = task
+ const taskFunctionName = name ?? DEFAULT_TASK_NAME
+ if (!this.taskFunctions.has(taskFunctionName)) {
+ this.sendToMainWorker({
+ workerError: {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ name: name!,
+ message: `Task function '${name}' not found`,
+ data
+ },
+ taskId
+ })
+ return
+ }
+ const fn = this.taskFunctions.get(taskFunctionName)?.taskFunction
+ if (isAsyncFunction(fn)) {
+ this.runAsync(fn as TaskAsyncFunction<Data, Response>, task)
+ } else {
+ this.runSync(fn as TaskSyncFunction<Data, Response>, task)
+ }
+ }
+
+ /**
+ * Runs the given task function synchronously.
+ *
+ * @param fn - Task function that will be executed.
+ * @param task - Input data for the task function.
+ */
+ protected readonly runSync = (
+ fn: TaskSyncFunction<Data, Response>,
+ task: Task<Data>
+ ): void => {
+ const { name, taskId, data } = task
+ try {
+ let taskPerformance = this.beginTaskPerformance(name)
+ const res = fn(data)
+ taskPerformance = this.endTaskPerformance(taskPerformance)
+ this.sendToMainWorker({
+ data: res,
+ taskPerformance,
+ taskId
+ })
+ } catch (error) {
+ this.sendToMainWorker({
+ workerError: {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ name: name!,
+ message: this.handleError(error as Error | string),
+ data
+ },
+ taskId
+ })
+ } finally {
+ this.updateLastTaskTimestamp()
+ }
+ }
+
+ /**
+ * Runs the given task function asynchronously.
+ *
+ * @param fn - Task function that will be executed.
+ * @param task - Input data for the task function.
+ */
+ protected readonly runAsync = (
+ fn: TaskAsyncFunction<Data, Response>,
+ task: Task<Data>
+ ): void => {
+ const { name, taskId, data } = task
+ let taskPerformance = this.beginTaskPerformance(name)
+ fn(data)