1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 import { EventEmitter
} from
'node:events'
4 import { dirname
, extname
, join
, parse
} from
'node:path'
5 import process
, { exit
} from
'node:process'
6 import { fileURLToPath
} from
'node:url'
7 import { isMainThread
} from
'node:worker_threads'
8 import type { Worker
} from
'worker_threads'
10 import chalk from
'chalk'
11 import { type MessageHandler
, availableParallelism
} from
'poolifier'
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'
20 type ChargingStationData
,
21 type ChargingStationOptions
,
22 type ChargingStationWorkerData
,
23 type ChargingStationWorkerEventError
,
24 type ChargingStationWorkerMessage
,
25 type ChargingStationWorkerMessageData
,
26 ChargingStationWorkerMessageEvents
,
30 type StorageConfiguration
,
31 type UIServerConfiguration
,
32 type WorkerConfiguration
33 } from
'../types/index.js'
37 formatDurationMilliSeconds
,
39 handleUncaughtException
,
40 handleUnhandledRejection
,
45 } from
'../utils/index.js'
46 import { type WorkerAbstract
, WorkerFactory
} from
'../worker/index.js'
48 const moduleName
= 'Bootstrap'
52 missingChargingStationsConfiguration
= 1,
53 duplicateChargingStationTemplateUrls
= 2,
54 noChargingStationTemplates
= 3,
55 gracefulShutdownError
= 4
58 interface TemplateChargingStations
{
65 export class Bootstrap
extends EventEmitter
{
66 private static instance
: Bootstrap
| null = null
67 private workerImplementation
?: WorkerAbstract
<ChargingStationWorkerData
>
68 private readonly uiServer
?: AbstractUIServer
69 private storage
?: Storage
70 private readonly templatesChargingStations
: Map
<string, TemplateChargingStations
>
71 private readonly version
: string = version
72 private initializedCounters
: boolean
73 private started
: boolean
74 private starting
: boolean
75 private stopping
: boolean
77 private constructor () {
79 for (const signal
of ['SIGINT', 'SIGQUIT', 'SIGTERM']) {
80 process
.on(signal
, this.gracefulShutdown
.bind(this))
82 // Enable unconditionally for now
83 handleUnhandledRejection()
84 handleUncaughtException()
88 this.templatesChargingStations
= new Map
<string, TemplateChargingStations
>()
89 this.uiServer
= UIServerFactory
.getUIServerImplementation(
90 Configuration
.getConfigurationSection
<UIServerConfiguration
>(ConfigurationSection
.uiServer
)
92 this.initializedCounters
= false
93 this.initializeCounters()
94 Configuration
.configurationChangeCallback
= async () => {
96 await Bootstrap
.getInstance().restart()
101 public static getInstance (): Bootstrap
{
102 if (Bootstrap
.instance
=== null) {
103 Bootstrap
.instance
= new Bootstrap()
105 return Bootstrap
.instance
108 public get
numberOfChargingStationTemplates (): number {
109 return this.templatesChargingStations
.size
112 public get
numberOfConfiguredChargingStations (): number {
113 return [...this.templatesChargingStations
.values()].reduce(
114 (accumulator
, value
) => accumulator
+ value
.configured
,
119 public getLastIndex (templateName
: string): number {
120 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
121 const indexes
= [...this.templatesChargingStations
.get(templateName
)!.indexes
]
123 .sort((a
, b
) => a
- b
)
124 for (let i
= 0; i
< indexes
.length
- 1; i
++) {
125 if (indexes
[i
+ 1] - indexes
[i
] !== 1) {
129 return indexes
[indexes
.length
- 1]
132 public getPerformanceStatistics (): IterableIterator
<Statistics
> | undefined {
133 return this.storage
?.getPerformanceStatistics()
136 private get
numberOfAddedChargingStations (): number {
137 return [...this.templatesChargingStations
.values()].reduce(
138 (accumulator
, value
) => accumulator
+ value
.added
,
143 private get
numberOfStartedChargingStations (): number {
144 return [...this.templatesChargingStations
.values()].reduce(
145 (accumulator
, value
) => accumulator
+ value
.started
,
150 public async start (): Promise
<void> {
152 if (!this.starting
) {
154 this.on(ChargingStationWorkerMessageEvents
.added
, this.workerEventAdded
)
155 this.on(ChargingStationWorkerMessageEvents
.deleted
, this.workerEventDeleted
)
156 this.on(ChargingStationWorkerMessageEvents
.started
, this.workerEventStarted
)
157 this.on(ChargingStationWorkerMessageEvents
.stopped
, this.workerEventStopped
)
158 this.on(ChargingStationWorkerMessageEvents
.updated
, this.workerEventUpdated
)
160 ChargingStationWorkerMessageEvents
.performanceStatistics
,
161 this.workerEventPerformanceStatistics
164 ChargingStationWorkerMessageEvents
.workerElementError
,
165 (eventError
: ChargingStationWorkerEventError
) => {
167 `${this.logPrefix()} ${moduleName}.start: Error occurred while handling '${eventError.event}' event on worker:`,
172 this.initializeCounters()
173 const workerConfiguration
= Configuration
.getConfigurationSection
<WorkerConfiguration
>(
174 ConfigurationSection
.worker
176 this.initializeWorkerImplementation(workerConfiguration
)
177 await this.workerImplementation
?.start()
178 const performanceStorageConfiguration
=
179 Configuration
.getConfigurationSection
<StorageConfiguration
>(
180 ConfigurationSection
.performanceStorage
182 if (performanceStorageConfiguration
.enabled
=== true) {
183 this.storage
= StorageFactory
.getStorage(
184 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
185 performanceStorageConfiguration
.type!,
186 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
187 performanceStorageConfiguration
.uri
!,
190 await this.storage
?.open()
192 Configuration
.getConfigurationSection
<UIServerConfiguration
>(ConfigurationSection
.uiServer
)
193 .enabled
=== true && this.uiServer
?.start()
194 // Start ChargingStation object instance in worker thread
195 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
196 for (const stationTemplateUrl
of Configuration
.getStationTemplateUrls()!) {
199 this.templatesChargingStations
.get(parse(stationTemplateUrl
.file
).name
)?.configured
??
200 stationTemplateUrl
.numberOfStations
201 for (let index
= 1; index
<= nbStations
; index
++) {
202 await this.addChargingStation(index
, stationTemplateUrl
.file
)
207 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
215 `Charging stations simulator ${
217 } started with ${this.numberOfConfiguredChargingStations} configured charging station(s) from ${this.numberOfChargingStationTemplates} charging station template(s) and ${
218 Configuration.workerDynamicPoolInUse() ? `${workerConfiguration.poolMinSize}
/` : ''
219 }${this.workerImplementation?.size}${
220 Configuration.workerPoolInUse() ? `/${workerConfiguration.poolMaxSize}
` : ''
221 } worker(s) concurrently running in '${workerConfiguration.processType}' mode${
222 this.workerImplementation?.maxElementsPerWorker != null
223 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
228 Configuration
.workerDynamicPoolInUse() &&
231 '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'
234 console
.info(chalk
.green('Worker set/pool information:'), this.workerImplementation
?.info
)
236 this.starting
= false
238 console
.error(chalk
.red('Cannot start an already starting charging stations simulator'))
241 console
.error(chalk
.red('Cannot start an already started charging stations simulator'))
245 public async stop (): Promise
<void> {
247 if (!this.stopping
) {
249 await this.uiServer
?.sendInternalRequest(
250 this.uiServer
.buildProtocolRequest(
252 ProcedureName
.STOP_CHARGING_STATION
,
253 Constants
.EMPTY_FROZEN_OBJECT
257 await this.waitChargingStationsStopped()
259 console
.error(chalk
.red('Error while waiting for charging stations to stop: '), error
)
261 await this.workerImplementation
?.stop()
262 delete this.workerImplementation
263 this.removeAllListeners()
264 this.uiServer
?.chargingStations
.clear()
265 await this.storage
?.close()
268 this.stopping
= false
270 console
.error(chalk
.red('Cannot stop an already stopping charging stations simulator'))
273 console
.error(chalk
.red('Cannot stop an already stopped charging stations simulator'))
277 private async restart (): Promise
<void> {
279 Configuration
.getConfigurationSection
<UIServerConfiguration
>(ConfigurationSection
.uiServer
)
280 .enabled
!== true && this.uiServer
?.stop()
281 this.initializedCounters
= false
285 private async waitChargingStationsStopped (): Promise
<string> {
286 return await new Promise
<string>((resolve
, reject
) => {
287 const waitTimeout
= setTimeout(() => {
288 const timeoutMessage
= `Timeout ${formatDurationMilliSeconds(
289 Constants.STOP_CHARGING_STATIONS_TIMEOUT
290 )} reached at stopping charging stations`
291 console
.warn(chalk
.yellow(timeoutMessage
))
292 reject(new Error(timeoutMessage
))
293 }, Constants
.STOP_CHARGING_STATIONS_TIMEOUT
)
294 waitChargingStationEvents(
296 ChargingStationWorkerMessageEvents
.stopped
,
297 this.numberOfStartedChargingStations
300 resolve('Charging stations stopped')
304 clearTimeout(waitTimeout
)
309 private initializeWorkerImplementation (workerConfiguration
: WorkerConfiguration
): void {
313 let elementsPerWorker
: number
314 switch (workerConfiguration
.elementsPerWorker
) {
316 elementsPerWorker
= this.numberOfConfiguredChargingStations
321 this.numberOfConfiguredChargingStations
> availableParallelism()
322 ? Math.round(this.numberOfConfiguredChargingStations
/ (availableParallelism() * 1.5))
326 this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
328 dirname(fileURLToPath(import.meta
.url
)),
329 `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`
331 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
332 workerConfiguration
.processType
!,
334 workerStartDelay
: workerConfiguration
.startDelay
,
335 elementStartDelay
: workerConfiguration
.elementStartDelay
,
336 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
337 poolMaxSize
: workerConfiguration
.poolMaxSize
!,
338 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
339 poolMinSize
: workerConfiguration
.poolMinSize
!,
342 messageHandler
: this.messageHandler
.bind(this) as MessageHandler
<Worker
>,
343 workerOptions
: { resourceLimits
: workerConfiguration
.resourceLimits
}
349 private messageHandler (
350 msg
: ChargingStationWorkerMessage
<ChargingStationWorkerMessageData
>
353 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
361 case ChargingStationWorkerMessageEvents
.added
:
362 this.emit(ChargingStationWorkerMessageEvents
.added
, msg
.data
)
364 case ChargingStationWorkerMessageEvents
.deleted
:
365 this.emit(ChargingStationWorkerMessageEvents
.deleted
, msg
.data
)
367 case ChargingStationWorkerMessageEvents
.started
:
368 this.emit(ChargingStationWorkerMessageEvents
.started
, msg
.data
)
370 case ChargingStationWorkerMessageEvents
.stopped
:
371 this.emit(ChargingStationWorkerMessageEvents
.stopped
, msg
.data
)
373 case ChargingStationWorkerMessageEvents
.updated
:
374 this.emit(ChargingStationWorkerMessageEvents
.updated
, msg
.data
)
376 case ChargingStationWorkerMessageEvents
.performanceStatistics
:
377 this.emit(ChargingStationWorkerMessageEvents
.performanceStatistics
, msg
.data
)
379 case ChargingStationWorkerMessageEvents
.addedWorkerElement
:
380 this.emit(ChargingStationWorkerMessageEvents
.addWorkerElement
, msg
.data
)
382 case ChargingStationWorkerMessageEvents
.workerElementError
:
383 this.emit(ChargingStationWorkerMessageEvents
.workerElementError
, msg
.data
)
387 `Unknown charging station worker event: '${
389 }' received with data: ${JSON.stringify(msg.data, undefined, 2)}`
394 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
402 private readonly workerEventAdded
= (data
: ChargingStationData
): void => {
403 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
)
405 `${this.logPrefix()} ${moduleName}.workerEventAdded: Charging station ${
406 data.stationInfo.chargingStationId
407 } (hashId: ${data.stationInfo.hashId}) added (${
408 this.numberOfAddedChargingStations
409 } added from ${this.numberOfConfiguredChargingStations} configured charging station(s))`
413 private readonly workerEventDeleted
= (data
: ChargingStationData
): void => {
414 this.uiServer
?.chargingStations
.delete(data
.stationInfo
.hashId
)
415 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
416 const templateChargingStations
= this.templatesChargingStations
.get(
417 data
.stationInfo
.templateName
419 --templateChargingStations
.added
420 templateChargingStations
.indexes
.delete(data
.stationInfo
.templateIndex
)
422 `${this.logPrefix()} ${moduleName}.workerEventDeleted: Charging station ${
423 data.stationInfo.chargingStationId
424 } (hashId: ${data.stationInfo.hashId}) deleted (${
425 this.numberOfAddedChargingStations
426 } added from ${this.numberOfConfiguredChargingStations} configured charging station(s))`
430 private readonly workerEventStarted
= (data
: ChargingStationData
): void => {
431 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
)
432 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
433 ++this.templatesChargingStations
.get(data
.stationInfo
.templateName
)!.started
435 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
436 data.stationInfo.chargingStationId
437 } (hashId: ${data.stationInfo.hashId}) started (${
438 this.numberOfStartedChargingStations
439 } started from ${this.numberOfAddedChargingStations} added charging station(s))`
443 private readonly workerEventStopped
= (data
: ChargingStationData
): void => {
444 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
)
445 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
446 --this.templatesChargingStations
.get(data
.stationInfo
.templateName
)!.started
448 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
449 data.stationInfo.chargingStationId
450 } (hashId: ${data.stationInfo.hashId}) stopped (${
451 this.numberOfStartedChargingStations
452 } started from ${this.numberOfAddedChargingStations} added charging station(s))`
456 private readonly workerEventUpdated
= (data
: ChargingStationData
): void => {
457 this.uiServer
?.chargingStations
.set(data
.stationInfo
.hashId
, data
)
460 private readonly workerEventPerformanceStatistics
= (data
: Statistics
): void => {
461 // eslint-disable-next-line @typescript-eslint/unbound-method
462 if (isAsyncFunction(this.storage
?.storePerformanceStatistics
)) {
464 this.storage
.storePerformanceStatistics
as (
465 performanceStatistics
: Statistics
467 )(data
).catch(Constants
.EMPTY_FUNCTION
)
469 (this.storage
?.storePerformanceStatistics
as (performanceStatistics
: Statistics
) => void)(
475 private initializeCounters (): void {
476 if (!this.initializedCounters
) {
477 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
478 const stationTemplateUrls
= Configuration
.getStationTemplateUrls()!
479 if (isNotEmptyArray(stationTemplateUrls
)) {
480 for (const stationTemplateUrl
of stationTemplateUrls
) {
481 const templateName
= parse(stationTemplateUrl
.file
).name
482 this.templatesChargingStations
.set(templateName
, {
483 configured
: stationTemplateUrl
.numberOfStations
,
486 indexes
: new Set
<number>()
488 this.uiServer
?.chargingStationTemplates
.add(templateName
)
490 if (this.templatesChargingStations
.size
!== stationTemplateUrls
.length
) {
493 "'stationTemplateUrls' contains duplicate entries, please check your configuration"
496 exit(exitCodes
.duplicateChargingStationTemplateUrls
)
500 chalk
.red("'stationTemplateUrls' not defined or empty, please check your configuration")
502 exit(exitCodes
.missingChargingStationsConfiguration
)
505 this.numberOfConfiguredChargingStations
=== 0 &&
506 Configuration
.getConfigurationSection
<UIServerConfiguration
>(ConfigurationSection
.uiServer
)
511 "'stationTemplateUrls' has no charging station enabled and UI server is disabled, please check your configuration"
514 exit(exitCodes
.noChargingStationTemplates
)
516 this.initializedCounters
= true
520 public async addChargingStation (
522 stationTemplateFile
: string,
523 options
?: ChargingStationOptions
525 await this.workerImplementation
?.addElement({
528 dirname(fileURLToPath(import.meta
.url
)),
535 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
536 const templateChargingStations
= this.templatesChargingStations
.get(
537 parse(stationTemplateFile
).name
539 ++templateChargingStations
.added
540 templateChargingStations
.indexes
.add(index
)
543 private gracefulShutdown (): void {
546 console
.info(chalk
.green('Graceful shutdown'))
547 this.uiServer
?.stop()
548 this.waitChargingStationsStopped()
550 exit(exitCodes
.succeeded
)
553 exit(exitCodes
.gracefulShutdownError
)
557 console
.error(chalk
.red('Error while shutdowning charging stations simulator: '), error
)
558 exit(exitCodes
.gracefulShutdownError
)
562 private readonly logPrefix
= (): string => {
563 return logPrefix(' Bootstrap |')