UI protocol: update Insomnia requests collection
[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 BaseError from '../../exception/BaseError';
6 import type { UIServerConfiguration } from '../../types/ConfigurationData';
7 import {
8 ProcedureName,
9 Protocol,
10 ProtocolRequest,
11 ProtocolResponse,
12 ProtocolVersion,
13 RequestPayload,
14 ResponseStatus,
15 } from '../../types/UIProtocol';
16 import logger from '../../utils/Logger';
17 import Utils from '../../utils/Utils';
18 import { AbstractUIServer } from './AbstractUIServer';
19 import { UIServiceUtils } from './ui-services/UIServiceUtils';
20
21 const moduleName = 'UIHttpServer';
22
23 export default 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 if (this.httpServer.listening === false) {
31 this.httpServer.listen(this.uiServerConfiguration.options);
32 }
33 }
34
35 // eslint-disable-next-line @typescript-eslint/no-unused-vars
36 public sendRequest(request: ProtocolRequest): void {
37 // This is intentionally left blank
38 }
39
40 public sendResponse(response: ProtocolResponse): void {
41 const [uuid, payload] = response;
42 if (this.responseHandlers.has(uuid) === true) {
43 const res = this.responseHandlers.get(uuid) as ServerResponse;
44 res.writeHead(this.responseStatusToStatusCode(payload.status), {
45 'Content-Type': 'application/json',
46 });
47 res.end(JSON.stringify(payload));
48 this.responseHandlers.delete(uuid);
49 } else {
50 logger.error(
51 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
52 );
53 }
54 }
55
56 public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string {
57 const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
58 const logMsg =
59 modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
60 return Utils.logPrefix(logMsg);
61 }
62
63 private requestListener(req: IncomingMessage, res: ServerResponse): void {
64 this.authenticate(req, (err) => {
65 if (err) {
66 res.setHeader('Content-Type', 'text/plain');
67 res.setHeader('WWW-Authenticate', 'Basic realm=users');
68 res.writeHead(StatusCodes.UNAUTHORIZED);
69 res.end(`${StatusCodes.UNAUTHORIZED} Unauthorized`);
70 req.destroy();
71 res.destroy();
72 }
73 });
74 // Expected request URL pathname: /ui/:version/:procedureName
75 const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [
76 Protocol,
77 ProtocolVersion,
78 ProcedureName
79 ];
80 const uuid = Utils.generateUUID();
81 this.responseHandlers.set(uuid, res);
82 try {
83 if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) {
84 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
85 }
86 this.registerProtocolVersionUIService(version);
87 req.on('error', (error) => {
88 logger.error(
89 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
90 error
91 );
92 });
93 if (req.method === 'POST') {
94 const bodyBuffer = [];
95 req
96 .on('data', (chunk) => {
97 bodyBuffer.push(chunk);
98 })
99 .on('end', () => {
100 const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
101 this.uiServices
102 .get(version)
103 .requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
104 .catch(() => {
105 this.sendResponse(
106 this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE })
107 );
108 });
109 });
110 } else {
111 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
112 }
113 } catch (error) {
114 logger.error(
115 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
116 error
117 );
118 this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }));
119 }
120 }
121
122 private responseStatusToStatusCode(status: ResponseStatus): StatusCodes {
123 switch (status) {
124 case ResponseStatus.SUCCESS:
125 return StatusCodes.OK;
126 case ResponseStatus.FAILURE:
127 return StatusCodes.BAD_REQUEST;
128 default:
129 return StatusCodes.INTERNAL_SERVER_ERROR;
130 }
131 }
132 }