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
<
9 > extends AsyncResource
{
10 protected readonly maxInactiveTime
: number
11 protected readonly async: boolean
12 protected lastTask
: number
13 protected readonly interval
?: NodeJS
.Timeout
17 * @param type The type of async event.
25 fn
: (data
: Data
) => Response
,
26 public readonly opts
: WorkerOptions
= {}
30 this.maxInactiveTime
= this.opts
.maxInactiveTime
?? 1000 * 60
31 this.async = !!this.opts
.async
32 this.lastTask
= Date.now()
33 if (!fn
) throw new Error('Fn parameter is mandatory')
34 // keep the worker active
36 this.interval
= setInterval(
37 this.checkAlive
.bind(this),
38 this.maxInactiveTime
/ 2
40 this.checkAlive
.bind(this)()
44 protected abstract getMainWorker (): MainWorker
46 protected abstract sendToMainWorker (message
: MessageValue
<Response
>): void
48 protected checkAlive (): void {
49 if (Date.now() - this.lastTask
> this.maxInactiveTime
) {
50 this.sendToMainWorker({ kill
: 1 })
54 protected handleError (e
: Error | string): string {
55 return (e
as unknown
) as string
59 fn
: (data
?: Data
) => Response
,
60 value
: MessageValue
<Data
>
63 const res
= fn(value
.data
)
64 this.sendToMainWorker({ data
: res
, id
: value
.id
})
65 this.lastTask
= Date.now()
67 const err
= this.handleError(e
)
68 this.sendToMainWorker({ error
: err
, id
: value
.id
})
69 this.lastTask
= Date.now()
74 fn
: (data
?: Data
) => Promise
<Response
>,
75 value
: MessageValue
<Data
>
79 this.sendToMainWorker({ data
: res
, id
: value
.id
})
80 this.lastTask
= Date.now()
84 const err
= this.handleError(e
)
85 this.sendToMainWorker({ error
: err
, id
: value
.id
})
86 this.lastTask
= Date.now()