Apply prettier formating
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerSet.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
4d7227e6 3import { WorkerData, WorkerMessageEvents, WorkerOptions, WorkerSetElement } from '../types/Worker';
c045d9a9 4
6013bc53 5import Utils from '../utils/Utils';
1e924543 6import { Worker } from 'worker_threads';
fd1fdf1b 7import WorkerAbstract from './WorkerAbstract';
7874b0b1 8import { WorkerUtils } from './WorkerUtils';
6013bc53 9
c3ee95af 10export default class WorkerSet extends WorkerAbstract<WorkerData> {
f2bf9948 11 private readonly workerSet: Set<WorkerSetElement>;
4d7227e6 12 private readonly messageHandler: (message: unknown) => void | Promise<void>;
6013bc53
JB
13
14 /**
15 * Create a new `WorkerSet`.
16 *
81797102 17 * @param workerScript
4d7227e6 18 * @param workerOptions
6013bc53 19 */
4d7227e6
JB
20 constructor(workerScript: string, workerOptions?: WorkerOptions) {
21 super(workerScript, workerOptions);
ffd71f2c 22 this.workerSet = new Set<WorkerSetElement>();
e7aeea18
JB
23 this.messageHandler =
24 workerOptions?.messageHandler ??
25 (() => {
26 /* This is intentional */
27 });
6013bc53
JB
28 }
29
30 get size(): number {
ded13d97 31 return this.workerSet.size;
6013bc53
JB
32 }
33
4d7227e6
JB
34 get maxElementsPerWorker(): number | null {
35 return this.workerOptions.elementsPerWorker;
36 }
37
6013bc53
JB
38 /**
39 *
81797102
JB
40 * @param elementData
41 * @returns
6013bc53
JB
42 * @public
43 */
c3ee95af 44 public async addElement(elementData: WorkerData): Promise<void> {
ded13d97 45 if (!this.workerSet) {
e7aeea18 46 throw new Error("Cannot add a WorkerSet element: workers' set does not exist");
6013bc53 47 }
e7aeea18
JB
48 if (
49 this.getLastWorkerSetElement().numberOfWorkerElements >= this.workerOptions.elementsPerWorker
50 ) {
4581acf3 51 await this.startWorker();
6013bc53 52 }
d070d967
JB
53 this.getLastWorker().postMessage({
54 id: WorkerMessageEvents.START_WORKER_ELEMENT,
e7aeea18 55 data: elementData,
d070d967 56 });
c045d9a9 57 this.getLastWorkerSetElement().numberOfWorkerElements++;
d070d967
JB
58 // Start element sequentially to optimize memory at startup
59 if (this.workerOptions.elementStartDelay > 0) {
60 await Utils.sleep(this.workerOptions.elementStartDelay);
61 }
6013bc53
JB
62 }
63
64 /**
65 *
81797102 66 * @returns
6013bc53
JB
67 * @public
68 */
69 public async start(): Promise<void> {
4581acf3 70 await this.startWorker();
6013bc53
JB
71 }
72
ded13d97
JB
73 /**
74 *
81797102 75 * @returns
ded13d97
JB
76 * @public
77 */
78 public async stop(): Promise<void> {
79 for (const workerSetElement of this.workerSet) {
80 await workerSetElement.worker.terminate();
81 }
82 this.workerSet.clear();
83 }
84
6013bc53
JB
85 /**
86 *
6013bc53
JB
87 * @private
88 */
4581acf3 89 private async startWorker(): Promise<void> {
a4624c96 90 const worker = new Worker(this.workerScript);
821c6c82
JB
91 worker.on('message', (msg) => {
92 (async () => {
93 await this.messageHandler(msg);
e7aeea18
JB
94 })().catch(() => {
95 /* This is intentional */
96 });
97 });
98 worker.on('error', () => {
99 /* This is intentional */
821c6c82 100 });
a4624c96 101 worker.on('exit', (code) => {
7874b0b1 102 WorkerUtils.defaultExitHandler(code);
d7a48614 103 this.workerSet.delete(this.getWorkerSetElementByWorker(worker));
6013bc53 104 });
ded13d97 105 this.workerSet.add({ worker, numberOfWorkerElements: 0 });
4581acf3 106 // Start worker sequentially to optimize memory at startup
e7aeea18
JB
107 this.workerOptions.workerStartDelay > 0 &&
108 (await Utils.sleep(this.workerOptions.workerStartDelay));
6013bc53
JB
109 }
110
c045d9a9
JB
111 private getLastWorkerSetElement(): WorkerSetElement {
112 let workerSetElement: WorkerSetElement;
e7aeea18
JB
113 for (workerSetElement of this.workerSet) {
114 /* This is intentional */
115 }
c045d9a9
JB
116 return workerSetElement;
117 }
118
119 private getLastWorker(): Worker {
120 return this.getLastWorkerSetElement().worker;
6013bc53 121 }
1e924543
JB
122
123 private getWorkerSetElementByWorker(worker: Worker): WorkerSetElement {
124 let workerSetElt: WorkerSetElement;
0e7a11e1 125 for (const workerSetElement of this.workerSet) {
81696bd5 126 if (workerSetElement.worker.threadId === worker.threadId) {
1e924543 127 workerSetElt = workerSetElement;
0e7a11e1 128 break;
1e924543 129 }
0e7a11e1 130 }
1e924543
JB
131 return workerSetElt;
132 }
6013bc53 133}