]> Piment Noir Git Repositories - e-mobility-charging-stations-simulator.git/blame - src/charging-station/ui-server/UIHttpServer.ts
chore(deps-dev): apply updates
[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,
d1f5bfd8 16 type UIServerConfiguration,
66a7748d 17} from '../../types/index.js'
a66bbcfe
JB
18import {
19 Constants,
a66bbcfe
JB
20 generateUUID,
21 isNotEmptyString,
276e05ae 22 JSONStringify,
4c3f6c20 23 logger,
d1f5bfd8 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',
0749233f 33 PATCH = 'PATCH',
1185579a 34 POST = 'POST',
271426fb 35 PUT = 'PUT',
1185579a
JB
36}
37
268a74bb 38export class UIHttpServer extends AbstractUIServer {
c4a89082
JB
39 public constructor (protected override readonly uiServerConfiguration: UIServerConfiguration) {
40 super(uiServerConfiguration)
41 }
42
8b7072dc 43 public logPrefix = (modName?: string, methodName?: string, prefixSuffix?: string): string => {
66a7748d 44 const logMsgPrefix = prefixSuffix != null ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server'
1f7fa4de 45 const logMsg =
9bf0ef23 46 isNotEmptyString(modName) && isNotEmptyString(methodName)
1b271a54 47 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
66a7748d
JB
48 : ` ${logMsgPrefix} |`
49 return logPrefix(logMsg)
50 }
1f7fa4de 51
c4a89082
JB
52 public sendRequest (request: ProtocolRequest): void {
53 switch (this.uiServerConfiguration.version) {
54 case ApplicationProtocolVersion.VERSION_20:
55 this.httpServer.emit('request', request)
56 break
57 }
58 }
59
60 public sendResponse (response: ProtocolResponse): void {
61 const [uuid, payload] = response
62 try {
63 if (this.hasResponseHandler(uuid)) {
64 const res = this.responseHandlers.get(uuid) as ServerResponse
65 res
66 .writeHead(this.responseStatusToStatusCode(payload.status), {
67 'Content-Type': 'application/json',
68 })
69 .end(JSONStringify(payload, undefined, MapStringifyFormat.object))
70 } else {
71 logger.error(
72 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
73 )
74 }
75 } catch (error) {
76 logger.error(
77 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
78 error
79 )
80 } finally {
81 this.responseHandlers.delete(uuid)
82 }
83 }
84
85 public start (): void {
86 this.httpServer.on('request', this.requestListener.bind(this))
87 this.startHttpServer()
0749233f
JB
88 }
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',
d1f5bfd8 96 'WWW-Authenticate': 'Basic realm=users',
b2e2c274 97 })
d1f5bfd8 98 .end(`${StatusCodes.UNAUTHORIZED.toString()} 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, {
71ac2bd7 136 errorMessage: (error as Error).message,
d1f5bfd8 137 errorStack: (error as Error).stack,
0749233f 138 status: ResponseStatus.FAILURE,
71ac2bd7
JB
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 149 }
d1f5bfd8 150 return undefined
0b22144c 151 })
66a7748d
JB
152 .catch(Constants.EMPTY_FUNCTION)
153 })
1f7fa4de 154 } else {
d1f5bfd8 155 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
66a7748d 156 throw new BaseError(`Unsupported HTTP method: '${req.method}'`)
1f7fa4de
JB
157 }
158 } catch (error) {
a745e412
JB
159 logger.error(
160 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
66a7748d
JB
161 error
162 )
163 this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }))
1f7fa4de
JB
164 }
165 }
166
66a7748d 167 private responseStatusToStatusCode (status: ResponseStatus): StatusCodes {
771633ff 168 switch (status) {
771633ff 169 case ResponseStatus.FAILURE:
66a7748d 170 return StatusCodes.BAD_REQUEST
0749233f
JB
171 case ResponseStatus.SUCCESS:
172 return StatusCodes.OK
771633ff 173 default:
66a7748d 174 return StatusCodes.INTERNAL_SERVER_ERROR
771633ff
JB
175 }
176 }
1f7fa4de 177}