perf: 'await' on UI request handlers only when necessary
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
1 import { BaseError, type OCPPError } from '../../../exception/index.js'
2 import {
3 BroadcastChannelProcedureName,
4 type BroadcastChannelRequestPayload,
5 type JsonType,
6 ProcedureName,
7 type ProtocolRequest,
8 type ProtocolRequestHandler,
9 type ProtocolResponse,
10 type ProtocolVersion,
11 type RequestPayload,
12 type ResponsePayload,
13 ResponseStatus
14 } from '../../../types/index.js'
15 import { isAsyncFunction, isNotEmptyArray, logger } from '../../../utils/index.js'
16 import { Bootstrap } from '../../Bootstrap.js'
17 import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel.js'
18 import type { AbstractUIServer } from '../AbstractUIServer.js'
19
20 const moduleName = 'AbstractUIService'
21
22 export abstract class AbstractUIService {
23 protected static readonly ProcedureNameToBroadCastChannelProcedureNameMapping = new Map<
24 ProcedureName,
25 BroadcastChannelProcedureName
26 >([
27 [ProcedureName.START_CHARGING_STATION, BroadcastChannelProcedureName.START_CHARGING_STATION],
28 [ProcedureName.STOP_CHARGING_STATION, BroadcastChannelProcedureName.STOP_CHARGING_STATION],
29 [ProcedureName.CLOSE_CONNECTION, BroadcastChannelProcedureName.CLOSE_CONNECTION],
30 [ProcedureName.OPEN_CONNECTION, BroadcastChannelProcedureName.OPEN_CONNECTION],
31 [
32 ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
33 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR
34 ],
35 [
36 ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
37 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR
38 ],
39 [ProcedureName.SET_SUPERVISION_URL, BroadcastChannelProcedureName.SET_SUPERVISION_URL],
40 [ProcedureName.START_TRANSACTION, BroadcastChannelProcedureName.START_TRANSACTION],
41 [ProcedureName.STOP_TRANSACTION, BroadcastChannelProcedureName.STOP_TRANSACTION],
42 [ProcedureName.AUTHORIZE, BroadcastChannelProcedureName.AUTHORIZE],
43 [ProcedureName.BOOT_NOTIFICATION, BroadcastChannelProcedureName.BOOT_NOTIFICATION],
44 [ProcedureName.STATUS_NOTIFICATION, BroadcastChannelProcedureName.STATUS_NOTIFICATION],
45 [ProcedureName.HEARTBEAT, BroadcastChannelProcedureName.HEARTBEAT],
46 [ProcedureName.METER_VALUES, BroadcastChannelProcedureName.METER_VALUES],
47 [ProcedureName.DATA_TRANSFER, BroadcastChannelProcedureName.DATA_TRANSFER],
48 [
49 ProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION,
50 BroadcastChannelProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION
51 ],
52 [
53 ProcedureName.FIRMWARE_STATUS_NOTIFICATION,
54 BroadcastChannelProcedureName.FIRMWARE_STATUS_NOTIFICATION
55 ]
56 ])
57
58 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>
59 private readonly version: ProtocolVersion
60 private readonly uiServer: AbstractUIServer
61 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel
62 private readonly broadcastChannelRequests: Map<string, number>
63
64 constructor (uiServer: AbstractUIServer, version: ProtocolVersion) {
65 this.uiServer = uiServer
66 this.version = version
67 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
68 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
69 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
70 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)]
71 ])
72 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this)
73 this.broadcastChannelRequests = new Map<string, number>()
74 }
75
76 public async requestHandler (request: ProtocolRequest): Promise<ProtocolResponse | undefined> {
77 let messageId: string | undefined
78 let command: ProcedureName | undefined
79 let requestPayload: RequestPayload | undefined
80 let responsePayload: ResponsePayload | undefined
81 try {
82 [messageId, command, requestPayload] = request
83
84 if (!this.requestHandlers.has(command)) {
85 throw new BaseError(
86 `${command} is not implemented to handle message payload ${JSON.stringify(
87 requestPayload,
88 undefined,
89 2
90 )}`
91 )
92 }
93
94 // Call the request handler to build the response payload
95 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
96 const requestHandler = this.requestHandlers.get(command)!
97 if (isAsyncFunction(requestHandler)) {
98 responsePayload = await requestHandler(messageId, command, requestPayload)
99 } else {
100 responsePayload = (
101 requestHandler as (
102 uuid?: string,
103 procedureName?: ProcedureName,
104 payload?: RequestPayload
105 ) => undefined | ResponsePayload
106 )(messageId, command, requestPayload)
107 }
108 } catch (error) {
109 // Log
110 logger.error(`${this.logPrefix(moduleName, 'requestHandler')} Handle request error:`, error)
111 responsePayload = {
112 hashIds: requestPayload?.hashIds,
113 status: ResponseStatus.FAILURE,
114 command,
115 requestPayload,
116 responsePayload,
117 errorMessage: (error as OCPPError).message,
118 errorStack: (error as OCPPError).stack,
119 errorDetails: (error as OCPPError).details
120 }
121 }
122 if (responsePayload != null) {
123 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
124 return this.uiServer.buildProtocolResponse(messageId!, responsePayload)
125 }
126 }
127
128 // public sendRequest (
129 // messageId: string,
130 // procedureName: ProcedureName,
131 // requestPayload: RequestPayload
132 // ): void {
133 // this.uiServer.sendRequest(
134 // this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
135 // )
136 // }
137
138 public sendResponse (messageId: string, responsePayload: ResponsePayload): void {
139 if (this.uiServer.hasResponseHandler(messageId)) {
140 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload))
141 }
142 }
143
144 public logPrefix = (modName: string, methodName: string): string => {
145 return this.uiServer.logPrefix(modName, methodName, this.version)
146 }
147
148 public deleteBroadcastChannelRequest (uuid: string): void {
149 this.broadcastChannelRequests.delete(uuid)
150 }
151
152 public getBroadcastChannelExpectedResponses (uuid: string): number {
153 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
154 return this.broadcastChannelRequests.get(uuid)!
155 }
156
157 protected handleProtocolRequest (
158 uuid: string,
159 procedureName: ProcedureName,
160 payload: RequestPayload
161 ): void {
162 this.sendBroadcastChannelRequest(
163 uuid,
164 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
165 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping.get(procedureName)!,
166 payload
167 )
168 }
169
170 private sendBroadcastChannelRequest (
171 uuid: string,
172 procedureName: BroadcastChannelProcedureName,
173 payload: BroadcastChannelRequestPayload
174 ): void {
175 if (isNotEmptyArray(payload.hashIds)) {
176 payload.hashIds = payload.hashIds
177 .map(hashId => {
178 if (this.uiServer.chargingStations.has(hashId)) {
179 return hashId
180 }
181 logger.warn(
182 `${this.logPrefix(
183 moduleName,
184 'sendBroadcastChannelRequest'
185 )} Charging station with hashId '${hashId}' not found`
186 )
187 return undefined
188 })
189 .filter(hashId => hashId != null) as string[]
190 } else {
191 delete payload.hashIds
192 }
193 const expectedNumberOfResponses = Array.isArray(payload.hashIds)
194 ? payload.hashIds.length
195 : this.uiServer.chargingStations.size
196 if (expectedNumberOfResponses === 0) {
197 throw new BaseError(
198 'hashIds array in the request payload does not contain any valid charging station hashId'
199 )
200 }
201 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload])
202 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses)
203 }
204
205 private handleListChargingStations (): ResponsePayload {
206 return {
207 status: ResponseStatus.SUCCESS,
208 chargingStations: [...this.uiServer.chargingStations.values()] as JsonType[]
209 } satisfies ResponsePayload
210 }
211
212 private async handleStartSimulator (): Promise<ResponsePayload> {
213 try {
214 await Bootstrap.getInstance().start()
215 return { status: ResponseStatus.SUCCESS }
216 } catch {
217 return { status: ResponseStatus.FAILURE }
218 }
219 }
220
221 private async handleStopSimulator (): Promise<ResponsePayload> {
222 try {
223 await Bootstrap.getInstance().stop()
224 return { status: ResponseStatus.SUCCESS }
225 } catch {
226 return { status: ResponseStatus.FAILURE }
227 }
228 }
229 }