refactor(simulator): switch to named exports
[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';
8 import {
9 type ProcedureName,
10 type Protocol,
11 type ProtocolRequest,
12 type ProtocolResponse,
13 type ProtocolVersion,
14 type RequestPayload,
15 ResponseStatus,
16 type UIServerConfiguration,
17 } from '../../types';
18 import { logger } from '../../utils/Logger';
19 import { Utils } from '../../utils/Utils';
20
21 const moduleName = 'UIHttpServer';
22
23 export 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 Utils.isNotEmptyString(modName) && Utils.isNotEmptyString(methodName)
67 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
68 : ` ${logMsgPrefix} |`;
69 return Utils.logPrefix(logMsg);
70 };
71
72 private requestListener(req: IncomingMessage, res: ServerResponse): void {
73 this.authenticate(req, (err) => {
74 if (err) {
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();
82 req.destroy();
83 }
84 });
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();
92 this.responseHandlers.set(uuid, res);
93 try {
94 const fullProtocol = `${protocol}${version}`;
95 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === false) {
96 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
97 }
98 this.registerProtocolVersionUIService(version);
99 req.on('error', (error) => {
100 logger.error(
101 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
102 error
103 );
104 });
105 if (req.method === 'POST') {
106 const bodyBuffer = [];
107 req
108 .on('data', (chunk) => {
109 bodyBuffer.push(chunk);
110 })
111 .on('end', () => {
112 const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
113 this.uiServices
114 .get(version)
115 ?.requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
116 .catch(() => {
117 /* Error caught by AbstractUIService */
118 });
119 });
120 } else {
121 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
122 }
123 } catch (error) {
124 logger.error(
125 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
126 error
127 );
128 this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }));
129 }
130 }
131
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 }
142 }