| 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 | res.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 | let requestPayload: RequestPayload | undefined |
| 130 | try { |
| 131 | requestPayload = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload |
| 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 | } |
| 142 | this.uiServices |
| 143 | .get(version) |
| 144 | ?.requestHandler(this.buildProtocolRequest(uuid, procedureName, requestPayload)) |
| 145 | .then((protocolResponse?: ProtocolResponse) => { |
| 146 | if (protocolResponse != null) { |
| 147 | this.sendResponse(protocolResponse) |
| 148 | } |
| 149 | }) |
| 150 | .catch(Constants.EMPTY_FUNCTION) |
| 151 | }) |
| 152 | } else { |
| 153 | throw new BaseError(`Unsupported HTTP method: '${req.method}'`) |
| 154 | } |
| 155 | } catch (error) { |
| 156 | logger.error( |
| 157 | `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`, |
| 158 | error |
| 159 | ) |
| 160 | this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE })) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | private responseStatusToStatusCode (status: ResponseStatus): StatusCodes { |
| 165 | switch (status) { |
| 166 | case ResponseStatus.SUCCESS: |
| 167 | return StatusCodes.OK |
| 168 | case ResponseStatus.FAILURE: |
| 169 | return StatusCodes.BAD_REQUEST |
| 170 | default: |
| 171 | return StatusCodes.INTERNAL_SERVER_ERROR |
| 172 | } |
| 173 | } |
| 174 | } |