Spaces:
Sleeping

File size: 13,759 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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 [];
        }
    }
}