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