Spaces:
Sleeping

File size: 9,663 Bytes
1305386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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<void> => {
        // 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<void> => {
        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<void> => {
        // 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<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;
    }

    // Get worker information 
    getWorkerInfo = async ({ workerId }: { workerId: string }): Promise<IWorkerRegistry | null> => {
        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;
        }
    }
}