import axios, { AxiosResponse } from "axios"; import https from "https"; import { IWorkerRegistryAPI } from "../../interfaces/core/IWorkerRegistryAPI"; import { IWorkerRegistry } from "../../interfaces/core/IWorkerRegistry"; export class WorkerRegistryAPI implements IWorkerRegistryAPI { 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(/\/$/, ''); } registerOrUpdate = async ({ workerRegistryData }: { workerRegistryData: IWorkerRegistry }): Promise => { // Validate required fields if (!workerRegistryData.workerId) { throw new Error("WorkerRegistry validation failed: workerId is required"); } if (!workerRegistryData.role) { throw new Error("WorkerRegistry validation failed: role is required"); } if (!workerRegistryData.platform) { throw new Error("WorkerRegistry validation failed: platform is required"); } if (!workerRegistryData.coder) { throw new Error("WorkerRegistry validation failed: coder is required"); } if (!Array.isArray(workerRegistryData.typeConfig) || workerRegistryData.typeConfig.length === 0) { throw new Error("WorkerRegistry validation failed: typeConfig must be a non-empty array"); } console.log("Đang đăng ký hoặc update worker qua API:", workerRegistryData.workerId); 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: new Date().toISOString(), typeConfig: cleanedTypeConfig } }; const response: AxiosResponse = await axios.post( `${this.apiBaseUrl}/workers/register`, requestBody, { headers: { 'Content-Type': 'application/json', }, timeout: this.apiTimeout, httpsAgent: this.httpsAgent } ); console.log(`Đã đăng ký worker ${workerRegistryData.workerId} thành công`); } catch (error: any) { console.error(`Lỗi khi đăng ký worker ${workerRegistryData.workerId}:`, error.message); if (error.response) { console.error("Response status:", error.response.status); console.error("Response data:", error.response.data); } // Do not throw: registry failures should not crash a long-lived worker. return; } } unRegister = async ({ workerRegistryData }: { workerRegistryData: IWorkerRegistry }): Promise => { console.log("Đang hủy đăng ký worker qua API:", workerRegistryData.workerId); try { await axios.delete( `${this.apiBaseUrl}/workers/${workerRegistryData.workerId}`, { headers: { 'Content-Type': 'application/json', }, timeout: this.apiTimeout, httpsAgent: this.httpsAgent } ); console.log(`Đã hủy đăng ký worker ${workerRegistryData.workerId} thành công`); } catch (error: any) { console.error(`Lỗi khi hủy đăng ký worker ${workerRegistryData.workerId}:`, error.message); if (error.response) { console.error("Response status:", error.response.status); console.error("Response data:", error.response.data); } // Do not throw: unregister failures should not crash. return; } } sendHeartbeat = async ({ workerRegistryData }: { workerRegistryData: IWorkerRegistry }): Promise => { // 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"); } console.log("Đang gửi heartbeat qua API cho worker:", workerRegistryData.workerId); 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, createdAt: workerRegistryData.createdAt instanceof Date ? workerRegistryData.createdAt.toISOString() : workerRegistryData.createdAt, lastSeen: new Date().toISOString(), updatedAt: new Date().toISOString(), typeConfig: cleanedTypeConfig } }; await axios.post( `${this.apiBaseUrl}/workers/heartbeat`, requestBody, { headers: { 'Content-Type': 'application/json', }, timeout: this.apiTimeout, httpsAgent: this.httpsAgent } ); console.log(`Đã gửi heartbeat cho worker ${workerRegistryData.workerId} thành công`); } catch (error: any) { console.error(`Lỗi khi gửi heartbeat cho worker ${workerRegistryData.workerId}:`, error.message); if (error.response) { console.error("Response status:", error.response.status); console.error("Response data:", error.response.data); } // Không throw error vì heartbeat failure không nên crash worker } } // Health check method to verify API connectivity healthCheck = async (): Promise => { 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; } // Get worker information getWorkerInfo = async ({ workerId }: { workerId: string }): Promise => { try { const response: AxiosResponse<{ worker: IWorkerRegistry }> = await axios.get( `${this.apiBaseUrl}/workers/${workerId}`, { headers: { 'Content-Type': 'application/json', }, timeout: this.apiTimeout, httpsAgent: this.httpsAgent } ); return response.data.worker || null; } catch (error: any) { if (error.response?.status === 404) { return null; // Worker not found } console.error(`Lỗi khi lấy thông tin worker ${workerId}:`, error.message); // Do not throw: treat as unavailable. return null; } } }