ccafb0845df0307a2577e34b68f5d4e8742ff18f
1 import type { IncomingMessage
, RequestListener
, ServerResponse
} from
'node:http';
3 import { StatusCodes
} from
'http-status-codes';
5 import { AbstractUIServer
} from
'./AbstractUIServer';
6 import { UIServerUtils
} from
'./UIServerUtils';
7 import { BaseError
} from
'../../exception';
12 type ProtocolResponse
,
16 type UIServerConfiguration
,
18 import { Constants
, Utils
, logger
} from
'../../utils';
20 const moduleName
= 'UIHttpServer';
29 export class UIHttpServer
extends AbstractUIServer
{
30 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
31 super(uiServerConfiguration
);
34 public start(): void {
35 this.httpServer
.on('request', this.requestListener
.bind(this) as RequestListener
);
36 this.startHttpServer();
39 // eslint-disable-next-line @typescript-eslint/no-unused-vars
40 public sendRequest(request
: ProtocolRequest
): void {
41 // This is intentionally left blank
44 public sendResponse(response
: ProtocolResponse
): void {
45 const [uuid
, payload
] = response
;
47 if (this.responseHandlers
.has(uuid
) === true) {
48 const res
= this.responseHandlers
.get(uuid
) as ServerResponse
;
50 .writeHead(this.responseStatusToStatusCode(payload
.status), {
51 'Content-Type': 'application/json',
53 .end(JSON
.stringify(payload
));
56 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
61 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
65 this.responseHandlers
.delete(uuid
);
69 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
70 const logMsgPrefix
= prefixSuffix
? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
72 Utils
.isNotEmptyString(modName
) && Utils
.isNotEmptyString(methodName
)
73 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
74 : ` ${logMsgPrefix} |`;
75 return Utils
.logPrefix(logMsg
);
78 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
79 this.authenticate(req
, (err
) => {
82 .writeHead(StatusCodes
.UNAUTHORIZED
, {
83 'Content-Type': 'text/plain',
84 'WWW-Authenticate': 'Basic realm=users',
86 .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`)
91 // Expected request URL pathname: /ui/:version/:procedureName
92 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
97 const uuid
= Utils
.generateUUID();
98 this.responseHandlers
.set(uuid
, res
);
100 const fullProtocol
= `${protocol}${version}`;
101 if (UIServerUtils
.isProtocolAndVersionSupported(fullProtocol
) === false) {
102 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
104 this.registerProtocolVersionUIService(version
);
105 req
.on('error', (error
) => {
107 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
111 if (req
.method
=== HttpMethods
.POST
) {
112 const bodyBuffer
= [];
114 .on('data', (chunk
) => {
115 bodyBuffer
.push(chunk
);
118 const body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
122 this.buildProtocolRequest(
125 body
?? Constants
.EMPTY_FREEZED_OBJECT
128 .then((protocolResponse
: ProtocolResponse
) => {
129 if (!Utils
.isNullOrUndefined(protocolResponse
)) {
130 this.sendResponse(protocolResponse
);
133 .catch(Constants
.EMPTY_FUNCTION
);
136 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
140 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
143 this.sendResponse(this.buildProtocolResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
147 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
149 case ResponseStatus
.SUCCESS
:
150 return StatusCodes
.OK
;
151 case ResponseStatus
.FAILURE
:
152 return StatusCodes
.BAD_REQUEST
;
154 return StatusCodes
.INTERNAL_SERVER_ERROR
;