refactor: cleanup type import
[poolifier.git] / src / worker / abstract-worker.ts
index 3a81e0f847f753ea55a7630d45a72fd08ec18a85..6a7a43259f11392fc764bf74e4cada6e20bc6518 100644 (file)
@@ -1,6 +1,6 @@
-import { AsyncResource } from 'async_hooks'
-import type { Worker } from 'cluster'
-import type { MessagePort } from 'worker_threads'
+import { AsyncResource } from 'node:async_hooks'
+import type { Worker } from 'node:cluster'
+import type { MessagePort } from 'node:worker_threads'
 import type { MessageValue } from '../utility-types'
 import { EMPTY_FUNCTION } from '../utils'
 import type { KillBehavior, WorkerOptions } from './worker-options'
@@ -24,7 +24,7 @@ export abstract class AbstractWorker<
   /**
    * Timestamp of the last task processed by this worker.
    */
-  protected lastTaskTimestamp: number
+  protected lastTaskTimestamp!: number
   /**
    * Handler Id of the `aliveInterval` worker alive check.
    */
@@ -44,7 +44,7 @@ export abstract class AbstractWorker<
    */
   public constructor (
     type: string,
-    isMain: boolean,
+    protected readonly isMain: boolean,
     fn: (data: Data) => Response,
     protected mainWorker: MainWorker | undefined | null,
     opts: WorkerOptions = {
@@ -63,9 +63,8 @@ export abstract class AbstractWorker<
     this.opts = opts
     this.checkFunctionInput(fn)
     this.checkWorkerOptions(this.opts)
-    this.lastTaskTimestamp = Date.now()
-    // Keep the worker active
-    if (!isMain) {
+    if (!this.isMain) {
+      this.lastTaskTimestamp = Date.now()
       this.aliveInterval = setInterval(
         this.checkAlive.bind(this),
         (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
@@ -95,7 +94,7 @@ export abstract class AbstractWorker<
       this.mainWorker = value.parent
     } else if (value.kill !== undefined) {
       // Here is time to kill this worker, just clearing the interval
-      if (this.aliveInterval != null) clearInterval(this.aliveInterval)
+      this.aliveInterval != null && clearInterval(this.aliveInterval)
       this.emitDestroy()
     }
   }
@@ -179,7 +178,7 @@ export abstract class AbstractWorker<
       const err = this.handleError(e as Error)
       this.sendToMainWorker({ error: err, id: value.id })
     } finally {
-      this.lastTaskTimestamp = Date.now()
+      !this.isMain && (this.lastTaskTimestamp = Date.now())
     }
   }
 
@@ -205,7 +204,7 @@ export abstract class AbstractWorker<
         this.sendToMainWorker({ error: err, id: value.id })
       })
       .finally(() => {
-        this.lastTaskTimestamp = Date.now()
+        !this.isMain && (this.lastTaskTimestamp = Date.now())
       })
       .catch(EMPTY_FUNCTION)
   }