Spaces:
Sleeping

File size: 8,541 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
import axios from 'axios';
import { IAggregationCounterAPI } from '../../interfaces/core/IAggregationCounterAPI';
import { IAggregationCounter } from '../../interfaces/core/IAggregationCounter';
import { IWorkerRegistry } from '../../interfaces/core/IWorkerRegistry';

export class AggregationCounterAPI implements IAggregationCounterAPI {
    private apiBaseUrl: string;
    private apiTimeout: number;
    private workerRegistry: IWorkerRegistry;

    constructor(apiBaseUrl: string, workerRegistry: IWorkerRegistry, apiTimeout: number = 30000) {
        this.apiBaseUrl = apiBaseUrl;
        this.workerRegistry = workerRegistry;
        this.apiTimeout = apiTimeout;
    }
    
    getApiBaseUrl(): string {
        return this.apiBaseUrl;
    }
    
    setApiBaseUrl(apiBaseUrl: string): void {
        this.apiBaseUrl = String(apiBaseUrl || '').trim().replace(/\/$/, '');
    }

    // Tạo counter mới
    async createCounter(params: {
        requestId: string;
        stepId: string;
        targetMessageType: string;
        expectedCount: number;
        timeoutMs?: number;
        timeoutAt?: string|undefined;
        parentResults?: any;
        delayMs?: number; // Số milliseconds delay khi tạo target message
        targetMessageAggregationCounters?: any[]; // Aggregation counters cho target message
    }): Promise<IAggregationCounter> {
        console.log(`Creating aggregation counter: ${params.requestId}:${params.stepId}`);
        
        try {
            const response = await axios.post(
                `${this.apiBaseUrl}/aggregation-counters`,
                params,
                {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    timeout: this.apiTimeout
                }
            );

            const counter = this.mapFromDto(response.data.counter);
            console.log(`Created aggregation counter successfully: ${counter.aggregationKey}`);
            return counter;
        } catch (error: any) {
            if (error.response) {
                console.error(`Failed to create aggregation counter: ${error.response.status} - ${error.response.data?.error || 'Unknown error'}`);
                throw new Error(`API error: ${error.response.data?.error || 'Unknown error'}`);
            } else if (error.request) {
                console.error('Failed to create aggregation counter: No response from server');
                throw new Error('No response from Noah API server');
            } else {
                console.error('Failed to create aggregation counter:', error.message);
                throw error;
            }
        }
    }

    // Increment counter
    async incrementCounter(params: {
        aggregationKey: string;
        taskType: string;
        result: any;
        workerId?: string;
        messageId?: string; // ID của message đã hoàn thành
    }): Promise<{
        counter: IAggregationCounter | null;
        isComplete: boolean;
        messageCreated?: boolean;
    }> {
        console.log(`Incrementing aggregation counter: ${params.aggregationKey} (${params.taskType})`);
        
        try {
            const response = await axios.post(
                `${this.apiBaseUrl}/aggregation-counters/increment`,
                {
                    workerRegistry: this.workerRegistry,
                    incrementData: params
                },
                {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    timeout: this.apiTimeout
                }
            );

            const result = {
                counter: response.data.counter ? this.mapFromDto(response.data.counter) : null,
                isComplete: response.data.isComplete,
                messageCreated: response.data.messageCreated
            };

            if (result.isComplete) {
                console.log(`Aggregation counter completed: ${params.aggregationKey}`);
                if (result.messageCreated) {
                    console.log(`Target message created for: ${params.aggregationKey}`);
                }
            } else {
                console.log(`Aggregation counter updated: ${params.aggregationKey}`);
            }

            return result;
        } catch (error: any) {
            if (error.response?.status === 404) {
                console.log(`Counter not found or not in waiting state: ${params.aggregationKey}`);
                return { counter: null, isComplete: false };
            }
            
            if (error.response) {
                console.error(`Failed to increment counter: ${error.response.status} - ${error.response.data?.error || 'Unknown error'}`);
                throw new Error(`API error: ${error.response.data?.error || 'Unknown error'}`);
            } else if (error.request) {
                console.error('Failed to increment counter: No response from server');
                throw new Error('No response from Noah API server');
            } else {
                console.error('Failed to increment counter:', error.message);
                throw error;
            }
        }
    }

    // Lấy counter theo key
    async getCounterByKey(aggregationKey: string): Promise<IAggregationCounter | null> {
        try {
            const response = await axios.get(
                `${this.apiBaseUrl}/aggregation-counters/${aggregationKey}`,
                {
                    timeout: this.apiTimeout
                }
            );

            return this.mapFromDto(response.data.counter);
        } catch (error: any) {
            if (error.response?.status === 404) {
                return null;
            }
            
            if (error.response) {
                console.error(`Failed to get counter: ${error.response.status} - ${error.response.data?.error || 'Unknown error'}`);
                throw new Error(`API error: ${error.response.data?.error || 'Unknown error'}`);
            } else if (error.request) {
                console.error('Failed to get counter: No response from server');
                throw new Error('No response from Noah API server');
            } else {
                console.error('Failed to get counter:', error.message);
                throw error;
            }
        }
    }

    // Lấy counters theo requestId
    async getCountersByRequestId(requestId: string): Promise<IAggregationCounter[]> {
        try {
            const response = await axios.get(
                `${this.apiBaseUrl}/aggregation-counters/request/${requestId}`,
                {
                    timeout: this.apiTimeout
                }
            );

            return response.data.counters.map((counter: any) => this.mapFromDto(counter));
        } catch (error: any) {
            if (error.response) {
                console.error(`Failed to get counters by requestId: ${error.response.status} - ${error.response.data?.error || 'Unknown error'}`);
                throw new Error(`API error: ${error.response.data?.error || 'Unknown error'}`);
            } else if (error.request) {
                console.error('Failed to get counters by requestId: No response from server');
                throw new Error('No response from Noah API server');
            } else {
                console.error('Failed to get counters by requestId:', error.message);
                throw error;
            }
        }
    }

    // Helper method to map DTO to interface
    private mapFromDto(dto: any): IAggregationCounter {
        return {
            _id: dto._id || null,
            requestId: dto.requestId,
            stepId: dto.stepId,
            aggregationKey: dto.aggregationKey,
            targetMessageType: dto.targetMessageType,
            expectedCount: dto.expectedCount,
            currentCount: dto.currentCount,
            status: dto.status,
            createdAt: new Date(dto.createdAt),
            updatedAt: new Date(dto.updatedAt),
            timeoutAt: dto.timeoutAt ? new Date(dto.timeoutAt) : null,
            parentResults: dto.parentResults,
            completedTaskMessageIds: dto.completedTaskMessageIds || [],
            ...(dto.delayMs !== undefined && { delayMs: dto.delayMs })
        };
    }
}