Commit | Line | Data |
---|---|---|
01f4001e | 1 | import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http'; |
1f7fa4de | 2 | |
a0202edc | 3 | import { StatusCodes } from 'http-status-codes'; |
1f7fa4de | 4 | |
4c3c0d59 JB |
5 | import { AbstractUIServer } from './AbstractUIServer'; |
6 | import { UIServerUtils } from './UIServerUtils'; | |
268a74bb | 7 | import { BaseError } from '../../exception'; |
1f7fa4de | 8 | import { |
e0b0ee21 JB |
9 | type ProcedureName, |
10 | type Protocol, | |
11 | type ProtocolRequest, | |
12 | type ProtocolResponse, | |
13 | type ProtocolVersion, | |
14 | type RequestPayload, | |
1f7fa4de | 15 | ResponseStatus, |
268a74bb JB |
16 | type UIServerConfiguration, |
17 | } from '../../types'; | |
59b6ed8d | 18 | import { Constants, Utils, logger } from '../../utils'; |
1f7fa4de JB |
19 | |
20 | const moduleName = 'UIHttpServer'; | |
21 | ||
1185579a JB |
22 | enum HttpMethods { |
23 | GET = 'GET', | |
24 | PUT = 'PUT', | |
25 | POST = 'POST', | |
26 | PATCH = 'PATCH', | |
27 | } | |
28 | ||
268a74bb | 29 | export class UIHttpServer extends AbstractUIServer { |
eb3abc4f JB |
30 | public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) { |
31 | super(uiServerConfiguration); | |
1f7fa4de JB |
32 | } |
33 | ||
34 | public start(): void { | |
daa6505e | 35 | this.httpServer.on('request', this.requestListener.bind(this) as RequestListener); |
a307349b | 36 | this.startHttpServer(); |
1f7fa4de JB |
37 | } |
38 | ||
1f7fa4de | 39 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
5e3cb728 | 40 | public sendRequest(request: ProtocolRequest): void { |
1f7fa4de JB |
41 | // This is intentionally left blank |
42 | } | |
43 | ||
5e3cb728 JB |
44 | public sendResponse(response: ProtocolResponse): void { |
45 | const [uuid, payload] = response; | |
976d11ec JB |
46 | try { |
47 | if (this.responseHandlers.has(uuid) === true) { | |
48 | const res = this.responseHandlers.get(uuid) as ServerResponse; | |
b2e2c274 JB |
49 | res |
50 | .writeHead(this.responseStatusToStatusCode(payload.status), { | |
51 | 'Content-Type': 'application/json', | |
52 | }) | |
53 | .end(JSON.stringify(payload)); | |
976d11ec JB |
54 | } else { |
55 | logger.error( | |
56 | `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}` | |
57 | ); | |
58 | } | |
59 | } catch (error) { | |
1f7fa4de | 60 | logger.error( |
976d11ec JB |
61 | `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`, |
62 | error | |
1f7fa4de | 63 | ); |
e2c77f10 JB |
64 | } finally { |
65 | this.responseHandlers.delete(uuid); | |
1f7fa4de JB |
66 | } |
67 | } | |
68 | ||
8b7072dc | 69 | public logPrefix = (modName?: string, methodName?: string, prefixSuffix?: string): string => { |
0d2cec76 | 70 | const logMsgPrefix = prefixSuffix ? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server'; |
1f7fa4de | 71 | const logMsg = |
5a2a53cf | 72 | Utils.isNotEmptyString(modName) && Utils.isNotEmptyString(methodName) |
1b271a54 JB |
73 | ? ` ${logMsgPrefix} | ${modName}.${methodName}:` |
74 | : ` ${logMsgPrefix} |`; | |
1f7fa4de | 75 | return Utils.logPrefix(logMsg); |
8b7072dc | 76 | }; |
1f7fa4de JB |
77 | |
78 | private requestListener(req: IncomingMessage, res: ServerResponse): void { | |
72092cfc | 79 | this.authenticate(req, (err) => { |
623b39b5 | 80 | if (err) { |
b2e2c274 JB |
81 | res |
82 | .writeHead(StatusCodes.UNAUTHORIZED, { | |
83 | 'Content-Type': 'text/plain', | |
84 | 'WWW-Authenticate': 'Basic realm=users', | |
85 | }) | |
86 | .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`) | |
87 | .destroy(); | |
623b39b5 | 88 | req.destroy(); |
623b39b5 JB |
89 | } |
90 | }); | |
1f7fa4de JB |
91 | // Expected request URL pathname: /ui/:version/:procedureName |
92 | const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [ | |
93 | Protocol, | |
94 | ProtocolVersion, | |
95 | ProcedureName | |
96 | ]; | |
97 | const uuid = Utils.generateUUID(); | |
94dc3080 | 98 | this.responseHandlers.set(uuid, res); |
1f7fa4de | 99 | try { |
7cb5b17f | 100 | const fullProtocol = `${protocol}${version}`; |
ed3d2808 | 101 | if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol) === false) { |
7cb5b17f | 102 | throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`); |
1f7fa4de | 103 | } |
daa6505e | 104 | this.registerProtocolVersionUIService(version); |
72092cfc | 105 | req.on('error', (error) => { |
1f7fa4de | 106 | logger.error( |
a745e412 | 107 | `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`, |
1f7fa4de JB |
108 | error |
109 | ); | |
110 | }); | |
1185579a | 111 | if (req.method === HttpMethods.POST) { |
1f7fa4de | 112 | const bodyBuffer = []; |
1f7fa4de | 113 | req |
72092cfc | 114 | .on('data', (chunk) => { |
1f7fa4de JB |
115 | bodyBuffer.push(chunk); |
116 | }) | |
117 | .on('end', () => { | |
a745e412 | 118 | const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload; |
1f7fa4de JB |
119 | this.uiServices |
120 | .get(version) | |
59b6ed8d JB |
121 | ?.requestHandler( |
122 | this.buildProtocolRequest( | |
123 | uuid, | |
124 | procedureName, | |
125 | body ?? Constants.EMPTY_FREEZED_OBJECT | |
126 | ) | |
127 | ) | |
0b22144c | 128 | .then((protocolResponse: ProtocolResponse) => { |
bf4afa56 | 129 | if (!Utils.isNullOrUndefined(protocolResponse)) { |
0b22144c JB |
130 | this.sendResponse(protocolResponse); |
131 | } | |
132 | }) | |
59b6ed8d | 133 | .catch(Constants.EMPTY_FUNCTION); |
1f7fa4de JB |
134 | }); |
135 | } else { | |
136 | throw new BaseError(`Unsupported HTTP method: '${req.method}'`); | |
137 | } | |
138 | } catch (error) { | |
a745e412 JB |
139 | logger.error( |
140 | `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`, | |
141 | error | |
142 | ); | |
852a4c5f | 143 | this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE })); |
1f7fa4de JB |
144 | } |
145 | } | |
146 | ||
771633ff JB |
147 | private responseStatusToStatusCode(status: ResponseStatus): StatusCodes { |
148 | switch (status) { | |
149 | case ResponseStatus.SUCCESS: | |
150 | return StatusCodes.OK; | |
151 | case ResponseStatus.FAILURE: | |
152 | return StatusCodes.BAD_REQUEST; | |
153 | default: | |
154 | return StatusCodes.INTERNAL_SERVER_ERROR; | |
155 | } | |
156 | } | |
1f7fa4de | 157 | } |