Spaces:
Sleeping
Sleeping
Download src/classes/core/MessageQueueAPI.ts from lamsaoganh/teamta: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/spaces/lamsaoganh/teamta/resolve/main/src/classes/core/MessageQueueAPI.ts
- Command line
-
hf download hf://spaces/lamsaoganh/teamta/src/classes/core/MessageQueueAPI.ts
-
curl -L -o MessageQueueAPI.ts https://huggingface.co/spaces/lamsaoganh/teamta/resolve/main/src/classes/core/MessageQueueAPI.ts
13.8 kB
| import axios, { AxiosResponse } from "axios"; | |
| import https from "https"; | |
| import { IMessageQueueAPI } from "../../interfaces/core/IMessageQueueAPI"; | |
| import { IMessage } from "../../interfaces/core/IMessage"; | |
| import { IWorkerRegistry } from "../../interfaces/core/IWorkerRegistry"; | |
| export class MessageQueueAPI implements IMessageQueueAPI { | |
| private apiBaseUrl: string; | |
| private apiTimeout: number; | |
| private httpsAgent: https.Agent; | |
| constructor({ apiBaseUrl, apiTimeout = 30000 }: { apiBaseUrl: string, apiTimeout?: number }) { | |
| this.apiBaseUrl = apiBaseUrl.replace(/\/$/, ''); // Remove trailing slash | |
| this.apiTimeout = apiTimeout; | |
| this.httpsAgent = new https.Agent({ rejectUnauthorized: false }); | |
| } | |
| getApiBaseUrl(): string { | |
| return this.apiBaseUrl; | |
| } | |
| setApiBaseUrl(apiBaseUrl: string): void { | |
| this.apiBaseUrl = String(apiBaseUrl || '').trim().replace(/\/$/, ''); | |
| } | |
| getPrioritizedMessagesToRun = async ({ workerRegistryData }: { workerRegistryData: IWorkerRegistry }): Promise<IMessage[]> => { | |
| // Validate required fields | |
| if (!workerRegistryData?.workerId) { | |
| throw new Error("WorkerRegistry validation failed: workerId is required"); | |
| } | |
| if (!Array.isArray(workerRegistryData.typeConfig) || workerRegistryData.typeConfig.length === 0) { | |
| throw new Error("WorkerRegistry validation failed: typeConfig must be a non-empty array"); | |
| } | |
| try { | |
| const cleanedTypeConfig = workerRegistryData.typeConfig.map(tc => { | |
| const cleaned: any = { | |
| messageType: tc.messageType, | |
| min: tc.min, | |
| max: tc.max, | |
| priority: tc.priority | |
| }; | |
| if (tc.description !== undefined) { | |
| cleaned.description = tc.description; | |
| } | |
| return cleaned; | |
| }); | |
| const requestBody = { | |
| workerRegistry: { | |
| ...workerRegistryData, | |
| lastSeen: workerRegistryData.lastSeen instanceof Date ? workerRegistryData.lastSeen.toISOString() : workerRegistryData.lastSeen, | |
| createdAt: workerRegistryData.createdAt instanceof Date ? workerRegistryData.createdAt.toISOString() : workerRegistryData.createdAt, | |
| updatedAt: workerRegistryData.updatedAt instanceof Date ? workerRegistryData.updatedAt.toISOString() : workerRegistryData.updatedAt, | |
| typeConfig: cleanedTypeConfig | |
| } | |
| }; | |
| const response: AxiosResponse<{ messages: IMessage[] }> = await axios.post( | |
| `${this.apiBaseUrl}/messages/fetch`, | |
| requestBody, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| timeout: this.apiTimeout, | |
| httpsAgent: this.httpsAgent | |
| } | |
| ); | |
| response.data.messages?.length?console.log(`Đã lấy được ${response.data.messages?.length || 0} messages từ API`):null; | |
| return response.data.messages || []; | |
| } catch (error: any) { | |
| console.error("Lỗi khi lấy messages từ API:", error.message); | |
| if (error.response) { | |
| console.error("Response status:", error.response.status); | |
| console.error("Response data:", error.response.data); | |
| } | |
| return []; | |
| } | |
| } | |
| updateMessageStatus = async ({ messageId, status, result, workerRegistry }: { messageId: string, status: string, result?: any, workerRegistry?: IWorkerRegistry }): Promise<void> => { | |
| console.log(`Đang cập nhật trạng thái message ${messageId} thành ${status}`); | |
| try { | |
| let endpoint: string; | |
| let payload: any = { | |
| messageId | |
| }; | |
| // Xác định endpoint và payload dựa trên status | |
| switch (status) { | |
| case 'processing': | |
| endpoint = '/messages/processing'; | |
| if (!workerRegistry) { | |
| console.error('workerRegistry is required for processing status; skipping update'); | |
| return; | |
| } | |
| payload.workerRegistry = workerRegistry; | |
| break; | |
| case 'done': | |
| case 'completed': | |
| endpoint = '/messages/complete'; | |
| if (!workerRegistry) { | |
| console.error('workerRegistry is required for complete status; skipping update'); | |
| return; | |
| } | |
| payload.workerRegistry = workerRegistry; | |
| if (result) { | |
| payload.result = result; | |
| } | |
| break; | |
| case 'failed': | |
| endpoint = '/messages/fail'; | |
| if (!workerRegistry) { | |
| console.error('workerRegistry is required for fail status; skipping update'); | |
| return; | |
| } | |
| payload.workerRegistry = workerRegistry; | |
| payload.errorMessage = result?.error || 'Unknown error'; | |
| break; | |
| case 'pending': | |
| endpoint = '/messages/pending'; | |
| if (!workerRegistry) { | |
| console.error('workerRegistry is required for pending status; skipping update'); | |
| return; | |
| } | |
| payload.workerRegistry = workerRegistry; | |
| break; | |
| case 'cancel': | |
| endpoint = '/messages/cancel'; | |
| // Cancel không cần workerRegistry | |
| break; | |
| default: | |
| console.error(`Unsupported status: ${status}; skipping update`); | |
| return; | |
| } | |
| await axios.post( | |
| `${this.apiBaseUrl}${endpoint}`, | |
| payload, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| timeout: this.apiTimeout, | |
| httpsAgent: this.httpsAgent | |
| } | |
| ); | |
| console.log(`Đã cập nhật trạng thái message ${messageId} thành ${status}`); | |
| } catch (error: any) { | |
| console.error(`Lỗi khi cập nhật trạng thái message ${messageId}:`, error.message); | |
| if (error.response) { | |
| console.error("Response status:", error.response.status); | |
| console.error("Response data:", error.response.data); | |
| } | |
| // Do not throw: Noah/API errors should not crash the worker loop. | |
| return; | |
| } | |
| } | |
| // Noah không hỗ trợ progress tracking, method này deprecated | |
| updateMessageProgress = async ({ messageId, progress }: { messageId: string, progress: number }): Promise<void> => { | |
| console.log(`⚠️ Progress tracking not supported by Noah API - skipping update for message ${messageId}: ${progress}%`); | |
| // Không làm gì cả vì Noah không hỗ trợ progress | |
| } | |
| updateMessageResultAndStatus = async ({ messageId, status, result, workerRegistry }: { messageId: string, status: string, result?: any, workerRegistry?: IWorkerRegistry }): Promise<void> => { | |
| console.log(`Đang cập nhật kết quả và trạng thái message ${messageId}`); | |
| // Sử dụng updateMessageStatus với result để xử lý cả status và result | |
| const params: any = { messageId, status, result }; | |
| if (workerRegistry) { | |
| params.workerRegistry = workerRegistry; | |
| } | |
| await this.updateMessageStatus(params); | |
| } | |
| // Health check method to verify API connectivity | |
| healthCheck = async (): Promise<boolean> => { | |
| const tryUrls = [ | |
| `${this.apiBaseUrl}/health`, | |
| `${this.apiBaseUrl}/healthz` | |
| ]; | |
| const httpsAgent = new https.Agent({ rejectUnauthorized: false }); | |
| for (const url of tryUrls) { | |
| try { | |
| const response = await axios.get(url, { | |
| timeout: 5000, | |
| httpsAgent: httpsAgent, | |
| headers: { | |
| 'Accept': 'application/json' | |
| } | |
| }); | |
| if (response.status === 200) return true; | |
| } catch (error: any) { | |
| console.log(`Health check failed for ${url}: ${error.message}`); | |
| } | |
| } | |
| console.error("API health check failed for all endpoints: /health, /healthz"); | |
| return false; | |
| } | |
| createMessage = async ({ messageData }: { messageData: IMessage }): Promise<IMessage> => { | |
| console.log("Đang tạo message mới qua API:", messageData.messageType); | |
| try { | |
| const response: AxiosResponse<{ messages: IMessage[] }> = await axios.post( | |
| `${this.apiBaseUrl}/messages/create`, | |
| { | |
| messages: [messageData] // Noah mong đợi array của messages | |
| }, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| timeout: this.apiTimeout, | |
| httpsAgent: this.httpsAgent | |
| } | |
| ); | |
| console.log(`Đã tạo message mới thành công: ${messageData.messageType}`); | |
| // Trả về message đầu tiên từ response với messageId | |
| const createdMessage = response.data.messages?.[0]; | |
| if (!createdMessage) { | |
| throw new Error('No message returned from create API'); | |
| } | |
| return createdMessage; | |
| } catch (error: any) { | |
| console.error(`Lỗi khi tạo message mới:`, error.message); | |
| if (error.response) { | |
| console.error("Response status:", error.response.status); | |
| console.error("Response data:", error.response.data); | |
| } | |
| throw error; | |
| } | |
| } | |
| createMessages = async ({ messagesData }: { messagesData: IMessage[] }): Promise<IMessage[]> => { | |
| if (!messagesData || messagesData.length === 0) { | |
| console.log("Không có messages để tạo, trả về mảng rỗng"); | |
| return []; | |
| } | |
| console.log(`Đang tạo ${messagesData.length} messages mới qua API`); | |
| try { | |
| const response: AxiosResponse<{ messages: IMessage[] }> = await axios.post( | |
| `${this.apiBaseUrl}/messages/create`, | |
| { | |
| messages: messagesData // Noah mong đợi array của messages | |
| }, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| timeout: this.apiTimeout, | |
| httpsAgent: this.httpsAgent | |
| } | |
| ); | |
| console.log(`Đã tạo ${response.data.messages?.length || 0} messages mới thành công`); | |
| // Trả về danh sách messages từ response với messageId | |
| const createdMessages = response.data.messages; | |
| if (!createdMessages || createdMessages.length === 0) { | |
| throw new Error('No messages returned from create API'); | |
| } | |
| return createdMessages; | |
| } catch (error: any) { | |
| console.error(`Lỗi khi tạo ${messagesData.length} messages mới:`, error.message); | |
| if (error.response) { | |
| console.error("Response status:", error.response.status); | |
| console.error("Response data:", error.response.data); | |
| } | |
| throw error; | |
| } | |
| } | |
| getMessagesByRequestId = async ({ requestId }: { requestId: string }): Promise<IMessage[]> => { | |
| console.log(`Đang lấy messages với requestId: ${requestId}`); | |
| if (!requestId) { | |
| console.log("requestId không tồn tại, không thể lấy messages"); | |
| return []; | |
| } | |
| try { | |
| const response: AxiosResponse<{ messages: IMessage[] }> = await axios.get( | |
| `${this.apiBaseUrl}/messages/request/${requestId}`, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| timeout: this.apiTimeout | |
| } | |
| ); | |
| console.log(`Đã lấy được ${response.data.messages?.length || 0} messages với requestId: ${requestId}`); | |
| return response.data.messages || []; | |
| } catch (error: any) { | |
| console.error(`Lỗi khi lấy messages theo requestId ${requestId}:`, error.message); | |
| if (error.response) { | |
| console.error("Response status:", error.response.status); | |
| console.error("Response data:", error.response.data); | |
| } | |
| return []; | |
| } | |
| } | |
| } |