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 type responseHandler
= { procedureName
: ProcedureName
; res
: ServerResponse
};
25 export default class UIHttpServer
extends AbstractUIServer
{
26 private readonly responseHandlers
: Map
<string, responseHandler
>;
28 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
29 super(uiServerConfiguration
);
30 this.responseHandlers
= new Map
<string, responseHandler
>();
33 public start(): void {
34 this.httpServer
.on('connection', (socket
) => {
35 this.sockets
.add(socket
);
36 socket
.on('close', () => {
37 this.sockets
.delete(socket
);
40 this.httpServer
.on('request', this.requestListener
.bind(this) as RequestListener
);
41 if (this.httpServer
.listening
=== false) {
42 this.httpServer
.listen(this.uiServerConfiguration
.options
);
46 // eslint-disable-next-line @typescript-eslint/no-unused-vars
47 public sendRequest(request
: ProtocolRequest
): void {
48 // This is intentionally left blank
51 public sendResponse(response
: ProtocolResponse
): void {
52 const [uuid
, payload
] = response
;
53 if (this.responseHandlers
.has(uuid
) === true) {
54 const { res
} = this.responseHandlers
.get(uuid
);
55 res
.writeHead(this.responseStatusToStatusCode(payload
.status), {
56 'Content-Type': 'application/json',
58 res
.end(JSON
.stringify(payload
));
59 this.responseHandlers
.delete(uuid
);
62 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
67 public logPrefix(modName
?: string, methodName
?: string, prefixSuffix
?: string): string {
68 const logMsgPrefix
= prefixSuffix
? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
70 modName
&& methodName
? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
71 return Utils
.logPrefix(logMsg
);
74 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
75 if (this.authenticate(req
) === false) {
76 res
.setHeader('Content-Type', 'text/plain');
77 res
.setHeader('WWW-Authenticate', 'Basic realm=users');
78 res
.writeHead(StatusCodes
.UNAUTHORIZED
);
79 res
.end(`${StatusCodes.UNAUTHORIZED} Unauthorized`);
82 // Expected request URL pathname: /ui/:version/:procedureName
83 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
88 const uuid
= Utils
.generateUUID();
89 this.responseHandlers
.set(uuid
, { procedureName
, res
});
91 if (UIServiceUtils
.isProtocolAndVersionSupported(protocol
, version
) === false) {
92 throw new BaseError(`Unsupported UI protocol version: '/${protocol}/${version}'`);
94 this.registerProtocolVersionUIService(version
);
95 req
.on('error', (error
) => {
97 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
101 if (req
.method
=== 'POST') {
102 const bodyBuffer
= [];
104 .on('data', (chunk
) => {
105 bodyBuffer
.push(chunk
);
108 const body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
111 .requestHandler(this.buildProtocolRequest(uuid
, procedureName
, body
?? {}))
114 this.buildProtocolResponse(uuid
, { status: ResponseStatus
.FAILURE
})
119 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
123 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
126 this.sendResponse(this.buildProtocolResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
130 private authenticate(req
: IncomingMessage
): boolean {
131 if (this.isBasicAuthEnabled() === true) {
132 if (this.isValidBasicAuth(req
) === true) {
140 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
142 case ResponseStatus
.SUCCESS
:
143 return StatusCodes
.OK
;
144 case ResponseStatus
.FAILURE
:
145 return StatusCodes
.BAD_REQUEST
;
147 return StatusCodes
.INTERNAL_SERVER_ERROR
;