Commit | Line | Data |
---|---|---|
a19b897d | 1 | // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved. |
b4d34251 | 2 | |
66a7748d | 3 | import { EventEmitter } from 'node:events' |
2f989136 | 4 | import { dirname, extname, join, parse } from 'node:path' |
66a7748d JB |
5 | import process, { exit } from 'node:process' |
6 | import { fileURLToPath } from 'node:url' | |
c5ecc04d | 7 | import { isMainThread } from 'node:worker_threads' |
ba9a56a6 | 8 | import type { Worker } from 'worker_threads' |
8114d10e | 9 | |
66a7748d | 10 | import chalk from 'chalk' |
ba9a56a6 | 11 | import { type MessageHandler, availableParallelism } from 'poolifier' |
8114d10e | 12 | |
66a7748d JB |
13 | import { waitChargingStationEvents } from './Helpers.js' |
14 | import type { AbstractUIServer } from './ui-server/AbstractUIServer.js' | |
15 | import { UIServerFactory } from './ui-server/UIServerFactory.js' | |
16 | import { version } from '../../package.json' | |
17 | import { BaseError } from '../exception/index.js' | |
18 | import { type Storage, StorageFactory } from '../performance/index.js' | |
e7aeea18 | 19 | import { |
bbe10d5f | 20 | type ChargingStationData, |
71ac2bd7 | 21 | type ChargingStationOptions, |
bbe10d5f | 22 | type ChargingStationWorkerData, |
244c1396 | 23 | type ChargingStationWorkerEventError, |
bbe10d5f JB |
24 | type ChargingStationWorkerMessage, |
25 | type ChargingStationWorkerMessageData, | |
e7aeea18 | 26 | ChargingStationWorkerMessageEvents, |
5d049829 | 27 | ConfigurationSection, |
e8237645 | 28 | type InternalTemplateStatistics, |
6bd808fd | 29 | ProcedureName, |
e8237645 | 30 | type SimulatorState, |
268a74bb | 31 | type Statistics, |
5d049829 JB |
32 | type StorageConfiguration, |
33 | type UIServerConfiguration, | |
66a7748d JB |
34 | type WorkerConfiguration |
35 | } from '../types/index.js' | |
fa5995d6 JB |
36 | import { |
37 | Configuration, | |
38 | Constants, | |
e8237645 | 39 | buildTemplateStatisticsPayload, |
9bf0ef23 JB |
40 | formatDurationMilliSeconds, |
41 | generateUUID, | |
fa5995d6 JB |
42 | handleUncaughtException, |
43 | handleUnhandledRejection, | |
be0a4d4d | 44 | isAsyncFunction, |
9bf0ef23 | 45 | isNotEmptyArray, |
9bf0ef23 | 46 | logPrefix, |
e375708d | 47 | logger |
66a7748d JB |
48 | } from '../utils/index.js' |
49 | import { type WorkerAbstract, WorkerFactory } from '../worker/index.js' | |
ded13d97 | 50 | |
66a7748d | 51 | const moduleName = 'Bootstrap' |
32de5a57 | 52 | |
a307349b | 53 | enum exitCodes { |
a51a4ead | 54 | succeeded = 0, |
a307349b | 55 | missingChargingStationsConfiguration = 1, |
2f989136 JB |
56 | duplicateChargingStationTemplateUrls = 2, |
57 | noChargingStationTemplates = 3, | |
58 | gracefulShutdownError = 4 | |
a307349b | 59 | } |
e4cb2c14 | 60 | |
f130b8e6 | 61 | export class Bootstrap extends EventEmitter { |
66a7748d | 62 | private static instance: Bootstrap | null = null |
66a7748d | 63 | private workerImplementation?: WorkerAbstract<ChargingStationWorkerData> |
a1cfaa16 | 64 | private readonly uiServer: AbstractUIServer |
66a7748d | 65 | private storage?: Storage |
e8237645 | 66 | private readonly templateStatistics: Map<string, InternalTemplateStatistics> |
66a7748d JB |
67 | private readonly version: string = version |
68 | private initializedCounters: boolean | |
69 | private started: boolean | |
70 | private starting: boolean | |
71 | private stopping: boolean | |
a1cfaa16 | 72 | private uiServerStarted: boolean |
ded13d97 | 73 | |
66a7748d JB |
74 | private constructor () { |
75 | super() | |
6bd808fd | 76 | for (const signal of ['SIGINT', 'SIGQUIT', 'SIGTERM']) { |
66a7748d | 77 | process.on(signal, this.gracefulShutdown.bind(this)) |
6bd808fd | 78 | } |
4724a293 | 79 | // Enable unconditionally for now |
66a7748d JB |
80 | handleUnhandledRejection() |
81 | handleUncaughtException() | |
82 | this.started = false | |
83 | this.starting = false | |
84 | this.stopping = false | |
a1cfaa16 | 85 | this.uiServerStarted = false |
36adaf06 | 86 | this.uiServer = UIServerFactory.getUIServerImplementation( |
66a7748d JB |
87 | Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer) |
88 | ) | |
e8237645 | 89 | this.templateStatistics = new Map<string, InternalTemplateStatistics>() |
42e341c4 JB |
90 | this.initializedCounters = false |
91 | this.initializeCounters() | |
66a7748d | 92 | Configuration.configurationChangeCallback = async () => { |
c5ecc04d JB |
93 | if (isMainThread) { |
94 | await Bootstrap.getInstance().restart() | |
95 | } | |
66a7748d | 96 | } |
ded13d97 JB |
97 | } |
98 | ||
66a7748d | 99 | public static getInstance (): Bootstrap { |
1ca780f9 | 100 | if (Bootstrap.instance === null) { |
66a7748d | 101 | Bootstrap.instance = new Bootstrap() |
ded13d97 | 102 | } |
66a7748d | 103 | return Bootstrap.instance |
ded13d97 JB |
104 | } |
105 | ||
2f989136 | 106 | public get numberOfChargingStationTemplates (): number { |
e8237645 | 107 | return this.templateStatistics.size |
2f989136 JB |
108 | } |
109 | ||
110 | public get numberOfConfiguredChargingStations (): number { | |
e8237645 | 111 | return [...this.templateStatistics.values()].reduce( |
2f989136 JB |
112 | (accumulator, value) => accumulator + value.configured, |
113 | 0 | |
114 | ) | |
115 | } | |
116 | ||
e8237645 | 117 | public getState (): SimulatorState { |
240fa4da | 118 | return { |
e8237645 JB |
119 | version: this.version, |
120 | started: this.started, | |
121 | templateStatistics: buildTemplateStatisticsPayload(this.templateStatistics) | |
240fa4da JB |
122 | } |
123 | } | |
124 | ||
c5ecc04d | 125 | public getLastIndex (templateName: string): number { |
e375708d | 126 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
e8237645 | 127 | const indexes = [...this.templateStatistics.get(templateName)!.indexes] |
e375708d JB |
128 | .concat(0) |
129 | .sort((a, b) => a - b) | |
130 | for (let i = 0; i < indexes.length - 1; i++) { | |
131 | if (indexes[i + 1] - indexes[i] !== 1) { | |
132 | return indexes[i] | |
133 | } | |
134 | } | |
135 | return indexes[indexes.length - 1] | |
c5ecc04d JB |
136 | } |
137 | ||
a66bbcfe JB |
138 | public getPerformanceStatistics (): IterableIterator<Statistics> | undefined { |
139 | return this.storage?.getPerformanceStatistics() | |
140 | } | |
141 | ||
244c1396 | 142 | private get numberOfAddedChargingStations (): number { |
e8237645 | 143 | return [...this.templateStatistics.values()].reduce( |
244c1396 JB |
144 | (accumulator, value) => accumulator + value.added, |
145 | 0 | |
146 | ) | |
147 | } | |
148 | ||
2f989136 | 149 | private get numberOfStartedChargingStations (): number { |
e8237645 | 150 | return [...this.templateStatistics.values()].reduce( |
2f989136 JB |
151 | (accumulator, value) => accumulator + value.started, |
152 | 0 | |
153 | ) | |
154 | } | |
155 | ||
66a7748d JB |
156 | public async start (): Promise<void> { |
157 | if (!this.started) { | |
158 | if (!this.starting) { | |
159 | this.starting = true | |
244c1396 | 160 | this.on(ChargingStationWorkerMessageEvents.added, this.workerEventAdded) |
09e5a7a8 | 161 | this.on(ChargingStationWorkerMessageEvents.deleted, this.workerEventDeleted) |
66a7748d JB |
162 | this.on(ChargingStationWorkerMessageEvents.started, this.workerEventStarted) |
163 | this.on(ChargingStationWorkerMessageEvents.stopped, this.workerEventStopped) | |
164 | this.on(ChargingStationWorkerMessageEvents.updated, this.workerEventUpdated) | |
4354af5a JB |
165 | this.on( |
166 | ChargingStationWorkerMessageEvents.performanceStatistics, | |
66a7748d JB |
167 | this.workerEventPerformanceStatistics |
168 | ) | |
44fccdf0 JB |
169 | this.on( |
170 | ChargingStationWorkerMessageEvents.workerElementError, | |
887a125e | 171 | (eventError: ChargingStationWorkerEventError) => { |
44fccdf0 | 172 | logger.error( |
3ab32759 | 173 | `${this.logPrefix()} ${moduleName}.start: Error occurred while handling '${eventError.event}' event on worker:`, |
887a125e | 174 | eventError |
44fccdf0 JB |
175 | ) |
176 | } | |
177 | ) | |
66a7748d | 178 | this.initializeCounters() |
5b373a23 | 179 | const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>( |
66a7748d JB |
180 | ConfigurationSection.worker |
181 | ) | |
182 | this.initializeWorkerImplementation(workerConfiguration) | |
183 | await this.workerImplementation?.start() | |
6d2b7d01 JB |
184 | const performanceStorageConfiguration = |
185 | Configuration.getConfigurationSection<StorageConfiguration>( | |
66a7748d JB |
186 | ConfigurationSection.performanceStorage |
187 | ) | |
6d2b7d01 JB |
188 | if (performanceStorageConfiguration.enabled === true) { |
189 | this.storage = StorageFactory.getStorage( | |
66a7748d | 190 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
6d2b7d01 | 191 | performanceStorageConfiguration.type!, |
66a7748d | 192 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
6d2b7d01 | 193 | performanceStorageConfiguration.uri!, |
66a7748d JB |
194 | this.logPrefix() |
195 | ) | |
196 | await this.storage?.open() | |
6d2b7d01 | 197 | } |
a1cfaa16 JB |
198 | if ( |
199 | !this.uiServerStarted && | |
200 | Configuration.getConfigurationSection<UIServerConfiguration>( | |
201 | ConfigurationSection.uiServer | |
202 | ).enabled === true | |
203 | ) { | |
204 | this.uiServer.start() | |
205 | this.uiServerStarted = true | |
206 | } | |
82e9c15a | 207 | // Start ChargingStation object instance in worker thread |
66a7748d | 208 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
e1d9a0f4 | 209 | for (const stationTemplateUrl of Configuration.getStationTemplateUrls()!) { |
82e9c15a | 210 | try { |
2f989136 | 211 | const nbStations = |
e8237645 | 212 | this.templateStatistics.get(parse(stationTemplateUrl.file).name)?.configured ?? |
afbb8202 | 213 | stationTemplateUrl.numberOfStations |
82e9c15a | 214 | for (let index = 1; index <= nbStations; index++) { |
c5ecc04d | 215 | await this.addChargingStation(index, stationTemplateUrl.file) |
82e9c15a JB |
216 | } |
217 | } catch (error) { | |
218 | console.error( | |
219 | chalk.red( | |
66a7748d | 220 | `Error at starting charging station with template file ${stationTemplateUrl.file}: ` |
82e9c15a | 221 | ), |
66a7748d JB |
222 | error |
223 | ) | |
ded13d97 | 224 | } |
ded13d97 | 225 | } |
82e9c15a JB |
226 | console.info( |
227 | chalk.green( | |
228 | `Charging stations simulator ${ | |
229 | this.version | |
c5ecc04d | 230 | } started with ${this.numberOfConfiguredChargingStations} configured charging station(s) from ${this.numberOfChargingStationTemplates} charging station template(s) and ${ |
2f989136 | 231 | Configuration.workerDynamicPoolInUse() ? `${workerConfiguration.poolMinSize}/` : '' |
82e9c15a | 232 | }${this.workerImplementation?.size}${ |
2f989136 | 233 | Configuration.workerPoolInUse() ? `/${workerConfiguration.poolMaxSize}` : '' |
5b373a23 | 234 | } worker(s) concurrently running in '${workerConfiguration.processType}' mode${ |
401fa922 | 235 | this.workerImplementation?.maxElementsPerWorker != null |
5199f9fd | 236 | ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` |
82e9c15a | 237 | : '' |
66a7748d JB |
238 | }` |
239 | ) | |
240 | ) | |
56e2e1ab JB |
241 | Configuration.workerDynamicPoolInUse() && |
242 | console.warn( | |
243 | chalk.yellow( | |
66a7748d JB |
244 | 'Charging stations simulator is using dynamic pool mode. This is an experimental feature with known issues.\nPlease consider using fixed pool or worker set mode instead' |
245 | ) | |
246 | ) | |
247 | console.info(chalk.green('Worker set/pool information:'), this.workerImplementation?.info) | |
248 | this.started = true | |
249 | this.starting = false | |
82e9c15a | 250 | } else { |
66a7748d | 251 | console.error(chalk.red('Cannot start an already starting charging stations simulator')) |
ded13d97 | 252 | } |
b322b8b4 | 253 | } else { |
66a7748d | 254 | console.error(chalk.red('Cannot start an already started charging stations simulator')) |
ded13d97 JB |
255 | } |
256 | } | |
257 | ||
c5ecc04d | 258 | public async stop (): Promise<void> { |
66a7748d JB |
259 | if (this.started) { |
260 | if (!this.stopping) { | |
261 | this.stopping = true | |
a1cfaa16 | 262 | await this.uiServer.sendInternalRequest( |
c5ecc04d JB |
263 | this.uiServer.buildProtocolRequest( |
264 | generateUUID(), | |
265 | ProcedureName.STOP_CHARGING_STATION, | |
266 | Constants.EMPTY_FROZEN_OBJECT | |
66a7748d | 267 | ) |
c5ecc04d JB |
268 | ) |
269 | try { | |
270 | await this.waitChargingStationsStopped() | |
271 | } catch (error) { | |
272 | console.error(chalk.red('Error while waiting for charging stations to stop: '), error) | |
ab7a96fa | 273 | } |
66a7748d JB |
274 | await this.workerImplementation?.stop() |
275 | delete this.workerImplementation | |
276 | this.removeAllListeners() | |
a1cfaa16 | 277 | this.uiServer.clearCaches() |
9d289c63 | 278 | this.initializedCounters = false |
66a7748d JB |
279 | await this.storage?.close() |
280 | delete this.storage | |
66a7748d JB |
281 | this.started = false |
282 | this.stopping = false | |
82e9c15a | 283 | } else { |
66a7748d | 284 | console.error(chalk.red('Cannot stop an already stopping charging stations simulator')) |
82e9c15a | 285 | } |
b322b8b4 | 286 | } else { |
66a7748d | 287 | console.error(chalk.red('Cannot stop an already stopped charging stations simulator')) |
ded13d97 | 288 | } |
ded13d97 JB |
289 | } |
290 | ||
c5ecc04d JB |
291 | private async restart (): Promise<void> { |
292 | await this.stop() | |
a1cfaa16 JB |
293 | if ( |
294 | this.uiServerStarted && | |
295 | Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer) | |
296 | .enabled !== true | |
297 | ) { | |
298 | this.uiServer.stop() | |
299 | this.uiServerStarted = false | |
300 | } | |
66a7748d | 301 | await this.start() |
ded13d97 JB |
302 | } |
303 | ||
66a7748d JB |
304 | private async waitChargingStationsStopped (): Promise<string> { |
305 | return await new Promise<string>((resolve, reject) => { | |
5b2721db | 306 | const waitTimeout = setTimeout(() => { |
a01134ed | 307 | const timeoutMessage = `Timeout ${formatDurationMilliSeconds( |
66a7748d JB |
308 | Constants.STOP_CHARGING_STATIONS_TIMEOUT |
309 | )} reached at stopping charging stations` | |
a01134ed JB |
310 | console.warn(chalk.yellow(timeoutMessage)) |
311 | reject(new Error(timeoutMessage)) | |
66a7748d | 312 | }, Constants.STOP_CHARGING_STATIONS_TIMEOUT) |
36adaf06 JB |
313 | waitChargingStationEvents( |
314 | this, | |
315 | ChargingStationWorkerMessageEvents.stopped, | |
a01134ed | 316 | this.numberOfStartedChargingStations |
5b2721db JB |
317 | ) |
318 | .then(() => { | |
66a7748d | 319 | resolve('Charging stations stopped') |
5b2721db | 320 | }) |
b7ee97c1 | 321 | .catch(reject) |
5b2721db | 322 | .finally(() => { |
66a7748d JB |
323 | clearTimeout(waitTimeout) |
324 | }) | |
325 | }) | |
36adaf06 JB |
326 | } |
327 | ||
66a7748d | 328 | private initializeWorkerImplementation (workerConfiguration: WorkerConfiguration): void { |
c5ecc04d JB |
329 | if (!isMainThread) { |
330 | return | |
331 | } | |
1feac591 | 332 | let elementsPerWorker: number |
5199f9fd | 333 | switch (workerConfiguration.elementsPerWorker) { |
1feac591 JB |
334 | case 'all': |
335 | elementsPerWorker = this.numberOfConfiguredChargingStations | |
336 | break | |
487f0dfd | 337 | case 'auto': |
1feac591 | 338 | default: |
487f0dfd | 339 | elementsPerWorker = |
2f989136 JB |
340 | this.numberOfConfiguredChargingStations > availableParallelism() |
341 | ? Math.round(this.numberOfConfiguredChargingStations / (availableParallelism() * 1.5)) | |
66a7748d JB |
342 | : 1 |
343 | break | |
8603c1ca | 344 | } |
6d2b7d01 JB |
345 | this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>( |
346 | join( | |
347 | dirname(fileURLToPath(import.meta.url)), | |
66a7748d | 348 | `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}` |
6d2b7d01 | 349 | ), |
66a7748d | 350 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
6d2b7d01 JB |
351 | workerConfiguration.processType!, |
352 | { | |
353 | workerStartDelay: workerConfiguration.startDelay, | |
354 | elementStartDelay: workerConfiguration.elementStartDelay, | |
66a7748d | 355 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
6d2b7d01 | 356 | poolMaxSize: workerConfiguration.poolMaxSize!, |
66a7748d | 357 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
6d2b7d01 | 358 | poolMinSize: workerConfiguration.poolMinSize!, |
1feac591 | 359 | elementsPerWorker, |
6d2b7d01 | 360 | poolOptions: { |
ba9a56a6 | 361 | messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>, |
66a7748d JB |
362 | workerOptions: { resourceLimits: workerConfiguration.resourceLimits } |
363 | } | |
364 | } | |
365 | ) | |
ded13d97 | 366 | } |
81797102 | 367 | |
66a7748d JB |
368 | private messageHandler ( |
369 | msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData> | |
32de5a57 LM |
370 | ): void { |
371 | // logger.debug( | |
372 | // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify( | |
373 | // msg, | |
4ed03b6e | 374 | // undefined, |
66a7748d JB |
375 | // 2 |
376 | // )}` | |
377 | // ) | |
32de5a57 | 378 | try { |
8cc482a9 | 379 | switch (msg.event) { |
244c1396 | 380 | case ChargingStationWorkerMessageEvents.added: |
44fccdf0 | 381 | this.emit(ChargingStationWorkerMessageEvents.added, msg.data) |
244c1396 | 382 | break |
09e5a7a8 JB |
383 | case ChargingStationWorkerMessageEvents.deleted: |
384 | this.emit(ChargingStationWorkerMessageEvents.deleted, msg.data) | |
385 | break | |
721646e9 | 386 | case ChargingStationWorkerMessageEvents.started: |
44fccdf0 | 387 | this.emit(ChargingStationWorkerMessageEvents.started, msg.data) |
66a7748d | 388 | break |
721646e9 | 389 | case ChargingStationWorkerMessageEvents.stopped: |
44fccdf0 | 390 | this.emit(ChargingStationWorkerMessageEvents.stopped, msg.data) |
66a7748d | 391 | break |
721646e9 | 392 | case ChargingStationWorkerMessageEvents.updated: |
44fccdf0 | 393 | this.emit(ChargingStationWorkerMessageEvents.updated, msg.data) |
66a7748d | 394 | break |
721646e9 | 395 | case ChargingStationWorkerMessageEvents.performanceStatistics: |
44fccdf0 | 396 | this.emit(ChargingStationWorkerMessageEvents.performanceStatistics, msg.data) |
66a7748d | 397 | break |
e1a3f3c1 | 398 | case ChargingStationWorkerMessageEvents.addedWorkerElement: |
a492245c | 399 | this.emit(ChargingStationWorkerMessageEvents.addWorkerElement, msg.data) |
e1a3f3c1 | 400 | break |
244c1396 | 401 | case ChargingStationWorkerMessageEvents.workerElementError: |
244c1396 | 402 | this.emit(ChargingStationWorkerMessageEvents.workerElementError, msg.data) |
66a7748d | 403 | break |
32de5a57 LM |
404 | default: |
405 | throw new BaseError( | |
f93dda6a JB |
406 | `Unknown charging station worker event: '${ |
407 | msg.event | |
66a7748d JB |
408 | }' received with data: ${JSON.stringify(msg.data, undefined, 2)}` |
409 | ) | |
32de5a57 LM |
410 | } |
411 | } catch (error) { | |
412 | logger.error( | |
413 | `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${ | |
8cc482a9 | 414 | msg.event |
32de5a57 | 415 | }' event:`, |
66a7748d JB |
416 | error |
417 | ) | |
32de5a57 LM |
418 | } |
419 | } | |
420 | ||
244c1396 | 421 | private readonly workerEventAdded = (data: ChargingStationData): void => { |
a1cfaa16 | 422 | this.uiServer.chargingStations.set(data.stationInfo.hashId, data) |
244c1396 JB |
423 | logger.info( |
424 | `${this.logPrefix()} ${moduleName}.workerEventAdded: Charging station ${ | |
425 | data.stationInfo.chargingStationId | |
426 | } (hashId: ${data.stationInfo.hashId}) added (${ | |
427 | this.numberOfAddedChargingStations | |
428 | } added from ${this.numberOfConfiguredChargingStations} configured charging station(s))` | |
09e5a7a8 JB |
429 | ) |
430 | } | |
431 | ||
432 | private readonly workerEventDeleted = (data: ChargingStationData): void => { | |
a1cfaa16 | 433 | this.uiServer.chargingStations.delete(data.stationInfo.hashId) |
09e5a7a8 | 434 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
e8237645 JB |
435 | const templateStatistics = this.templateStatistics.get(data.stationInfo.templateName)! |
436 | --templateStatistics.added | |
437 | templateStatistics.indexes.delete(data.stationInfo.templateIndex) | |
09e5a7a8 JB |
438 | logger.info( |
439 | `${this.logPrefix()} ${moduleName}.workerEventDeleted: Charging station ${ | |
440 | data.stationInfo.chargingStationId | |
441 | } (hashId: ${data.stationInfo.hashId}) deleted (${ | |
442 | this.numberOfAddedChargingStations | |
443 | } added from ${this.numberOfConfiguredChargingStations} configured charging station(s))` | |
244c1396 JB |
444 | ) |
445 | } | |
446 | ||
66a7748d | 447 | private readonly workerEventStarted = (data: ChargingStationData): void => { |
a1cfaa16 | 448 | this.uiServer.chargingStations.set(data.stationInfo.hashId, data) |
2f989136 | 449 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
e8237645 | 450 | ++this.templateStatistics.get(data.stationInfo.templateName)!.started |
56eb297e | 451 | logger.info( |
e6159ce8 | 452 | `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${ |
56eb297e | 453 | data.stationInfo.chargingStationId |
e6159ce8 | 454 | } (hashId: ${data.stationInfo.hashId}) started (${ |
56eb297e | 455 | this.numberOfStartedChargingStations |
244c1396 | 456 | } started from ${this.numberOfAddedChargingStations} added charging station(s))` |
66a7748d JB |
457 | ) |
458 | } | |
32de5a57 | 459 | |
66a7748d | 460 | private readonly workerEventStopped = (data: ChargingStationData): void => { |
a1cfaa16 | 461 | this.uiServer.chargingStations.set(data.stationInfo.hashId, data) |
2f989136 | 462 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
e8237645 | 463 | --this.templateStatistics.get(data.stationInfo.templateName)!.started |
56eb297e | 464 | logger.info( |
e6159ce8 | 465 | `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${ |
56eb297e | 466 | data.stationInfo.chargingStationId |
e6159ce8 | 467 | } (hashId: ${data.stationInfo.hashId}) stopped (${ |
56eb297e | 468 | this.numberOfStartedChargingStations |
244c1396 | 469 | } started from ${this.numberOfAddedChargingStations} added charging station(s))` |
66a7748d JB |
470 | ) |
471 | } | |
32de5a57 | 472 | |
66a7748d | 473 | private readonly workerEventUpdated = (data: ChargingStationData): void => { |
a1cfaa16 | 474 | this.uiServer.chargingStations.set(data.stationInfo.hashId, data) |
66a7748d | 475 | } |
32de5a57 | 476 | |
66a7748d | 477 | private readonly workerEventPerformanceStatistics = (data: Statistics): void => { |
be0a4d4d JB |
478 | // eslint-disable-next-line @typescript-eslint/unbound-method |
479 | if (isAsyncFunction(this.storage?.storePerformanceStatistics)) { | |
480 | ( | |
481 | this.storage.storePerformanceStatistics as ( | |
482 | performanceStatistics: Statistics | |
483 | ) => Promise<void> | |
484 | )(data).catch(Constants.EMPTY_FUNCTION) | |
485 | } else { | |
486 | (this.storage?.storePerformanceStatistics as (performanceStatistics: Statistics) => void)( | |
487 | data | |
488 | ) | |
489 | } | |
66a7748d | 490 | } |
32de5a57 | 491 | |
66a7748d JB |
492 | private initializeCounters (): void { |
493 | if (!this.initializedCounters) { | |
66a7748d JB |
494 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
495 | const stationTemplateUrls = Configuration.getStationTemplateUrls()! | |
9bf0ef23 | 496 | if (isNotEmptyArray(stationTemplateUrls)) { |
7436ee0d | 497 | for (const stationTemplateUrl of stationTemplateUrls) { |
8c7d214a JB |
498 | const templateName = join( |
499 | parse(stationTemplateUrl.file).dir, | |
500 | parse(stationTemplateUrl.file).name | |
501 | ) | |
e8237645 | 502 | this.templateStatistics.set(templateName, { |
2f989136 | 503 | configured: stationTemplateUrl.numberOfStations, |
244c1396 | 504 | added: 0, |
c5ecc04d | 505 | started: 0, |
e375708d | 506 | indexes: new Set<number>() |
2f989136 | 507 | }) |
a1cfaa16 | 508 | this.uiServer.chargingStationTemplates.add(templateName) |
2f989136 | 509 | } |
e8237645 | 510 | if (this.templateStatistics.size !== stationTemplateUrls.length) { |
2f989136 JB |
511 | console.error( |
512 | chalk.red( | |
513 | "'stationTemplateUrls' contains duplicate entries, please check your configuration" | |
514 | ) | |
515 | ) | |
516 | exit(exitCodes.duplicateChargingStationTemplateUrls) | |
7436ee0d | 517 | } |
a596d200 | 518 | } else { |
2f989136 JB |
519 | console.error( |
520 | chalk.red("'stationTemplateUrls' not defined or empty, please check your configuration") | |
66a7748d JB |
521 | ) |
522 | exit(exitCodes.missingChargingStationsConfiguration) | |
a596d200 | 523 | } |
c5ecc04d JB |
524 | if ( |
525 | this.numberOfConfiguredChargingStations === 0 && | |
526 | Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer) | |
baf34a77 | 527 | .enabled !== true |
c5ecc04d | 528 | ) { |
2f989136 JB |
529 | console.error( |
530 | chalk.red( | |
c5ecc04d | 531 | "'stationTemplateUrls' has no charging station enabled and UI server is disabled, please check your configuration" |
2f989136 JB |
532 | ) |
533 | ) | |
66a7748d | 534 | exit(exitCodes.noChargingStationTemplates) |
a596d200 | 535 | } |
66a7748d | 536 | this.initializedCounters = true |
846d2851 | 537 | } |
7c72977b JB |
538 | } |
539 | ||
71ac2bd7 JB |
540 | public async addChargingStation ( |
541 | index: number, | |
542 | stationTemplateFile: string, | |
543 | options?: ChargingStationOptions | |
544 | ): Promise<void> { | |
6ed3c845 | 545 | await this.workerImplementation?.addElement({ |
717c1e56 | 546 | index, |
d972af76 JB |
547 | templateFile: join( |
548 | dirname(fileURLToPath(import.meta.url)), | |
e7aeea18 JB |
549 | 'assets', |
550 | 'station-templates', | |
c5ecc04d | 551 | stationTemplateFile |
71ac2bd7 JB |
552 | ), |
553 | options | |
66a7748d | 554 | }) |
c5ecc04d | 555 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
e8237645 JB |
556 | const templateStatistics = this.templateStatistics.get(parse(stationTemplateFile).name)! |
557 | ++templateStatistics.added | |
558 | templateStatistics.indexes.add(index) | |
717c1e56 JB |
559 | } |
560 | ||
66a7748d | 561 | private gracefulShutdown (): void { |
f130b8e6 JB |
562 | this.stop() |
563 | .then(() => { | |
5199f9fd | 564 | console.info(chalk.green('Graceful shutdown')) |
a1cfaa16 JB |
565 | this.uiServer.stop() |
566 | this.uiServerStarted = false | |
36adaf06 JB |
567 | this.waitChargingStationsStopped() |
568 | .then(() => { | |
66a7748d | 569 | exit(exitCodes.succeeded) |
36adaf06 | 570 | }) |
5b2721db | 571 | .catch(() => { |
66a7748d JB |
572 | exit(exitCodes.gracefulShutdownError) |
573 | }) | |
f130b8e6 | 574 | }) |
a974c8e4 | 575 | .catch(error => { |
66a7748d JB |
576 | console.error(chalk.red('Error while shutdowning charging stations simulator: '), error) |
577 | exit(exitCodes.gracefulShutdownError) | |
578 | }) | |
36adaf06 | 579 | } |
f130b8e6 | 580 | |
66a7748d JB |
581 | private readonly logPrefix = (): string => { |
582 | return logPrefix(' Bootstrap |') | |
583 | } | |
ded13d97 | 584 | } |