Improve JSDoc comments (#130)
[poolifier.git] / src / worker / abstract-worker.ts
CommitLineData
c97c7edb
S
1import { AsyncResource } from 'async_hooks'
2import type { MessageValue } from '../utility-types'
3import type { WorkerOptions } from './worker-options'
4
729c563d
S
5/**
6 * Base class containing some shared logic for all poolifier workers.
7 *
8 * @template MainWorker Type of main worker.
9 * @template Data Type of data this worker receives from pool's execution.
10 * @template Response Type of response the worker sends back to the main worker.
11 */
c97c7edb
S
12export abstract class AbstractWorker<
13 MainWorker,
d3c8a1a8
S
14 Data = unknown,
15 Response = unknown
c97c7edb 16> extends AsyncResource {
729c563d
S
17 /**
18 * The maximum time to keep this worker alive while idle. The pool automatically checks and terminates this worker when the time expires.
19 */
c97c7edb 20 protected readonly maxInactiveTime: number
729c563d
S
21 /**
22 * Whether the worker is working asynchronously or not.
23 */
c97c7edb 24 protected readonly async: boolean
729c563d
S
25 /**
26 * Timestamp of the last task processed by this worker.
27 */
c97c7edb 28 protected lastTask: number
729c563d
S
29 /**
30 * Handler ID of the `interval` alive check.
31 */
c97c7edb
S
32 protected readonly interval?: NodeJS.Timeout
33
34 /**
729c563d 35 * Constructs a new poolifier worker.
c97c7edb
S
36 *
37 * @param type The type of async event.
729c563d
S
38 * @param isMain Whether this is the main worker or not.
39 * @param fn Function processed by the worker when the pool's `execution` function is invoked.
40 * @param opts Options for the worker.
c97c7edb
S
41 */
42 public constructor (
43 type: string,
44 isMain: boolean,
45 fn: (data: Data) => Response,
46 public readonly opts: WorkerOptions = {}
47 ) {
48 super(type)
49
50 this.maxInactiveTime = this.opts.maxInactiveTime ?? 1000 * 60
51 this.async = !!this.opts.async
52 this.lastTask = Date.now()
f2fdaa86 53 if (!fn) throw new Error('fn parameter is mandatory')
c97c7edb
S
54 // keep the worker active
55 if (!isMain) {
56 this.interval = setInterval(
57 this.checkAlive.bind(this),
58 this.maxInactiveTime / 2
59 )
60 this.checkAlive.bind(this)()
61 }
62 }
63
729c563d
S
64 /**
65 * Returns the main worker.
66 */
c97c7edb
S
67 protected abstract getMainWorker (): MainWorker
68
729c563d
S
69 /**
70 * Send a message to the main worker.
71 *
72 * @param message The response message.
73 */
c97c7edb
S
74 protected abstract sendToMainWorker (message: MessageValue<Response>): void
75
729c563d
S
76 /**
77 * Check to see if the worker should be terminated, because its living too long.
78 */
c97c7edb
S
79 protected checkAlive (): void {
80 if (Date.now() - this.lastTask > this.maxInactiveTime) {
81 this.sendToMainWorker({ kill: 1 })
82 }
83 }
84
729c563d
S
85 /**
86 * Handle an error and convert it to a string so it can be sent back to the main worker.
87 *
88 * @param e The error raised by the worker.
89 */
c97c7edb
S
90 protected handleError (e: Error | string): string {
91 return (e as unknown) as string
92 }
93
729c563d
S
94 /**
95 * Run the given function synchronously.
96 *
97 * @param fn Function that will be executed.
98 * @param value Input data for the given function.
99 */
c97c7edb
S
100 protected run (
101 fn: (data?: Data) => Response,
102 value: MessageValue<Data>
103 ): void {
104 try {
105 const res = fn(value.data)
106 this.sendToMainWorker({ data: res, id: value.id })
107 this.lastTask = Date.now()
108 } catch (e) {
109 const err = this.handleError(e)
110 this.sendToMainWorker({ error: err, id: value.id })
111 this.lastTask = Date.now()
112 }
113 }
114
729c563d
S
115 /**
116 * Run the given function asynchronously.
117 *
118 * @param fn Function that will be executed.
119 * @param value Input data for the given function.
120 */
c97c7edb
S
121 protected runAsync (
122 fn: (data?: Data) => Promise<Response>,
123 value: MessageValue<Data>
124 ): void {
125 fn(value.data)
126 .then(res => {
127 this.sendToMainWorker({ data: res, id: value.id })
128 this.lastTask = Date.now()
129 return null
130 })
131 .catch(e => {
132 const err = this.handleError(e)
133 this.sendToMainWorker({ error: err, id: value.id })
134 this.lastTask = Date.now()
135 })
136 }
137}