File size: 4,291 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 *  Retry Controller - ระบบควบคุมการทำซ้ำ
 *  Chahua Development Thailand
 *  CEO: Saharath C.
 * 
 *  Purpose: จัดการการ retry operations ที่ล้มเหลว
 */

class RetryController {
    constructor(options = {}) {
        this.config = {
            maxRetries: options.maxRetries || 3,
            baseDelay: options.baseDelay || 1000, // 1 second
            maxDelay: options.maxDelay || 30000, // 30 seconds
            backoffMultiplier: options.backoffMultiplier || 2,
            jitter: options.jitter || true
        };
        
        this.retryHistory = new Map();
        console.log(' Retry Controller initialized');
    }

    async executeWithRetry(operation, context = {}, customConfig = {}) {
        const config = { ...this.config, ...customConfig };
        const operationId = context.id || this.generateOperationId();
        
        console.log(` Starting operation with retry: ${operationId}`);
        
        let lastError;
        let attempt = 0;
        
        while (attempt <= config.maxRetries) {
            try {
                console.log(`   Attempt ${attempt + 1}/${config.maxRetries + 1}`);
                
                const result = await operation(context, attempt);
                
                if (attempt > 0) {
                    console.log(` Operation succeeded on attempt ${attempt + 1}`);
                }
                
                this.logSuccess(operationId, attempt);
                return result;
                
            } catch (error) {
                lastError = error;
                attempt++;
                
                console.log(` Attempt ${attempt} failed: ${error.message}`);
                
                if (attempt <= config.maxRetries) {
                    const delay = this.calculateDelay(attempt, config);
                    console.log(` Retrying in ${delay}ms...`);
                    
                    await this.sleep(delay);
                } else {
                    console.log(` All retry attempts exhausted for ${operationId}`);
                }
            }
        }
        
        this.logFailure(operationId, config.maxRetries + 1, lastError);
        throw new Error(`Operation failed after ${config.maxRetries + 1} attempts: ${lastError.message}`);
    }

    calculateDelay(attempt, config) {
        let delay = config.baseDelay * Math.pow(config.backoffMultiplier, attempt - 1);
        
        // Cap at max delay
        delay = Math.min(delay, config.maxDelay);
        
        // Add jitter to prevent thundering herd
        if (config.jitter) {
            delay = delay * (0.5 + Math.random() * 0.5);
        }
        
        return Math.round(delay);
    }

    async sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    generateOperationId() {
        return `op_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
    }

    logSuccess(operationId, attempts) {
        this.retryHistory.set(operationId, {
            operationId,
            success: true,
            attempts: attempts + 1,
            timestamp: new Date().toISOString()
        });
    }

    logFailure(operationId, attempts, error) {
        this.retryHistory.set(operationId, {
            operationId,
            success: false,
            attempts,
            error: error.message,
            timestamp: new Date().toISOString()
        });
    }

    getRetryStats() {
        const history = Array.from(this.retryHistory.values());
        const successful = history.filter(h => h.success).length;
        const failed = history.length - successful;
        
        const avgAttempts = history.length > 0 
            ? Math.round(history.reduce((sum, h) => sum + h.attempts, 0) / history.length)
            : 0;
        
        return {
            totalOperations: history.length,
            successful,
            failed,
            successRate: history.length > 0 ? Math.round((successful / history.length) * 100) : 0,
            averageAttempts: avgAttempts
        };
    }

    clearHistory() {
        this.retryHistory.clear();
        console.log(' Retry history cleared');
    }
}

module.exports = RetryController;