Spaces:
Sleeping

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

export class AggregationHelper {
    private aggregationAPI: AggregationCounterAPI;
    private workerRegistry: IWorkerRegistry;

    constructor(aggregationAPI: AggregationCounterAPI, workerRegistry: IWorkerRegistry) {
        this.aggregationAPI = aggregationAPI;
        this.workerRegistry = workerRegistry;
    }

    /**

     * Tạo counter mới cho workflow aggregation

     * @param requestId - ID duy nhất cho request

     * @param stepId - ID step trong workflow (vd: "parallel-step-1")

     * @param targetMessageType - Loại message sẽ được tạo khi hoàn thành

     * @param expectedCount - Số lượng task con dự kiến

     * @param timeoutMs - Timeout tự động (mặc định 10 phút)

     * @param parentResults - Kết quả từ step trước (nếu có)

     * @param delayMs - Delay trước khi tạo target message (optional)

     * @param targetMessageAggregationCounters - Aggregation counters cho target message (optional)

     */
    async createAggregationCounter(params: {
        requestId: string;
        stepId: string;
        targetMessageType: string;
        expectedCount: number;
        timeoutMs?: number;
        parentResults?: any;
        delayMs?: number;
        targetMessageAggregationCounters?: any[];
    }): Promise<IAggregationCounter> {
        const timeoutMs = params.timeoutMs || (10 * 60 * 1000); // 10 phút mặc định
        
        console.log(`[AggregationHelper] Creating counter for ${params.requestId}:${params.stepId} expecting ${params.expectedCount} tasks`);
        
        return await this.aggregationAPI.createCounter({
            ...params,
            timeoutMs
        });
    }

    /**

     * Báo cáo kết quả hoàn thành của một task con

     * @param aggregationKey - Key của counter (requestId:stepId)

     * @param taskType - Loại task vừa hoàn thành

     * @param result - Kết quả của task

     * @param workerId - ID của worker (tự động lấy từ registry nếu không có)

     * @param messageId - ID của message đã hoàn thành

     */
    async reportTaskCompletion(params: {
        aggregationKey: string;
        taskType: string;
        result: any;
        workerId?: string;
        messageId?: string; // ID của message đã hoàn thành
    }): Promise<{
        isComplete: boolean;
        messageCreated?: boolean;
    }> {
        const workerId = params.workerId || this.workerRegistry.workerId;
        
        console.log(`[AggregationHelper] Reporting completion for ${params.aggregationKey} - ${params.taskType}${params.messageId ? ` (messageId: ${params.messageId})` : ''}`);
        
        const incrementParams: {
            aggregationKey: string;
            taskType: string;
            result: any;
            workerId: string;
            messageId?: string;
        } = {
            aggregationKey: params.aggregationKey,
            taskType: params.taskType,
            result: params.result,
            workerId
        };

        // Chỉ thêm messageId nếu có giá trị
        if (params.messageId) {
            incrementParams.messageId = params.messageId;
        }

        const response = await this.aggregationAPI.incrementCounter(incrementParams);

        if (response.isComplete) {
            console.log(`[AggregationHelper] Aggregation completed for ${params.aggregationKey}${response.messageCreated ? ' - Target message created' : ''}`);
            
            return {
                isComplete: true,
                messageCreated: response.messageCreated || false
            };
        }

        return {
            isComplete: false
        };
    }

    /**

     * Kiểm tra trạng thái của một counter

     */
    async checkCounterStatus(aggregationKey: string): Promise<{
        exists: boolean;
        counter?: IAggregationCounter;
        isComplete?: boolean;
        progress?: {
            completed: number;
            expected: number;
            percentage: number;
        };
    }> {
        const counter = await this.aggregationAPI.getCounterByKey(aggregationKey);
        
        if (!counter) {
            return { exists: false };
        }

        const isComplete = counter.status === 'completed' || counter.status === 'failed';
        const progress = {
            completed: counter.currentCount,
            expected: counter.expectedCount,
            percentage: Math.round((counter.currentCount / counter.expectedCount) * 100)
        };

        return {
            exists: true,
            counter,
            isComplete,
            progress
        };
    }

    /**

     * Lấy tất cả counters cho một requestId

     */
    async getAllCountersForRequest(requestId: string): Promise<IAggregationCounter[]> {
        return await this.aggregationAPI.getCountersByRequestId(requestId);
    }

    /**

     * Tính toán aggregation key từ requestId và stepId

     */
    static createAggregationKey(requestId: string, stepId: string): string {
        return `${requestId}:${stepId}`;
    }

    /**

     * Helper để tạo stepId theo pattern

     */
    static createStepId(stepType: 'parallel' | 'sequential' | 'conditional', stepNumber: number, description?: string): string {
        const base = `${stepType}-step-${stepNumber}`;
        return description ? `${base}-${description}` : base;
    }

    /**

     * Wrapper để dễ dàng sử dụng trong service

     * Tạo counter và trả về aggregation key

     */
    async initializeParallelStep(params: {
        requestId: string;
        stepNumber: number;
        stepDescription?: string;
        targetMessageType: string;
        expectedCount: number;
        timeoutMs?: number;
        parentResults?: any;
        delayMs?: number;
        targetMessageAggregationCounters?: any[];
    }): Promise<string> {
        const stepId = AggregationHelper.createStepId('parallel', params.stepNumber, params.stepDescription);
        
        await this.createAggregationCounter({
            requestId: params.requestId,
            stepId,
            targetMessageType: params.targetMessageType,
            expectedCount: params.expectedCount,
            ...(params.timeoutMs !== undefined && { timeoutMs: params.timeoutMs }),
            ...(params.parentResults !== undefined && { parentResults: params.parentResults }),
            ...(params.delayMs !== undefined && { delayMs: params.delayMs }),
            ...(params.targetMessageAggregationCounters !== undefined && { targetMessageAggregationCounters: params.targetMessageAggregationCounters })
        });

        return AggregationHelper.createAggregationKey(params.requestId, stepId);
    }

    /**

     * Wrapper để báo cáo hoàn thành task trong parallel step

     */
    async completeParallelTask(params: {
        requestId: string;
        stepNumber: number;
        stepDescription?: string;
        taskType: string;
        result: any;
        workerId?: string;
        messageId?: string; // ID của message đã hoàn thành
    }): Promise<{
        isComplete: boolean;
        messageCreated?: boolean;
    }> {
        const stepId = AggregationHelper.createStepId('parallel', params.stepNumber, params.stepDescription);
        const aggregationKey = AggregationHelper.createAggregationKey(params.requestId, stepId);

        const reportParams: {
            aggregationKey: string;
            taskType: string;
            result: any;
            workerId?: string;
            messageId?: string;
        } = {
            aggregationKey,
            taskType: params.taskType,
            result: params.result
        };

        // Chỉ thêm các optional params nếu có giá trị
        if (params.workerId) {
            reportParams.workerId = params.workerId;
        }
        if (params.messageId) {
            reportParams.messageId = params.messageId;
        }

        return await this.reportTaskCompletion(reportParams);
    }
}