Spaces:
Sleeping

teamta / src /classes /core /AggregationHelper.ts
lamsaoganh's picture
Upload 62 files
1305386 verified
Raw History Blame Contribute Delete
8.46 kB
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);
}
}