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