Only allow primitive JSON for transfer between worker and main worker (#128)
[poolifier.git] / src / worker / thread-worker.ts
CommitLineData
fa699c42 1import { isMainThread, parentPort } from 'worker_threads'
d3c8a1a8 2import type { JSONValue, MessageValue } from '../utility-types'
c97c7edb 3import { AbstractWorker } from './abstract-worker'
325f50bc 4import type { WorkerOptions } from './worker-options'
a32e02ba 5
a32e02ba 6/**
4ade5f1f
S
7 * An example worker that will be always alive, you just need to **extend** this class if you want a static pool.
8 *
9 * When this worker is inactive for more than 1 minute, it will send this info to the main thread,
10 * if you are using DynamicThreadPool, the workers created after will be killed, the min num of thread will be guaranteed.
11 *
12 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
a32e02ba 13 * @since 0.0.1
14 */
d3c8a1a8
S
15export class ThreadWorker<
16 Data extends JSONValue = JSONValue,
17 Response extends JSONValue = JSONValue
18> extends AbstractWorker<MessagePort, Data, Response> {
ee99693b 19 protected parent?: MessagePort
4ade5f1f 20
c97c7edb
S
21 public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) {
22 super('worker-thread-pool:pioardi', isMainThread, fn, opts)
4ade5f1f 23
325f50bc
S
24 parentPort?.on('message', (value: MessageValue<Data>) => {
25 if (value?.data && value.id) {
26 // here you will receive messages
c97c7edb 27 // console.log('This is the main worker ' + isMain)
325f50bc
S
28 if (this.async) {
29 this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
30 } else {
31 this.runInAsyncScope(this.run.bind(this), this, fn, value)
7784f548 32 }
325f50bc
S
33 } else if (value.parent) {
34 // save the port to communicate with the main thread
35 // this will be received once
36 this.parent = value.parent
37 } else if (value.kill) {
c97c7edb 38 // here is time to kill this worker, just clearing the interval
325f50bc
S
39 if (this.interval) clearInterval(this.interval)
40 this.emitDestroy()
a32e02ba 41 }
325f50bc 42 })
a32e02ba 43 }
44
c97c7edb
S
45 protected getMainWorker (): MessagePort {
46 if (!this.parent) {
47 throw new Error('Parent was not set')
106744f7 48 }
c97c7edb 49 return this.parent
106744f7 50 }
7784f548 51
c97c7edb
S
52 protected sendToMainWorker (message: MessageValue<Response>): void {
53 this.getMainWorker().postMessage(message)
7784f548 54 }
a32e02ba 55}