546c7642de181d33de56e8f4ea9e214515a2220e
[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';
6 import {
7 type ProcedureName,
8 type Protocol,
9 type ProtocolRequest,
10 type ProtocolResponse,
11 type ProtocolVersion,
12 type RequestPayload,
13 ResponseStatus,
14 type UIServerConfiguration,
15 } from '../../types';
16 import { logger } from '../../utils/Logger';
17 import { Utils } from '../../utils/Utils';
18 import { AbstractUIServer, UIServerUtils } from '../internal';
19
20 const moduleName = 'UIHttpServer';
21
22 export class UIHttpServer extends AbstractUIServer {
23 public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) {
24 super(uiServerConfiguration);
25 }
26
27 public start(): void {
28 this.httpServer.on('request', this.requestListener.bind(this) as RequestListener);
29 this.startHttpServer();
30 }
31
32 // eslint-disable-next-line @typescript-eslint/no-unused-vars
33 public sendRequest(request: ProtocolRequest): void {
34 // This is intentionally left blank
35 }
36
37 public sendResponse(response: ProtocolResponse): void {
38 const [uuid, payload] = response;
39 try {
40 if (this.responseHandlers.has(uuid) === true) {
41 const res = this.responseHandlers.get(uuid) as ServerResponse;
42 res
43 .writeHead(this.responseStatusToStatusCode(payload.status), {
44 'Content-Type': 'application/json',
45 })
46 .end(JSON.stringify(payload));
47 } else {
48 logger.error(
49 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
50 );
51 }
52 } catch (error) {
53 logger.error(
54 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
55 error
56 );
57 } finally {
58 this.responseHandlers.delete(uuid);
59 }
60 }
61
62 public logPrefix = (modName?: string, methodName?: string, prefixSuffix?: string): string => {
63 const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
64 const logMsg =
65 Utils.isNotEmptyString(modName) && Utils.isNotEmptyString(methodName)
66 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
67 : ` ${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 const fullProtocol = `${protocol}${version}`;
94 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === false) {
95 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
96 }
97 this.registerProtocolVersionUIService(version);
98 req.on('error', (error) => {
99 logger.error(
100 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
101 error
102 );
103 });
104 if (req.method === 'POST') {
105 const bodyBuffer = [];
106 req
107 .on('data', (chunk) => {
108 bodyBuffer.push(chunk);
109 })
110 .on('end', () => {
111 const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
112 this.uiServices
113 .get(version)
114 ?.requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
115 .catch(() => {
116 /* Error caught by AbstractUIService */
117 });
118 });
119 } else {
120 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
121 }
122 } catch (error) {
123 logger.error(
124 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
125 error
126 );
127 this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }));
128 }
129 }
130
131 private responseStatusToStatusCode(status: ResponseStatus): StatusCodes {
132 switch (status) {
133 case ResponseStatus.SUCCESS:
134 return StatusCodes.OK;
135 case ResponseStatus.FAILURE:
136 return StatusCodes.BAD_REQUEST;
137 default:
138 return StatusCodes.INTERNAL_SERVER_ERROR;
139 }
140 }
141 }