87f10a5eab41ef30ce19d0dd5211320900d9697e
[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 { AbstractUIServer } from './AbstractUIServer';
6 import { UIServerUtils } from './UIServerUtils';
7 import BaseError from '../../exception/BaseError';
8 import type { UIServerConfiguration } from '../../types/ConfigurationData';
9 import {
10 type ProcedureName,
11 type Protocol,
12 type ProtocolRequest,
13 type ProtocolResponse,
14 type ProtocolVersion,
15 type RequestPayload,
16 ResponseStatus,
17 } from '../../types/UIProtocol';
18 import logger from '../../utils/Logger';
19 import Utils from '../../utils/Utils';
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 this.startHttpServer();
31 }
32
33 // eslint-disable-next-line @typescript-eslint/no-unused-vars
34 public sendRequest(request: ProtocolRequest): void {
35 // This is intentionally left blank
36 }
37
38 public sendResponse(response: ProtocolResponse): void {
39 const [uuid, payload] = response;
40 try {
41 if (this.responseHandlers.has(uuid) === true) {
42 const res = this.responseHandlers.get(uuid) as ServerResponse;
43 res
44 .writeHead(this.responseStatusToStatusCode(payload.status), {
45 'Content-Type': 'application/json',
46 })
47 .end(JSON.stringify(payload));
48 } else {
49 logger.error(
50 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
51 );
52 }
53 } catch (error) {
54 logger.error(
55 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
56 error
57 );
58 } finally {
59 this.responseHandlers.delete(uuid);
60 }
61 }
62
63 public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string {
64 const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
65 const logMsg =
66 modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
67 return Utils.logPrefix(logMsg);
68 }
69
70 private requestListener(req: IncomingMessage, res: ServerResponse): void {
71 this.authenticate(req, (err) => {
72 if (err) {
73 res
74 .writeHead(StatusCodes.UNAUTHORIZED, {
75 'Content-Type': 'text/plain',
76 'WWW-Authenticate': 'Basic realm=users',
77 })
78 .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`)
79 .destroy();
80 req.destroy();
81 }
82 });
83 // Expected request URL pathname: /ui/:version/:procedureName
84 const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [
85 Protocol,
86 ProtocolVersion,
87 ProcedureName
88 ];
89 const uuid = Utils.generateUUID();
90 this.responseHandlers.set(uuid, res);
91 try {
92 const fullProtocol = `${protocol}${version}`;
93 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === false) {
94 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
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 }