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