fix: node-worker-threads-pool needs inline imports in code block
[poolifier.git] / src / worker / abstract-worker.ts
index 76a7ee70ba96a93e6a92934a6b9cc54d81dbe821..1e1d3088fb7cce28ad22f1961899786e6edd5fdd 100644 (file)
@@ -45,7 +45,7 @@ export abstract class AbstractWorker<
    */
   protected lastTaskTimestamp!: number
   /**
-   * Performance statistics computation.
+   * Performance statistics computation requirements.
    */
   protected statistics!: WorkerStatistics
   /**
@@ -160,13 +160,13 @@ export abstract class AbstractWorker<
     } else if (message.parent != null) {
       // Main worker reference message received
       this.mainWorker = message.parent
+    } else if (message.statistics != null) {
+      // Statistics message received
+      this.statistics = message.statistics
     } else if (message.kill != null) {
       // Kill message received
       this.aliveInterval != null && clearInterval(this.aliveInterval)
       this.emitDestroy()
-    } else if (message.statistics != null) {
-      // Statistics message received
-      this.statistics = message.statistics
     }
   }
 
@@ -224,7 +224,7 @@ export abstract class AbstractWorker<
     message: MessageValue<Data>
   ): void {
     try {
-      let taskPerformance = this.beginTaskPerformance(message)
+      let taskPerformance = this.beginTaskPerformance()
       const res = fn(message.data)
       taskPerformance = this.endTaskPerformance(taskPerformance)
       this.sendToMainWorker({
@@ -256,7 +256,7 @@ export abstract class AbstractWorker<
     fn: WorkerAsyncFunction<Data, Response>,
     message: MessageValue<Data>
   ): void {
-    let taskPerformance = this.beginTaskPerformance(message)
+    let taskPerformance = this.beginTaskPerformance()
     fn(message.data)
       .then(res => {
         taskPerformance = this.endTaskPerformance(taskPerformance)
@@ -297,13 +297,10 @@ export abstract class AbstractWorker<
     return fn
   }
 
-  private beginTaskPerformance (message: MessageValue<Data>): TaskPerformance {
-    const timestamp = performance.now()
+  private beginTaskPerformance (): TaskPerformance {
+    this.checkStatistics()
     return {
-      timestamp,
-      ...(this.statistics.waitTime && {
-        waitTime: timestamp - (message.timestamp ?? timestamp)
-      }),
+      timestamp: performance.now(),
       ...(this.statistics.elu && { elu: performance.eventLoopUtilization() })
     }
   }
@@ -311,6 +308,7 @@ export abstract class AbstractWorker<
   private endTaskPerformance (
     taskPerformance: TaskPerformance
   ): TaskPerformance {
+    this.checkStatistics()
     return {
       ...taskPerformance,
       ...(this.statistics.runTime && {
@@ -321,4 +319,10 @@ export abstract class AbstractWorker<
       })
     }
   }
+
+  private checkStatistics (): void {
+    if (this.statistics == null) {
+      throw new Error('Performance statistics computation requirements not set')
+    }
+  }
 }