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
,
27 const moduleName
= 'UIHttpServer';
36 export class UIHttpServer
extends AbstractUIServer
{
37 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
38 super(uiServerConfiguration
);
41 public start(): void {
42 this.httpServer
.on('request', this.requestListener
.bind(this) as RequestListener
);
43 this.startHttpServer();
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
;
54 if (this.hasResponseHandler(uuid
) === true) {
55 const res
= this.responseHandlers
.get(uuid
) as ServerResponse
;
57 .writeHead(this.responseStatusToStatusCode(payload
.status), {
58 'Content-Type': 'application/json',
60 .end(JSON
.stringify(payload
));
63 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`,
68 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
72 this.responseHandlers
.delete(uuid
);
76 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
77 const logMsgPrefix
= prefixSuffix
? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
79 isNotEmptyString(modName
) && isNotEmptyString(methodName
)
80 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
81 : ` ${logMsgPrefix} |`;
82 return logPrefix(logMsg
);
85 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
86 this.authenticate(req
, (err
) => {
89 .writeHead(StatusCodes
.UNAUTHORIZED
, {
90 'Content-Type': 'text/plain',
91 'WWW-Authenticate': 'Basic realm=users',
93 .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`)
98 // Expected request URL pathname: /ui/:version/:procedureName
99 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
104 const uuid
= generateUUID();
105 this.responseHandlers
.set(uuid
, res
);
107 const fullProtocol
= `${protocol}${version}`;
108 if (UIServerUtils
.isProtocolAndVersionSupported(fullProtocol
) === false) {
109 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
111 this.registerProtocolVersionUIService(version
);
112 req
.on('error', (error
) => {
114 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
118 if (req
.method
=== HttpMethods
.POST
) {
119 const bodyBuffer
= [];
121 .on('data', (chunk
) => {
122 bodyBuffer
.push(chunk
);
125 const body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
129 this.buildProtocolRequest(
132 body
?? Constants
.EMPTY_FREEZED_OBJECT
,
135 .then((protocolResponse
: ProtocolResponse
) => {
136 if (!isNullOrUndefined(protocolResponse
)) {
137 this.sendResponse(protocolResponse
);
140 .catch(Constants
.EMPTY_FUNCTION
);
143 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
147 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
150 this.sendResponse(this.buildProtocolResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
154 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
156 case ResponseStatus
.SUCCESS
:
157 return StatusCodes
.OK
;
158 case ResponseStatus
.FAILURE
:
159 return StatusCodes
.BAD_REQUEST
;
161 return StatusCodes
.INTERNAL_SERVER_ERROR
;