1 import { AsyncResource
} from
'async_hooks'
2 import type { MessageValue
} from
'../utility-types'
3 import type { WorkerOptions
} from
'./worker-options'
5 export abstract class AbstractWorker
<
7 // eslint-disable-next-line @typescript-eslint/no-explicit-any
9 // eslint-disable-next-line @typescript-eslint/no-explicit-any
11 > extends AsyncResource
{
12 protected readonly maxInactiveTime
: number
13 protected readonly async: boolean
14 protected lastTask
: number
15 protected readonly interval
?: NodeJS
.Timeout
19 * @param type The type of async event.
27 fn
: (data
: Data
) => Response
,
28 public readonly opts
: WorkerOptions
= {}
32 this.maxInactiveTime
= this.opts
.maxInactiveTime
?? 1000 * 60
33 this.async = !!this.opts
.async
34 this.lastTask
= Date.now()
35 if (!fn
) throw new Error('Fn parameter is mandatory')
36 // keep the worker active
38 this.interval
= setInterval(
39 this.checkAlive
.bind(this),
40 this.maxInactiveTime
/ 2
42 this.checkAlive
.bind(this)()
46 protected abstract getMainWorker (): MainWorker
48 protected abstract sendToMainWorker (message
: MessageValue
<Response
>): void
50 protected checkAlive (): void {
51 if (Date.now() - this.lastTask
> this.maxInactiveTime
) {
52 this.sendToMainWorker({ kill
: 1 })
56 protected handleError (e
: Error | string): string {
57 return (e
as unknown
) as string
61 fn
: (data
?: Data
) => Response
,
62 value
: MessageValue
<Data
>
65 const res
= fn(value
.data
)
66 this.sendToMainWorker({ data
: res
, id
: value
.id
})
67 this.lastTask
= Date.now()
69 const err
= this.handleError(e
)
70 this.sendToMainWorker({ error
: err
, id
: value
.id
})
71 this.lastTask
= Date.now()
76 fn
: (data
?: Data
) => Promise
<Response
>,
77 value
: MessageValue
<Data
>
81 this.sendToMainWorker({ data
: res
, id
: value
.id
})
82 this.lastTask
= Date.now()
86 const err
= this.handleError(e
)
87 this.sendToMainWorker({ error
: err
, id
: value
.id
})
88 this.lastTask
= Date.now()