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