152529373d375f033985f571989ed8e31cc63dba
[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 type { ServerOptions } from '../../types/ConfigurationData';
7 import {
8 ProcedureName,
9 Protocol,
10 ProtocolRequest,
11 ProtocolResponse,
12 ProtocolVersion,
13 RequestPayload,
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 if ((this.server as Server).listening === false) {
38 (this.server as Server).listen(this.options ?? Configuration.getUIServer().options);
39 }
40 }
41
42 public stop(): void {
43 this.chargingStations.clear();
44 this.responseHandlers.clear();
45 }
46
47 // eslint-disable-next-line @typescript-eslint/no-unused-vars
48 public sendRequest(request: ProtocolRequest): void {
49 // This is intentionally left blank
50 }
51
52 public sendResponse(response: ProtocolResponse): void {
53 const [uuid, payload] = response;
54 const statusCode = this.responseStatusToStatusCode(payload.status);
55 if (this.responseHandlers.has(uuid) === true) {
56 const { res } = this.responseHandlers.get(uuid);
57 res.writeHead(statusCode, { 'Content-Type': 'application/json' });
58 res.write(JSON.stringify(payload));
59 res.end();
60 this.responseHandlers.delete(uuid);
61 } else {
62 logger.error(
63 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
64 );
65 }
66 }
67
68 public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string {
69 const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
70 const logMsg =
71 modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
72 return Utils.logPrefix(logMsg);
73 }
74
75 private requestListener(req: IncomingMessage, res: ServerResponse): void {
76 // Expected request URL pathname: /ui/:version/:procedureName
77 const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [
78 Protocol,
79 ProtocolVersion,
80 ProcedureName
81 ];
82 const uuid = Utils.generateUUID();
83 this.responseHandlers.set(uuid, { procedureName, res });
84 try {
85 if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) {
86 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
87 }
88 req.on('error', (error) => {
89 logger.error(
90 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
91 error
92 );
93 });
94 if (!this.uiServices.has(version)) {
95 this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this));
96 }
97 if (req.method === 'POST') {
98 const bodyBuffer = [];
99 req
100 .on('data', (chunk) => {
101 bodyBuffer.push(chunk);
102 })
103 .on('end', () => {
104 const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
105 this.uiServices
106 .get(version)
107 .requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
108 .catch(() => {
109 this.sendResponse(
110 this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE })
111 );
112 });
113 });
114 } else {
115 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
116 }
117 } catch (error) {
118 logger.error(
119 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
120 error
121 );
122 this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }));
123 }
124 }
125
126 private responseStatusToStatusCode(status: ResponseStatus): StatusCodes {
127 switch (status) {
128 case ResponseStatus.SUCCESS:
129 return StatusCodes.OK;
130 case ResponseStatus.FAILURE:
131 return StatusCodes.BAD_REQUEST;
132 default:
133 return StatusCodes.INTERNAL_SERVER_ERROR;
134 }
135 }
136 }