feat: add initial HTTP/2 support to ui server (mutually exclusive for now)
[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 { AbstractUIServer } from './AbstractUIServer';
6 import { UIServerUtils } from './UIServerUtils';
7 import { BaseError } from '../../exception';
8 import {
9 ApplicationProtocolVersion,
10 type ProcedureName,
11 type Protocol,
12 type ProtocolRequest,
13 type ProtocolResponse,
14 type ProtocolVersion,
15 type RequestPayload,
16 ResponseStatus,
17 type UIServerConfiguration,
18 } from '../../types';
19 import {
20 Constants,
21 generateUUID,
22 isNotEmptyString,
23 isNullOrUndefined,
24 logPrefix,
25 logger,
26 } from '../../utils';
27
28 const moduleName = 'UIHttpServer';
29
30 enum HttpMethods {
31 GET = 'GET',
32 PUT = 'PUT',
33 POST = 'POST',
34 PATCH = 'PATCH',
35 }
36
37 export class UIHttpServer extends AbstractUIServer {
38 public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) {
39 super(uiServerConfiguration);
40 }
41
42 public start(): void {
43 this.httpServer.on('request', this.requestListener.bind(this) as RequestListener);
44 this.startHttpServer();
45 }
46
47 public sendRequest(request: ProtocolRequest): void {
48 switch (this.uiServerConfiguration.version) {
49 case ApplicationProtocolVersion.VERSION_20:
50 this.httpServer.emit('request', request);
51 break;
52 }
53 }
54
55 public sendResponse(response: ProtocolResponse): void {
56 const [uuid, payload] = response;
57 try {
58 if (this.hasResponseHandler(uuid) === true) {
59 const res = this.responseHandlers.get(uuid) as ServerResponse;
60 res
61 .writeHead(this.responseStatusToStatusCode(payload.status), {
62 'Content-Type': 'application/json',
63 })
64 .end(JSON.stringify(payload));
65 } else {
66 logger.error(
67 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`,
68 );
69 }
70 } catch (error) {
71 logger.error(
72 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
73 error,
74 );
75 } finally {
76 this.responseHandlers.delete(uuid);
77 }
78 }
79
80 public logPrefix = (modName?: string, methodName?: string, prefixSuffix?: string): string => {
81 const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
82 const logMsg =
83 isNotEmptyString(modName) && isNotEmptyString(methodName)
84 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
85 : ` ${logMsgPrefix} |`;
86 return logPrefix(logMsg);
87 };
88
89 private requestListener(req: IncomingMessage, res: ServerResponse): void {
90 this.authenticate(req, (err) => {
91 if (err) {
92 res
93 .writeHead(StatusCodes.UNAUTHORIZED, {
94 'Content-Type': 'text/plain',
95 'WWW-Authenticate': 'Basic realm=users',
96 })
97 .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`)
98 .destroy();
99 req.destroy();
100 }
101 });
102 // Expected request URL pathname: /ui/:version/:procedureName
103 const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [
104 Protocol,
105 ProtocolVersion,
106 ProcedureName,
107 ];
108 const uuid = generateUUID();
109 this.responseHandlers.set(uuid, res);
110 try {
111 const fullProtocol = `${protocol}${version}`;
112 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === false) {
113 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
114 }
115 this.registerProtocolVersionUIService(version);
116 req.on('error', (error) => {
117 logger.error(
118 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
119 error,
120 );
121 });
122 if (req.method === HttpMethods.POST) {
123 const bodyBuffer: Uint8Array[] = [];
124 req
125 .on('data', (chunk: Uint8Array) => {
126 bodyBuffer.push(chunk);
127 })
128 .on('end', () => {
129 const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
130 this.uiServices
131 .get(version)
132 ?.requestHandler(
133 this.buildProtocolRequest(
134 uuid,
135 procedureName,
136 body ?? Constants.EMPTY_FREEZED_OBJECT,
137 ),
138 )
139 .then((protocolResponse?: ProtocolResponse) => {
140 if (!isNullOrUndefined(protocolResponse)) {
141 this.sendResponse(protocolResponse!);
142 }
143 })
144 .catch(Constants.EMPTY_FUNCTION);
145 });
146 } else {
147 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
148 }
149 } catch (error) {
150 logger.error(
151 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
152 error,
153 );
154 this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }));
155 }
156 }
157
158 private responseStatusToStatusCode(status: ResponseStatus): StatusCodes {
159 switch (status) {
160 case ResponseStatus.SUCCESS:
161 return StatusCodes.OK;
162 case ResponseStatus.FAILURE:
163 return StatusCodes.BAD_REQUEST;
164 default:
165 return StatusCodes.INTERNAL_SERVER_ERROR;
166 }
167 }
168 }