2d729bfc3be22b57ca4a0e71e26702245e5fedd2
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIHttpServer.ts
1 import { IncomingMessage, RequestListener, Server, ServerResponse } from 'http';
2
3 import { StatusCodes } from 'http-status-codes';
4
5 import BaseError from '../../exception/BaseError';
6 import { ServerOptions } from '../../types/ConfigurationData';
7 import {
8 ProcedureName,
9 Protocol,
10 ProtocolResponse,
11 ProtocolVersion,
12 RequestPayload,
13 ResponsePayload,
14 ResponseStatus,
15 } from '../../types/UIProtocol';
16 import Configuration from '../../utils/Configuration';
17 import logger from '../../utils/Logger';
18 import Utils from '../../utils/Utils';
19 import { AbstractUIServer } from './AbstractUIServer';
20 import UIServiceFactory from './ui-services/UIServiceFactory';
21 import { UIServiceUtils } from './ui-services/UIServiceUtils';
22
23 const moduleName = 'UIHttpServer';
24
25 type responseHandler = { procedureName: ProcedureName; res: ServerResponse };
26
27 export default class UIHttpServer extends AbstractUIServer {
28 private readonly responseHandlers: Map<string, responseHandler>;
29
30 public constructor(private options?: ServerOptions) {
31 super();
32 this.server = new Server(this.requestListener.bind(this) as RequestListener);
33 this.responseHandlers = new Map<string, responseHandler>();
34 }
35
36 public start(): void {
37 (this.server as Server).listen(this.options ?? Configuration.getUIServer().options);
38 }
39
40 public stop(): void {
41 this.chargingStations.clear();
42 }
43
44 // eslint-disable-next-line @typescript-eslint/no-unused-vars
45 public sendRequest(request: string): void {
46 // This is intentionally left blank
47 }
48
49 public sendResponse(response: string): void {
50 const [uuid, payload] = JSON.parse(response) as ProtocolResponse;
51 const statusCode = this.responseStatusToStatusCode(payload.status);
52 if (this.responseHandlers.has(uuid)) {
53 const { res } = this.responseHandlers.get(uuid);
54 res.writeHead(statusCode, { 'Content-Type': 'application/json' });
55 res.write(JSON.stringify(payload));
56 res.end();
57 this.responseHandlers.delete(uuid);
58 } else {
59 logger.error(
60 `${this.logPrefix()} ${moduleName}.sendResponse: Response received for unknown request: ${response}`
61 );
62 }
63 }
64
65 public logPrefix(modName?: string, methodName?: string): string {
66 const logMsg =
67 modName && methodName ? ` UI HTTP Server | ${modName}.${methodName}:` : ' UI HTTP Server |';
68 return Utils.logPrefix(logMsg);
69 }
70
71 private requestListener(req: IncomingMessage, res: ServerResponse): void {
72 // Expected request URL pathname: /ui/:version/:procedureName
73 const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [
74 Protocol,
75 ProtocolVersion,
76 ProcedureName
77 ];
78 const uuid = Utils.generateUUID();
79 this.responseHandlers.set(uuid, { procedureName, res });
80 try {
81 if (UIServiceUtils.isProtocolSupported(protocol, version) === false) {
82 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
83 }
84 req.on('error', (error) => {
85 logger.error(
86 `${this.logPrefix(
87 moduleName,
88 'requestListener.req.onerror'
89 )} Error at incoming request handling:`,
90 error
91 );
92 });
93 if (!this.uiServices.has(version)) {
94 this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this));
95 }
96 if (req.method === 'POST') {
97 const bodyBuffer = [];
98 let body: RequestPayload;
99 req
100 .on('data', (chunk) => {
101 bodyBuffer.push(chunk);
102 })
103 .on('end', () => {
104 body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
105 this.uiServices
106 .get(version)
107 .requestHandler(this.buildRequest(uuid, procedureName, body ?? {}))
108 .catch(() => {
109 this.sendResponse(this.buildResponse(uuid, { status: ResponseStatus.FAILURE }));
110 });
111 });
112 } else {
113 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
114 }
115 } catch (error) {
116 this.sendResponse(this.buildResponse(uuid, { status: ResponseStatus.FAILURE }));
117 }
118 }
119
120 private buildRequest(
121 id: string,
122 procedureName: ProcedureName,
123 requestPayload: RequestPayload
124 ): string {
125 return JSON.stringify([id, procedureName, requestPayload]);
126 }
127
128 private buildResponse(id: string, responsePayload: ResponsePayload): string {
129 return JSON.stringify([id, responsePayload]);
130 }
131
132 private responseStatusToStatusCode(status: ResponseStatus): StatusCodes {
133 switch (status) {
134 case ResponseStatus.SUCCESS:
135 return StatusCodes.OK;
136 case ResponseStatus.FAILURE:
137 return StatusCodes.BAD_REQUEST;
138 default:
139 return StatusCodes.INTERNAL_SERVER_ERROR;
140 }
141 }
142 }