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