chahuadev-framework-en / modules /retry-controller.js
chahuadev
Update README
857cdcf
/**
* 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;