186669ef83e96d42c2c2fed420f2153ba4a1bfff
1 import type { IncomingMessage
, RequestListener
, ServerResponse
} from
'node:http';
3 import { StatusCodes
} from
'http-status-codes';
5 import { BaseError
} from
'../../exception';
10 type ProtocolResponse
,
14 type UIServerConfiguration
,
16 import { Utils
, logger
} from
'../../utils';
17 import { AbstractUIServer
, UIServerUtils
} from
'../internal';
19 const moduleName
= 'UIHttpServer';
28 export class UIHttpServer
extends AbstractUIServer
{
29 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
30 super(uiServerConfiguration
);
33 public start(): void {
34 this.httpServer
.on('request', this.requestListener
.bind(this) as RequestListener
);
35 this.startHttpServer();
38 // eslint-disable-next-line @typescript-eslint/no-unused-vars
39 public sendRequest(request
: ProtocolRequest
): void {
40 // This is intentionally left blank
43 public sendResponse(response
: ProtocolResponse
): void {
44 const [uuid
, payload
] = response
;
46 if (this.responseHandlers
.has(uuid
) === true) {
47 const res
= this.responseHandlers
.get(uuid
) as ServerResponse
;
49 .writeHead(this.responseStatusToStatusCode(payload
.status), {
50 'Content-Type': 'application/json',
52 .end(JSON
.stringify(payload
));
55 `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`
60 `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`,
64 this.responseHandlers
.delete(uuid
);
68 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
69 const logMsgPrefix
= prefixSuffix
? `UI HTTP Server ${prefixSuffix}` : 'UI HTTP Server';
71 Utils
.isNotEmptyString(modName
) && Utils
.isNotEmptyString(methodName
)
72 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
73 : ` ${logMsgPrefix} |`;
74 return Utils
.logPrefix(logMsg
);
77 private requestListener(req
: IncomingMessage
, res
: ServerResponse
): void {
78 this.authenticate(req
, (err
) => {
81 .writeHead(StatusCodes
.UNAUTHORIZED
, {
82 'Content-Type': 'text/plain',
83 'WWW-Authenticate': 'Basic realm=users',
85 .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`)
90 // Expected request URL pathname: /ui/:version/:procedureName
91 const [protocol
, version
, procedureName
] = req
.url
?.split('/').slice(1) as [
96 const uuid
= Utils
.generateUUID();
97 this.responseHandlers
.set(uuid
, res
);
99 const fullProtocol
= `${protocol}${version}`;
100 if (UIServerUtils
.isProtocolAndVersionSupported(fullProtocol
) === false) {
101 throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
103 this.registerProtocolVersionUIService(version
);
104 req
.on('error', (error
) => {
106 `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
110 if (req
.method
=== HttpMethods
.POST
) {
111 const bodyBuffer
= [];
113 .on('data', (chunk
) => {
114 bodyBuffer
.push(chunk
);
117 const body
= JSON
.parse(Buffer
.concat(bodyBuffer
).toString()) as RequestPayload
;
120 ?.requestHandler(this.buildProtocolRequest(uuid
, procedureName
, body
?? {}))
122 /* Error caught by AbstractUIService */
126 throw new BaseError(`Unsupported HTTP method: '${req.method}'`);
130 `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
133 this.sendResponse(this.buildProtocolResponse(uuid
, { status: ResponseStatus
.FAILURE
}));
137 private responseStatusToStatusCode(status: ResponseStatus
): StatusCodes
{
139 case ResponseStatus
.SUCCESS
:
140 return StatusCodes
.OK
;
141 case ResponseStatus
.FAILURE
:
142 return StatusCodes
.BAD_REQUEST
;
144 return StatusCodes
.INTERNAL_SERVER_ERROR
;