import { IMessage } from "../../interfaces/core/IMessage"; import { IMessageQueueAPI } from "../../interfaces/core/IMessageQueueAPI"; import { IMessageRunner } from "../../interfaces/core/IMessageRunner"; import { IPayloadFetcher } from "../../interfaces/core/IPayloadFetcher"; import { IPayloadPoster } from "../../interfaces/core/IPayloadPoster"; import { IService } from "../../interfaces/core/IService"; export class MessageRunner implements IMessageRunner { services: IService[]; payloadFetcher: IPayloadFetcher; payloadPoster: IPayloadPoster; constructor({ service, payloadFetcher, payloadPoster }: { service: IService[], payloadFetcher: IPayloadFetcher, payloadPoster: IPayloadPoster, }) { this.services = service; this.payloadFetcher = payloadFetcher; this.payloadPoster = payloadPoster; } run = async ({ message, messageQueueAPI }: { message: IMessage, messageQueueAPI: IMessageQueueAPI }): Promise => { const startTime = Date.now(); // Tìm service phù hợp để xử lý message const foundService = this.services.find(service => service.messageType == message.messageType); if (!foundService) { throw new Error(`Không tìm thấy service phù hợp để xử lý messageType ${message.messageType}`); } try { // Đặt timeout cho message processing const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error(`Processing timeout after ${message.timeoutMs}ms`)), message.timeoutMs) ); const processingPromise = foundService.handle({ message, payloadFetcher: this.payloadFetcher, payloadPoster: this.payloadPoster, messageQueueAPI, }); // Race giữa processing và timeout await Promise.race([processingPromise, timeoutPromise]); console.log(`[${message.requestId}] Message ${message.messageId} processed successfully in ${Date.now() - startTime}ms`); } catch (error: any) { const elapsedTime = Date.now() - startTime; const isTimeout = elapsedTime >= message.timeoutMs; console.error(`[${message.requestId}] Message ${message.messageId} failed after ${elapsedTime}ms:`, error.message); if (isTimeout) { throw new Error(`[${message.requestId}] Message ${message.messageId} timed out after ${message.timeoutMs}ms`); } else { // Lỗi khác - để foundService.handle xử lý throw error; } } } }