1 import type { IncomingMessage
, RequestListener
, ServerResponse
} from
'http';
3 import { StatusCodes
} from
'http-status-codes';
5 import BaseError from
'../../exception/BaseError';
6 import type { UIServerConfiguration
} from
'../../types/ConfigurationData';
15 } from
'../../types/UIProtocol';
16 import logger from
'../../utils/Logger';
17 import Utils from
'../../utils/Utils';
18 import { AbstractUIServer
} from
'./AbstractUIServer';
19 import { UIServiceUtils
} from
'./ui-services/UIServiceUtils';
21 const moduleName
= 'UIHttpServer';
23 export default class UIHttpServer
extends AbstractUIServer
{
24 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
25 super(uiServerConfiguration
);
28 public start(): void {
29 this.httpServer
.on('request', this.requestListener
.bind(this) as RequestListener
);
30 if (this.httpServer
.listening
=== false) {
31 this.httpServer
.listen(this.uiServerConfiguration
.options
);
35 // eslint-disable-next-line @typescript-eslint/no-unused-vars
36 public sendRequest(request
: ProtocolRequest
): void {
37 // This is intentionally left blank
40 public sendResponse(response
: ProtocolResponse
): void {
41 const [uuid
, payload
] = response
;
43 if (this.responseHandlers
.has(uuid
) === true) {
44 const res
= this.responseHandlers
.get(uuid
) as ServerResponse
;
46 .writeHead(this.responseStatusToStatusCode(payload
.status), {
47 'Content-Type': 'application/json',
49 .end(JSON
.stringify(payload
));
52 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
57 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
61 this.responseHandlers
.delete(uuid
);
65 public logPrefix(modName
?: string, methodName
?: string, prefixSuffix
?: string): string {
66 const logMsgPrefix
= prefixSuffix
? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
68 modName
&& methodName
? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
69 return Utils
.logPrefix(logMsg
);
72 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
73 this.authenticate(req
, (err
) => {
76 .writeHead(StatusCodes
.UNAUTHORIZED
, {
77 'Content-Type': 'text/plain',
78 'WWW-Authenticate': 'Basic realm=users',
80 .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`)
85 // Expected request URL pathname: /ui/:version/:procedureName
86 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
91 const uuid
= Utils
.generateUUID();
92 this.responseHandlers
.set(uuid
, res
);
94 if (UIServiceUtils
.isProtocolAndVersionSupported(protocol
, version
) === false) {
95 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
97 this.registerProtocolVersionUIService(version
);
98 req
.on('error', (error
) => {
100 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
104 if (req
.method
=== 'POST') {
105 const bodyBuffer
= [];
107 .on('data', (chunk
) => {
108 bodyBuffer
.push(chunk
);
111 const body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
114 .requestHandler(this.buildProtocolRequest(uuid
, procedureName
, body
?? {}))
116 /* Error caught by AbstractUIService */
120 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
124 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
127 this.sendResponse(this.buildProtocolResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
131 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
133 case ResponseStatus
.SUCCESS
:
134 return StatusCodes
.OK
;
135 case ResponseStatus
.FAILURE
:
136 return StatusCodes
.BAD_REQUEST
;
138 return StatusCodes
.INTERNAL_SERVER_ERROR
;