fix: fix race condition at counting executing tasks on worker node
[poolifier.git] / src / pools / abstract-pool.ts
index 53aad1fdfcb548f56c9b1e87e93e86799b11271d..bb5f02d49923c99c4b21dd068b431524e5b8ce38 100644 (file)
@@ -854,7 +854,19 @@ export abstract class AbstractPool<
     message: MessageValue<Response>
   ): void {
     const workerTaskStatistics = workerUsage.tasks
-    --workerTaskStatistics.executing
+    if (
+      workerTaskStatistics.executing != null &&
+      workerTaskStatistics.executing > 0
+    ) {
+      --workerTaskStatistics.executing
+    } else if (
+      workerTaskStatistics.executing != null &&
+      workerTaskStatistics.executing < 0
+    ) {
+      throw new Error(
+        'Worker usage statistics for tasks executing cannot be negative'
+      )
+    }
     if (message.taskError == null) {
       ++workerTaskStatistics.executed
     } else {