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