| 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
| 2 | |
| 3 | import path from 'node:path'; |
| 4 | import { fileURLToPath } from 'node:url'; |
| 5 | import { type Worker, isMainThread } from 'node:worker_threads'; |
| 6 | |
| 7 | import chalk from 'chalk'; |
| 8 | |
| 9 | import type { AbstractUIServer } from './ui-server/AbstractUIServer'; |
| 10 | import { UIServerFactory } from './ui-server/UIServerFactory'; |
| 11 | import packageJson from '../../package.json' assert { type: 'json' }; |
| 12 | import { BaseError } from '../exception'; |
| 13 | import { type Storage, StorageFactory } from '../performance'; |
| 14 | import { |
| 15 | type ChargingStationData, |
| 16 | type ChargingStationWorkerData, |
| 17 | type ChargingStationWorkerMessage, |
| 18 | type ChargingStationWorkerMessageData, |
| 19 | ChargingStationWorkerMessageEvents, |
| 20 | type StationTemplateUrl, |
| 21 | type Statistics, |
| 22 | } from '../types'; |
| 23 | import { Configuration, ErrorUtils, Utils, logger } from '../utils'; |
| 24 | import { type MessageHandler, type WorkerAbstract, WorkerFactory } from '../worker'; |
| 25 | |
| 26 | const moduleName = 'Bootstrap'; |
| 27 | |
| 28 | enum exitCodes { |
| 29 | missingChargingStationsConfiguration = 1, |
| 30 | noChargingStationTemplates = 2, |
| 31 | } |
| 32 | |
| 33 | export class Bootstrap { |
| 34 | private static instance: Bootstrap | null = null; |
| 35 | public numberOfChargingStations!: number; |
| 36 | public numberOfChargingStationTemplates!: number; |
| 37 | private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null; |
| 38 | private readonly uiServer!: AbstractUIServer | null; |
| 39 | private readonly storage!: Storage; |
| 40 | private numberOfStartedChargingStations!: number; |
| 41 | private readonly version: string = packageJson.version; |
| 42 | private initializedCounters: boolean; |
| 43 | private started: boolean; |
| 44 | private readonly workerScript: string; |
| 45 | |
| 46 | private constructor() { |
| 47 | // Enable unconditionally for now |
| 48 | ErrorUtils.handleUnhandledRejection(); |
| 49 | ErrorUtils.handleUncaughtException(); |
| 50 | this.initializedCounters = false; |
| 51 | this.started = false; |
| 52 | this.initializeCounters(); |
| 53 | this.workerImplementation = null; |
| 54 | this.workerScript = path.join( |
| 55 | path.dirname(fileURLToPath(import.meta.url)), |
| 56 | `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}` |
| 57 | ); |
| 58 | Configuration.getUIServer().enabled === true && |
| 59 | (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer())); |
| 60 | Configuration.getPerformanceStorage().enabled === true && |
| 61 | (this.storage = StorageFactory.getStorage( |
| 62 | Configuration.getPerformanceStorage().type, |
| 63 | Configuration.getPerformanceStorage().uri, |
| 64 | this.logPrefix() |
| 65 | )); |
| 66 | Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart()); |
| 67 | } |
| 68 | |
| 69 | public static getInstance(): Bootstrap { |
| 70 | if (Bootstrap.instance === null) { |
| 71 | Bootstrap.instance = new Bootstrap(); |
| 72 | } |
| 73 | return Bootstrap.instance; |
| 74 | } |
| 75 | |
| 76 | public async start(): Promise<void> { |
| 77 | if (isMainThread && this.started === false) { |
| 78 | this.initializeCounters(); |
| 79 | this.initializeWorkerImplementation(); |
| 80 | await this.workerImplementation?.start(); |
| 81 | await this.storage?.open(); |
| 82 | this.uiServer?.start(); |
| 83 | // Start ChargingStation object instance in worker thread |
| 84 | for (const stationTemplateUrl of Configuration.getStationTemplateUrls()) { |
| 85 | try { |
| 86 | const nbStations = stationTemplateUrl.numberOfStations ?? 0; |
| 87 | for (let index = 1; index <= nbStations; index++) { |
| 88 | await this.startChargingStation(index, stationTemplateUrl); |
| 89 | } |
| 90 | } catch (error) { |
| 91 | console.error( |
| 92 | chalk.red( |
| 93 | `Error at starting charging station with template file ${stationTemplateUrl.file}: ` |
| 94 | ), |
| 95 | error |
| 96 | ); |
| 97 | } |
| 98 | } |
| 99 | console.info( |
| 100 | chalk.green( |
| 101 | `Charging stations simulator ${ |
| 102 | this.version |
| 103 | } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${ |
| 104 | Configuration.workerDynamicPoolInUse() |
| 105 | ? `${Configuration.getWorker().poolMinSize?.toString()}/` |
| 106 | : '' |
| 107 | }${this.workerImplementation?.size}${ |
| 108 | Configuration.workerPoolInUse() |
| 109 | ? `/${Configuration.getWorker().poolMaxSize?.toString()}` |
| 110 | : '' |
| 111 | } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${ |
| 112 | !Utils.isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker) |
| 113 | ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)` |
| 114 | : '' |
| 115 | }` |
| 116 | ) |
| 117 | ); |
| 118 | this.started = true; |
| 119 | } else { |
| 120 | console.error(chalk.red('Cannot start an already started charging stations simulator')); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | public async stop(): Promise<void> { |
| 125 | if (isMainThread && this.started === true) { |
| 126 | await this.workerImplementation?.stop(); |
| 127 | this.workerImplementation = null; |
| 128 | this.uiServer?.stop(); |
| 129 | await this.storage?.close(); |
| 130 | this.initializedCounters = false; |
| 131 | this.started = false; |
| 132 | } else { |
| 133 | console.error(chalk.red('Cannot stop a not started charging stations simulator')); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | public async restart(): Promise<void> { |
| 138 | await this.stop(); |
| 139 | await this.start(); |
| 140 | } |
| 141 | |
| 142 | private initializeWorkerImplementation(): void { |
| 143 | this.workerImplementation === null && |
| 144 | (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>( |
| 145 | this.workerScript, |
| 146 | Configuration.getWorker().processType, |
| 147 | { |
| 148 | workerStartDelay: Configuration.getWorker().startDelay, |
| 149 | elementStartDelay: Configuration.getWorker().elementStartDelay, |
| 150 | poolMaxSize: Configuration.getWorker().poolMaxSize, |
| 151 | poolMinSize: Configuration.getWorker().poolMinSize, |
| 152 | elementsPerWorker: Configuration.getWorker().elementsPerWorker, |
| 153 | poolOptions: { |
| 154 | workerChoiceStrategy: Configuration.getWorker().poolStrategy, |
| 155 | }, |
| 156 | messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>, |
| 157 | } |
| 158 | )); |
| 159 | } |
| 160 | |
| 161 | private messageHandler( |
| 162 | msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData> |
| 163 | ): void { |
| 164 | // logger.debug( |
| 165 | // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify( |
| 166 | // msg, |
| 167 | // null, |
| 168 | // 2 |
| 169 | // )}` |
| 170 | // ); |
| 171 | try { |
| 172 | switch (msg.id) { |
| 173 | case ChargingStationWorkerMessageEvents.started: |
| 174 | this.workerEventStarted(msg.data as ChargingStationData); |
| 175 | break; |
| 176 | case ChargingStationWorkerMessageEvents.stopped: |
| 177 | this.workerEventStopped(msg.data as ChargingStationData); |
| 178 | break; |
| 179 | case ChargingStationWorkerMessageEvents.updated: |
| 180 | this.workerEventUpdated(msg.data as ChargingStationData); |
| 181 | break; |
| 182 | case ChargingStationWorkerMessageEvents.performanceStatistics: |
| 183 | this.workerEventPerformanceStatistics(msg.data as Statistics); |
| 184 | break; |
| 185 | default: |
| 186 | throw new BaseError( |
| 187 | `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}` |
| 188 | ); |
| 189 | } |
| 190 | } catch (error) { |
| 191 | logger.error( |
| 192 | `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${ |
| 193 | msg.id |
| 194 | }' event:`, |
| 195 | error |
| 196 | ); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | private workerEventStarted = (data: ChargingStationData) => { |
| 201 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
| 202 | ++this.numberOfStartedChargingStations; |
| 203 | logger.info( |
| 204 | `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${ |
| 205 | data.stationInfo.chargingStationId |
| 206 | } (hashId: ${data.stationInfo.hashId}) started (${ |
| 207 | this.numberOfStartedChargingStations |
| 208 | } started from ${this.numberOfChargingStations})` |
| 209 | ); |
| 210 | }; |
| 211 | |
| 212 | private workerEventStopped = (data: ChargingStationData) => { |
| 213 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
| 214 | --this.numberOfStartedChargingStations; |
| 215 | logger.info( |
| 216 | `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${ |
| 217 | data.stationInfo.chargingStationId |
| 218 | } (hashId: ${data.stationInfo.hashId}) stopped (${ |
| 219 | this.numberOfStartedChargingStations |
| 220 | } started from ${this.numberOfChargingStations})` |
| 221 | ); |
| 222 | }; |
| 223 | |
| 224 | private workerEventUpdated = (data: ChargingStationData) => { |
| 225 | this.uiServer?.chargingStations.set(data.stationInfo.hashId, data); |
| 226 | }; |
| 227 | |
| 228 | private workerEventPerformanceStatistics = (data: Statistics) => { |
| 229 | this.storage.storePerformanceStatistics(data) as void; |
| 230 | }; |
| 231 | |
| 232 | private initializeCounters() { |
| 233 | if (this.initializedCounters === false) { |
| 234 | this.numberOfChargingStationTemplates = 0; |
| 235 | this.numberOfChargingStations = 0; |
| 236 | const stationTemplateUrls = Configuration.getStationTemplateUrls(); |
| 237 | if (Utils.isNotEmptyArray(stationTemplateUrls)) { |
| 238 | this.numberOfChargingStationTemplates = stationTemplateUrls.length; |
| 239 | for (const stationTemplateUrl of stationTemplateUrls) { |
| 240 | this.numberOfChargingStations += stationTemplateUrl.numberOfStations ?? 0; |
| 241 | } |
| 242 | } else { |
| 243 | console.warn( |
| 244 | chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting") |
| 245 | ); |
| 246 | process.exit(exitCodes.missingChargingStationsConfiguration); |
| 247 | } |
| 248 | if (this.numberOfChargingStations === 0) { |
| 249 | console.warn( |
| 250 | chalk.yellow('No charging station template enabled in configuration, exiting') |
| 251 | ); |
| 252 | process.exit(exitCodes.noChargingStationTemplates); |
| 253 | } |
| 254 | this.numberOfStartedChargingStations = 0; |
| 255 | this.initializedCounters = true; |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | private async startChargingStation( |
| 260 | index: number, |
| 261 | stationTemplateUrl: StationTemplateUrl |
| 262 | ): Promise<void> { |
| 263 | await this.workerImplementation?.addElement({ |
| 264 | index, |
| 265 | templateFile: path.join( |
| 266 | path.dirname(fileURLToPath(import.meta.url)), |
| 267 | 'assets', |
| 268 | 'station-templates', |
| 269 | stationTemplateUrl.file |
| 270 | ), |
| 271 | }); |
| 272 | } |
| 273 | |
| 274 | private logPrefix = (): string => { |
| 275 | return Utils.logPrefix(' Bootstrap |'); |
| 276 | }; |
| 277 | } |