feat: restart worker in case of uncaught error
[poolifier.git] / src / worker / abstract-worker.ts
index 12fb67af32934383a9498e541fadc031e85cbafe..8a38b4e576464ecb88078540cc8604d7b3ad323f 100644 (file)
@@ -87,7 +87,7 @@ export abstract class AbstractWorker<
     this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
     this.opts.maxInactiveTime =
       opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
-    this.opts.async = opts.async ?? false
+    delete this.opts.async
   }
 
   /**
@@ -103,14 +103,6 @@ export abstract class AbstractWorker<
     if (taskFunctions == null) {
       throw new Error('taskFunctions parameter is mandatory')
     }
-    if (
-      typeof taskFunctions !== 'function' &&
-      typeof taskFunctions !== 'object'
-    ) {
-      throw new TypeError(
-        'taskFunctions parameter is not a function or an object'
-      )
-    }
     this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>()
     if (typeof taskFunctions === 'function') {
       this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this))
@@ -132,7 +124,9 @@ export abstract class AbstractWorker<
         throw new Error('taskFunctions parameter object is empty')
       }
     } else {
-      throw new TypeError('taskFunctions parameter is not an object literal')
+      throw new TypeError(
+        'taskFunctions parameter is not a function or a plain object'
+      )
     }
   }
 
@@ -213,12 +207,14 @@ export abstract class AbstractWorker<
   ): 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
+        runTime,
+        waitTime
       })
     } catch (e) {
       const err = this.handleError(e as Error)
@@ -239,13 +235,15 @@ export abstract class AbstractWorker<
     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
+          runTime,
+          waitTime
         })
         return null
       })
@@ -268,7 +266,7 @@ export abstract class AbstractWorker<
     name = name ?? DEFAULT_FUNCTION_NAME
     const fn = this.taskFunctions.get(name)
     if (fn == null) {
-      throw new Error(`Task function "${name}" not found`)
+      throw new Error(`Task function '${name}' not found`)
     }
     return fn
   }