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