chronik-cache
Version:
A cache helper for chronik-client
75 lines (74 loc) • 3.02 kB
JavaScript
;
// Copyright (c) 2024 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Logger_1 = __importDefault(require("./Logger"));
class FailoverHandler {
constructor(options = {}) {
this.maxRetries = options.maxRetries || 3;
this.retryDelay = options.retryDelay || 1500; // milliseconds
this.exponentialBackoff = options.exponentialBackoff ?? true;
this.enableLogging = options.enableLogging ?? false;
this.logger = new Logger_1.default(this.enableLogging);
}
async executeWithRetry(operation, context = '') {
let lastError;
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
try {
return await operation();
}
catch (error) {
lastError = error;
const delay = this.exponentialBackoff
? this.retryDelay * Math.pow(2, attempt - 1)
: this.retryDelay;
this.logger.error(`[Failover] ${context} - Attempt ${attempt}/${this.maxRetries} failed:`, lastError.message);
if (attempt < this.maxRetries) {
this.logger.log(`[Failover] Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
this.logger.error(`[Failover] ${context} - All retry attempts failed`);
throw lastError;
}
/**
* Special handling for WebSocket related operations
*/
async handleWebSocketOperation(operation, address, context = '') {
try {
return await this.executeWithRetry(operation, context);
}
catch (error) {
const err = error;
this.logger.error(`[Failover] WebSocket operation failed for address ${address}:`, err.message);
// WebSocket specific error handling logic
if (err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET') {
this.logger.log(`[Failover] WebSocket connection issue detected for ${address}`);
}
throw error;
}
}
/**
* Special handling for database operations
*/
async handleDbOperation(operation, context = '') {
try {
return await this.executeWithRetry(operation, context);
}
catch (error) {
const err = error;
this.logger.error(`[Failover] Database operation failed:`, err.message);
// Database specific error handling logic
if (err.type === 'NotFoundError') {
return null;
}
throw error;
}
}
}
exports.default = FailoverHandler;