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