Restructure UI server code to prepare it for issue #238
authorJérôme Benoit <jerome.benoit@sap.com>
Fri, 13 May 2022 08:25:23 +0000 (10:25 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Fri, 13 May 2022 08:25:23 +0000 (10:25 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
README.md
src/charging-station/Bootstrap.ts
src/charging-station/ui-server/UIWebSocketServer.ts [moved from src/charging-station/UIWebSocketServer.ts with 81% similarity]
src/charging-station/ui-server/ui-services/AbstractUIService.ts [moved from src/charging-station/ui-websocket-services/AbstractUIService.ts with 69% similarity]
src/charging-station/ui-server/ui-services/UIService001.ts [moved from src/charging-station/ui-websocket-services/UIService001.ts with 73% similarity]
src/charging-station/ui-server/ui-services/UIServiceFactory.ts [moved from src/charging-station/ui-websocket-services/UIServiceFactory.ts with 75% similarity]
src/charging-station/ui-server/ui-services/UIServiceUtils.ts [moved from src/charging-station/ui-websocket-services/UIServiceUtils.ts with 86% similarity]
src/types/ConfigurationData.ts
src/types/UIProtocol.ts
src/utils/Configuration.ts

index 7873b31f337766396cb931f7a3f5bbbe52f09e37..849bea6f79f6084f5548e3669b6d11636379f810 100644 (file)
--- a/README.md
+++ b/README.md
@@ -80,7 +80,7 @@ But the modifications to test have to be done to the files in the build result d
 | logLevel                   | emerg/alert/crit/error/warning/notice/info/debug | info                                                                        | string                                                                                     | winston logging level                                                                                                                                   |
 | logFile                    |                                                  | combined.log                                                                | string                                                                                     | log file relative path                                                                                                                                  |
 | logErrorFile               |                                                  | error.log                                                                   | string                                                                                     | error log file relative path                                                                                                                            |
-| uiWebSocketServer          |                                                  | { "enabled": true, "options": { "host: "localhost", "port": 8080 } }        | { enabled: boolean; options: ServerOptions; }                                              | UI WebSocket server configuration section                                                                                                               |
+| uiServer                   |                                                  | { "enabled": true, "options": { "host: "localhost", "port": 8080 } }        | { enabled: boolean; options: ServerOptions; }                                              | UI WebSocket server configuration section                                                                                                               |
 | performanceStorage         |                                                  | { "enabled": false, "type": "jsonfile", "file:///performanceRecords.json" } | { enabled: boolean; type: string; URI: string; } where type can be 'jsonfile' or 'mongodb' | performance storage configuration section                                                                                                               |
 | stationTemplateUrls        |                                                  | {}[]                                                                        | { file: string; numberOfStations: number; }[]                                              | array of charging station configuration templates URIs configuration section (charging station configuration template file name and number of stations) |
 
index 7113500740fa30d57ad5915ad12ef91483fe4f8c..3701b1706616522a7e23f9cc129ddffabb8c2891 100644 (file)
@@ -11,8 +11,8 @@ import { StationTemplateUrl } from '../types/ConfigurationData';
 import Statistics from '../types/Statistics';
 import { Storage } from '../performance/storage/Storage';
 import { StorageFactory } from '../performance/storage/StorageFactory';
-import { UIServiceUtils } from './ui-websocket-services/UIServiceUtils';
-import UIWebSocketServer from './UIWebSocketServer';
+import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
+import UIWebSocketServer from './ui-server/UIWebSocketServer';
 import Utils from '../utils/Utils';
 import WorkerAbstract from '../worker/WorkerAbstract';
 import WorkerFactory from '../worker/WorkerFactory';
@@ -24,7 +24,7 @@ import { version } from '../../package.json';
 export default class Bootstrap {
   private static instance: Bootstrap | null = null;
   private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
-  private readonly uiWebSocketServer!: UIWebSocketServer;
+  private readonly uiServer!: UIWebSocketServer;
   private readonly storage!: Storage;
   private numberOfChargingStations: number;
   private readonly version: string = version;
@@ -39,9 +39,9 @@ export default class Bootstrap {
       'ChargingStationWorker.js'
     );
     this.initWorkerImplementation();
-    Configuration.getUIWebSocketServer().enabled &&
-      (this.uiWebSocketServer = new UIWebSocketServer({
-        ...Configuration.getUIWebSocketServer().options,
+    Configuration.getUIServer().enabled &&
+      (this.uiServer = new UIWebSocketServer({
+        ...Configuration.getUIServer().options,
         handleProtocols: UIServiceUtils.handleProtocols,
       }));
     Configuration.getPerformanceStorage().enabled &&
@@ -66,7 +66,7 @@ export default class Bootstrap {
         this.numberOfChargingStations = 0;
         await this.storage?.open();
         await this.workerImplementation.start();
-        this.uiWebSocketServer?.start();
+        this.uiServer?.start();
         const stationTemplateUrls = Configuration.getStationTemplateUrls();
         // Start ChargingStation object in worker thread
         if (stationTemplateUrls) {
@@ -125,7 +125,7 @@ export default class Bootstrap {
   public async stop(): Promise<void> {
     if (isMainThread && this.started) {
       await this.workerImplementation.stop();
-      this.uiWebSocketServer?.stop();
+      this.uiServer?.stop();
       await this.storage?.close();
     } else {
       console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
@@ -154,9 +154,9 @@ export default class Bootstrap {
         },
         messageHandler: async (msg: ChargingStationWorkerMessage) => {
           if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
-            this.uiWebSocketServer.chargingStations.add(msg.data.id as string);
+            this.uiServer.chargingStations.add(msg.data.id as string);
           } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
-            this.uiWebSocketServer.chargingStations.delete(msg.data.id as string);
+            this.uiServer.chargingStations.delete(msg.data.id as string);
           } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
             await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
           }
similarity index 81%
rename from src/charging-station/UIWebSocketServer.ts
rename to src/charging-station/ui-server/UIWebSocketServer.ts
index 424ab8c936b560fe1088d9a99022f0dd98b240e9..98dd52b2489fdeb1dc82670ed40339d2934893a5 100644 (file)
@@ -1,12 +1,12 @@
-import { Protocol, ProtocolVersion } from '../types/UIProtocol';
+import { Protocol, ProtocolVersion } from '../../types/UIProtocol';
 import WebSocket, { OPEN, Server, ServerOptions } from 'ws';
 
-import AbstractUIService from './ui-websocket-services/AbstractUIService';
-import Configuration from '../utils/Configuration';
+import AbstractUIService from './ui-services/AbstractUIService';
+import Configuration from '../../utils/Configuration';
 import { IncomingMessage } from 'http';
-import UIServiceFactory from './ui-websocket-services/UIServiceFactory';
-import Utils from '../utils/Utils';
-import logger from '../utils/Logger';
+import UIServiceFactory from './ui-services/UIServiceFactory';
+import Utils from '../../utils/Utils';
+import logger from '../../utils/Logger';
 
 export default class UIWebSocketServer extends Server {
   public readonly chargingStations: Set<string>;
@@ -14,7 +14,7 @@ export default class UIWebSocketServer extends Server {
 
   public constructor(options?: ServerOptions, callback?: () => void) {
     // Create the WebSocket Server
-    super(options ?? Configuration.getUIWebSocketServer().options, callback);
+    super(options ?? Configuration.getUIServer().options, callback);
     this.chargingStations = new Set<string>();
     this.uiServices = new Map<ProtocolVersion, AbstractUIService>();
   }
similarity index 69%
rename from src/charging-station/ui-websocket-services/AbstractUIService.ts
rename to src/charging-station/ui-server/ui-services/AbstractUIService.ts
index f8de1be5ab845374ab95398d221f18ea0fe5ce27..d4ad33988e2062f7c99b779026f07cf5323c1fe0 100644 (file)
@@ -1,18 +1,22 @@
-import { ProtocolCommand, ProtocolRequest, ProtocolRequestHandler } from '../../types/UIProtocol';
+import {
+  ProtocolCommand,
+  ProtocolRequest,
+  ProtocolRequestHandler,
+} from '../../../types/UIProtocol';
 
-import BaseError from '../../exception/BaseError';
-import { JsonType } from '../../types/JsonType';
+import BaseError from '../../../exception/BaseError';
+import { JsonType } from '../../../types/JsonType';
 import { RawData } from 'ws';
 import UIWebSocketServer from '../UIWebSocketServer';
-import Utils from '../../utils/Utils';
-import logger from '../../utils/Logger';
+import Utils from '../../../utils/Utils';
+import logger from '../../../utils/Logger';
 
 export default abstract class AbstractUIService {
-  protected readonly uiWebSocketServer: UIWebSocketServer;
+  protected readonly uiServer: UIWebSocketServer;
   protected readonly messageHandlers: Map<ProtocolCommand, ProtocolRequestHandler>;
 
-  constructor(uiWebSocketServer: UIWebSocketServer) {
-    this.uiWebSocketServer = uiWebSocketServer;
+  constructor(uiServer: UIWebSocketServer) {
+    this.uiServer = uiServer;
     this.messageHandlers = new Map<ProtocolCommand, ProtocolRequestHandler>([
       [ProtocolCommand.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
     ]);
@@ -34,7 +38,7 @@ export default abstract class AbstractUIService {
         messageResponse = (await this.messageHandlers.get(command)(payload)) as JsonType;
       } catch (error) {
         // Log
-        logger.error(this.uiWebSocketServer.logPrefix() + ' Handle message error: %j', error);
+        logger.error(this.uiServer.logPrefix() + ' Handle message error: %j', error);
         throw error;
       }
     } else {
@@ -48,7 +52,7 @@ export default abstract class AbstractUIService {
       );
     }
     // Send the message response
-    this.uiWebSocketServer.sendResponse(this.buildProtocolMessage(command, messageResponse));
+    this.uiServer.sendResponse(this.buildProtocolMessage(command, messageResponse));
   }
 
   protected buildProtocolMessage(command: ProtocolCommand, payload: JsonType): string {
@@ -56,6 +60,6 @@ export default abstract class AbstractUIService {
   }
 
   private handleListChargingStations(): JsonType {
-    return Array.from(this.uiWebSocketServer.chargingStations);
+    return Array.from(this.uiServer.chargingStations);
   }
 }
similarity index 73%
rename from src/charging-station/ui-websocket-services/UIService001.ts
rename to src/charging-station/ui-server/ui-services/UIService001.ts
index 18fb66a9d4a08589883bcb3569622bccac817034..eecdcd34792da1ef2bf6beae1f4cff19595ab704 100644 (file)
@@ -1,12 +1,12 @@
-import { ProtocolCommand, ProtocolRequestHandler } from '../../types/UIProtocol';
+import { ProtocolCommand, ProtocolRequestHandler } from '../../../types/UIProtocol';
 
 import AbstractUIService from './AbstractUIService';
-import { JsonType } from '../../types/JsonType';
+import { JsonType } from '../../../types/JsonType';
 import UIWebSocketServer from '../UIWebSocketServer';
 
 export default class UIService001 extends AbstractUIService {
-  constructor(uiWebSocketServer: UIWebSocketServer) {
-    super(uiWebSocketServer);
+  constructor(uiServer: UIWebSocketServer) {
+    super(uiServer);
     this.messageHandlers.set(
       ProtocolCommand.START_TRANSACTION,
       this.handleStartTransaction.bind(this) as ProtocolRequestHandler
similarity index 75%
rename from src/charging-station/ui-websocket-services/UIServiceFactory.ts
rename to src/charging-station/ui-server/ui-services/UIServiceFactory.ts
index d6a87cdb1b69429d3852175d0fa56be30682bbe9..d4f92c10d30345845aff373e5bbb29cb995252ce 100644 (file)
@@ -1,5 +1,5 @@
 import AbstractUIService from './AbstractUIService';
-import { ProtocolVersion } from '../../types/UIProtocol';
+import { ProtocolVersion } from '../../../types/UIProtocol';
 import UIService001 from './UIService001';
 import UIWebSocketServer from '../UIWebSocketServer';
 
@@ -10,11 +10,11 @@ export default class UIServiceFactory {
 
   public static getUIServiceImplementation(
     version: ProtocolVersion,
-    uiWebSocketServer: UIWebSocketServer
+    uiServer: UIWebSocketServer
   ): AbstractUIService | null {
     switch (version) {
       case ProtocolVersion['0.0.1']:
-        return new UIService001(uiWebSocketServer);
+        return new UIService001(uiServer);
       default:
         return null;
     }
similarity index 86%
rename from src/charging-station/ui-websocket-services/UIServiceUtils.ts
rename to src/charging-station/ui-server/ui-services/UIServiceUtils.ts
index 9427c08e5aa61b466a77e6caa5f111e3af8147ed..dabb5d474e88a78aebe5ea965b5b591e9f20246e 100644 (file)
@@ -1,8 +1,8 @@
-import { Protocol, ProtocolVersion } from '../../types/UIProtocol';
+import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
 
 import { IncomingMessage } from 'http';
-import Utils from '../../utils/Utils';
-import logger from '../../utils/Logger';
+import Utils from '../../../utils/Utils';
+import logger from '../../../utils/Logger';
 
 export class UIServiceUtils {
   public static handleProtocols = (
index 94e65ed55d93f90c37fe361376bf96e5162e5b0b..cf534c39bfe6d8e6ef71359a7268d2442e82c69a 100644 (file)
@@ -14,7 +14,7 @@ export interface StationTemplateUrl {
   numberOfStations: number;
 }
 
-export interface UIWebSocketServerConfiguration {
+export interface UIServerConfiguration {
   enabled?: boolean;
   options?: ServerOptions;
 }
@@ -29,7 +29,7 @@ export default interface ConfigurationData {
   supervisionUrls?: string | string[];
   supervisionUrlDistribution?: SupervisionUrlDistribution;
   stationTemplateUrls: StationTemplateUrl[];
-  uiWebSocketServer?: UIWebSocketServerConfiguration;
+  uiServer?: UIServerConfiguration;
   performanceStorage?: StorageConfiguration;
   autoReconnectMaxRetries?: number;
   workerProcess?: WorkerProcessType;
index 4344c0d642df3e7ab229750b7b71be40455389d3..1756c0faff73b694a310f83bbf368c898aa8100f 100644 (file)
@@ -4,6 +4,11 @@ export enum Protocol {
   UI = 'ui',
 }
 
+export enum ApplicationProtocol {
+  HTTP = 'http',
+  WS = 'ws',
+}
+
 export enum ProtocolVersion {
   '0.0.1' = '0.0.1',
 }
index 9ab2582d140d54ddb068aaac229aeba9577734b1..0b0bec774c1465c147f54689de9846aba8faf143 100644 (file)
@@ -2,7 +2,7 @@ import ConfigurationData, {
   StationTemplateUrl,
   StorageConfiguration,
   SupervisionUrlDistribution,
-  UIWebSocketServerConfiguration,
+  UIServerConfiguration,
 } from '../types/ConfigurationData';
 
 import Constants from './Constants';
@@ -45,41 +45,38 @@ export default class Configuration {
       : Constants.DEFAULT_LOG_STATISTICS_INTERVAL;
   }
 
-  static getUIWebSocketServer(): UIWebSocketServerConfiguration {
+  static getUIServer(): UIServerConfiguration {
     let options: ServerOptions = {
       host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
       port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT,
     };
-    let uiWebSocketServerConfiguration: UIWebSocketServerConfiguration = {
+    let uiServerConfiguration: UIServerConfiguration = {
       enabled: true,
       options,
     };
-    if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiWebSocketServer')) {
-      if (
-        Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'options')
-      ) {
+    if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiServer')) {
+      if (Configuration.objectHasOwnProperty(Configuration.getConfig().uiServer, 'options')) {
         options = {
           ...options,
           ...(Configuration.objectHasOwnProperty(
-            Configuration.getConfig().uiWebSocketServer.options,
+            Configuration.getConfig().uiServer.options,
             'host'
-          ) && { host: Configuration.getConfig().uiWebSocketServer.options.host }),
+          ) && { host: Configuration.getConfig().uiServer.options.host }),
           ...(Configuration.objectHasOwnProperty(
-            Configuration.getConfig().uiWebSocketServer.options,
+            Configuration.getConfig().uiServer.options,
             'port'
-          ) && { port: Configuration.getConfig().uiWebSocketServer.options.port }),
+          ) && { port: Configuration.getConfig().uiServer.options.port }),
         };
       }
-      uiWebSocketServerConfiguration = {
-        ...uiWebSocketServerConfiguration,
-        ...(Configuration.objectHasOwnProperty(
-          Configuration.getConfig().uiWebSocketServer,
-          'enabled'
-        ) && { enabled: Configuration.getConfig().uiWebSocketServer.enabled }),
+      uiServerConfiguration = {
+        ...uiServerConfiguration,
+        ...(Configuration.objectHasOwnProperty(Configuration.getConfig().uiServer, 'enabled') && {
+          enabled: Configuration.getConfig().uiServer.enabled,
+        }),
         options,
       };
     }
-    return uiWebSocketServerConfiguration;
+    return uiServerConfiguration;
   }
 
   static getPerformanceStorage(): StorageConfiguration {