refactor(simulator): switch utils to internal module export/import
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIHttpServer.ts
CommitLineData
daa6505e 1import type { IncomingMessage, RequestListener, ServerResponse } from 'http';
1f7fa4de 2
a0202edc 3import { StatusCodes } from 'http-status-codes';
1f7fa4de 4
268a74bb 5import { BaseError } from '../../exception';
1f7fa4de 6import {
e0b0ee21
JB
7 type ProcedureName,
8 type Protocol,
9 type ProtocolRequest,
10 type ProtocolResponse,
11 type ProtocolVersion,
12 type RequestPayload,
1f7fa4de 13 ResponseStatus,
268a74bb
JB
14 type UIServerConfiguration,
15} from '../../types';
60a74391 16import { Utils, logger } from '../../utils';
2896e06d 17import { AbstractUIServer, UIServerUtils } from '../internal';
1f7fa4de
JB
18
19const moduleName = 'UIHttpServer';
20
268a74bb 21export class UIHttpServer extends AbstractUIServer {
eb3abc4f
JB
22 public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) {
23 super(uiServerConfiguration);
1f7fa4de
JB
24 }
25
26 public start(): void {
daa6505e 27 this.httpServer.on('request', this.requestListener.bind(this) as RequestListener);
a307349b 28 this.startHttpServer();
1f7fa4de
JB
29 }
30
1f7fa4de 31 // eslint-disable-next-line @typescript-eslint/no-unused-vars
5e3cb728 32 public sendRequest(request: ProtocolRequest): void {
1f7fa4de
JB
33 // This is intentionally left blank
34 }
35
5e3cb728
JB
36 public sendResponse(response: ProtocolResponse): void {
37 const [uuid, payload] = response;
976d11ec
JB
38 try {
39 if (this.responseHandlers.has(uuid) === true) {
40 const res = this.responseHandlers.get(uuid) as ServerResponse;
b2e2c274
JB
41 res
42 .writeHead(this.responseStatusToStatusCode(payload.status), {
43 'Content-Type': 'application/json',
44 })
45 .end(JSON.stringify(payload));
976d11ec
JB
46 } else {
47 logger.error(
48 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
49 );
50 }
51 } catch (error) {
1f7fa4de 52 logger.error(
976d11ec
JB
53 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
54 error
1f7fa4de 55 );
e2c77f10
JB
56 } finally {
57 this.responseHandlers.delete(uuid);
1f7fa4de
JB
58 }
59 }
60
8b7072dc 61 public logPrefix = (modName?: string, methodName?: string, prefixSuffix?: string): string => {
0d2cec76 62 const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
1f7fa4de 63 const logMsg =
5a2a53cf 64 Utils.isNotEmptyString(modName) && Utils.isNotEmptyString(methodName)
1b271a54
JB
65 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
66 : ` ${logMsgPrefix} |`;
1f7fa4de 67 return Utils.logPrefix(logMsg);
8b7072dc 68 };
1f7fa4de
JB
69
70 private requestListener(req: IncomingMessage, res: ServerResponse): void {
72092cfc 71 this.authenticate(req, (err) => {
623b39b5 72 if (err) {
b2e2c274
JB
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();
623b39b5 80 req.destroy();
623b39b5
JB
81 }
82 });
1f7fa4de
JB
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();
94dc3080 90 this.responseHandlers.set(uuid, res);
1f7fa4de 91 try {
7cb5b17f 92 const fullProtocol = `${protocol}${version}`;
ed3d2808 93 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === false) {
7cb5b17f 94 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
1f7fa4de 95 }
daa6505e 96 this.registerProtocolVersionUIService(version);
72092cfc 97 req.on('error', (error) => {
1f7fa4de 98 logger.error(
a745e412 99 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
1f7fa4de
JB
100 error
101 );
102 });
1f7fa4de
JB
103 if (req.method === 'POST') {
104 const bodyBuffer = [];
1f7fa4de 105 req
72092cfc 106 .on('data', (chunk) => {
1f7fa4de
JB
107 bodyBuffer.push(chunk);
108 })
109 .on('end', () => {
a745e412 110 const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
1f7fa4de
JB
111 this.uiServices
112 .get(version)
551e477c 113 ?.requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
1f7fa4de 114 .catch(() => {
976d11ec 115 /* Error caught by AbstractUIService */
1f7fa4de
JB
116 });
117 });
118 } else {
119 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
120 }
121 } catch (error) {
a745e412
JB
122 logger.error(
123 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
124 error
125 );
852a4c5f 126 this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }));
1f7fa4de
JB
127 }
128 }
129
771633ff
JB
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 }
1f7fa4de 140}