File size: 11,595 Bytes
d6d843f |
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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
#!/usr/bin/env node
/**
* FAILOVER CHAIN MANAGER
* Builds redundancy chains and manages automatic failover for API resources
*/
const fs = require('fs');
class FailoverManager {
constructor(reportPath = './api-monitor-report.json') {
this.reportPath = reportPath;
this.report = null;
this.failoverChains = {};
}
// Load monitoring report
loadReport() {
try {
const data = fs.readFileSync(this.reportPath, 'utf8');
this.report = JSON.parse(data);
return true;
} catch (error) {
console.error('Failed to load report:', error.message);
return false;
}
}
// Build failover chains for each data type
buildFailoverChains() {
console.log('\nββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β FAILOVER CHAIN BUILDER β');
console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
const chains = {
ethereumPrice: this.buildPriceChain('ethereum'),
bitcoinPrice: this.buildPriceChain('bitcoin'),
ethereumExplorer: this.buildExplorerChain('ethereum'),
bscExplorer: this.buildExplorerChain('bsc'),
tronExplorer: this.buildExplorerChain('tron'),
rpcEthereum: this.buildRPCChain('ethereum'),
rpcBSC: this.buildRPCChain('bsc'),
newsFeeds: this.buildNewsChain(),
sentiment: this.buildSentimentChain()
};
this.failoverChains = chains;
// Display chains
for (const [chainName, chain] of Object.entries(chains)) {
this.displayChain(chainName, chain);
}
return chains;
}
// Build price data failover chain
buildPriceChain(coin) {
const chain = [];
// Get market data resources
const marketResources = this.report?.categories?.marketData || [];
// Sort by status and tier
const sorted = marketResources
.filter(r => ['ONLINE', 'DEGRADED'].includes(r.status))
.sort((a, b) => {
// Prioritize by tier first
if (a.tier !== b.tier) return a.tier - b.tier;
// Then by status
const statusPriority = { ONLINE: 1, DEGRADED: 2, SLOW: 3 };
return statusPriority[a.status] - statusPriority[b.status];
});
for (const resource of sorted) {
chain.push({
name: resource.name,
url: resource.url,
status: resource.status,
tier: resource.tier,
responseTime: resource.lastCheck?.responseTime
});
}
return chain;
}
// Build explorer failover chain
buildExplorerChain(blockchain) {
const chain = [];
const explorerResources = this.report?.categories?.blockchainExplorers || [];
const filtered = explorerResources
.filter(r => {
const name = r.name.toLowerCase();
return (blockchain === 'ethereum' && name.includes('eth')) ||
(blockchain === 'bsc' && name.includes('bsc')) ||
(blockchain === 'tron' && name.includes('tron'));
})
.filter(r => ['ONLINE', 'DEGRADED'].includes(r.status))
.sort((a, b) => a.tier - b.tier);
for (const resource of filtered) {
chain.push({
name: resource.name,
url: resource.url,
status: resource.status,
tier: resource.tier,
responseTime: resource.lastCheck?.responseTime
});
}
return chain;
}
// Build RPC node failover chain
buildRPCChain(network) {
const chain = [];
const rpcResources = this.report?.categories?.rpcNodes || [];
const filtered = rpcResources
.filter(r => {
const name = r.name.toLowerCase();
return name.includes(network.toLowerCase());
})
.filter(r => ['ONLINE', 'DEGRADED'].includes(r.status))
.sort((a, b) => {
if (a.tier !== b.tier) return a.tier - b.tier;
return (a.lastCheck?.responseTime || 999999) - (b.lastCheck?.responseTime || 999999);
});
for (const resource of filtered) {
chain.push({
name: resource.name,
url: resource.url,
status: resource.status,
tier: resource.tier,
responseTime: resource.lastCheck?.responseTime
});
}
return chain;
}
// Build news feed failover chain
buildNewsChain() {
const chain = [];
const newsResources = this.report?.categories?.newsAndSentiment || [];
const filtered = newsResources
.filter(r => ['ONLINE', 'DEGRADED'].includes(r.status))
.sort((a, b) => a.tier - b.tier);
for (const resource of filtered) {
chain.push({
name: resource.name,
url: resource.url,
status: resource.status,
tier: resource.tier,
responseTime: resource.lastCheck?.responseTime
});
}
return chain;
}
// Build sentiment data failover chain
buildSentimentChain() {
const chain = [];
const newsResources = this.report?.categories?.newsAndSentiment || [];
const filtered = newsResources
.filter(r => r.name.toLowerCase().includes('fear') ||
r.name.toLowerCase().includes('greed') ||
r.name.toLowerCase().includes('sentiment'))
.filter(r => ['ONLINE', 'DEGRADED'].includes(r.status));
for (const resource of filtered) {
chain.push({
name: resource.name,
url: resource.url,
status: resource.status,
tier: resource.tier,
responseTime: resource.lastCheck?.responseTime
});
}
return chain;
}
// Display failover chain
displayChain(chainName, chain) {
console.log(`\nπ ${chainName.toUpperCase()} Failover Chain:`);
console.log('β'.repeat(60));
if (chain.length === 0) {
console.log(' β οΈ No available resources');
return;
}
chain.forEach((resource, index) => {
const arrow = index === 0 ? 'π―' : ' β';
const priority = index === 0 ? '[PRIMARY]' : index === 1 ? '[BACKUP]' : `[BACKUP-${index}]`;
const tierBadge = `[TIER-${resource.tier}]`;
const rt = resource.responseTime ? `${resource.responseTime}ms` : 'N/A';
console.log(` ${arrow} ${priority.padEnd(12)} ${resource.name.padEnd(25)} ${resource.status.padEnd(10)} ${rt.padStart(8)} ${tierBadge}`);
});
}
// Generate failover configuration file
exportFailoverConfig(filename = 'failover-config.json') {
const config = {
generatedAt: new Date().toISOString(),
chains: this.failoverChains,
usage: {
description: 'Automatic failover configuration for API resources',
example: `
// Example usage in your application:
const failoverConfig = require('./failover-config.json');
async function fetchWithFailover(chainName, fetchFunction) {
const chain = failoverConfig.chains[chainName];
for (const resource of chain) {
try {
const result = await fetchFunction(resource.url);
return result;
} catch (error) {
console.log(\`Failed \${resource.name}, trying next...\`);
continue;
}
}
throw new Error('All resources in chain failed');
}
// Use it:
const data = await fetchWithFailover('ethereumPrice', async (url) => {
const response = await fetch(url + '/api/v3/simple/price?ids=ethereum&vs_currencies=usd');
return response.json();
});
`
}
};
fs.writeFileSync(filename, JSON.stringify(config, null, 2));
console.log(`\nβ Failover configuration exported to ${filename}`);
}
// Identify categories with single point of failure
identifySinglePointsOfFailure() {
console.log('\nββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β SINGLE POINT OF FAILURE ANALYSIS β');
console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
const spofs = [];
for (const [chainName, chain] of Object.entries(this.failoverChains)) {
const onlineCount = chain.filter(r => r.status === 'ONLINE').length;
if (onlineCount === 0) {
spofs.push({
chain: chainName,
severity: 'CRITICAL',
message: 'Zero available resources'
});
} else if (onlineCount === 1) {
spofs.push({
chain: chainName,
severity: 'HIGH',
message: 'Only one resource available (SPOF)'
});
} else if (onlineCount === 2) {
spofs.push({
chain: chainName,
severity: 'MEDIUM',
message: 'Only two resources available'
});
}
}
if (spofs.length === 0) {
console.log(' β No single points of failure detected\n');
} else {
for (const spof of spofs) {
const icon = spof.severity === 'CRITICAL' ? 'π΄' :
spof.severity === 'HIGH' ? 'π ' : 'π‘';
console.log(` ${icon} [${spof.severity}] ${spof.chain}: ${spof.message}`);
}
console.log();
}
return spofs;
}
// Generate redundancy report
generateRedundancyReport() {
console.log('\nββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ');
console.log('β REDUNDANCY ANALYSIS REPORT β');
console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n');
const categories = this.report?.categories || {};
for (const [category, resources] of Object.entries(categories)) {
const total = resources.length;
const online = resources.filter(r => r.status === 'ONLINE').length;
const degraded = resources.filter(r => r.status === 'DEGRADED').length;
const offline = resources.filter(r => r.status === 'OFFLINE').length;
let indicator = 'β';
if (online === 0) indicator = 'β';
else if (online === 1) indicator = 'β ';
else if (online >= 3) indicator = 'ββ';
console.log(` ${indicator} ${category.padEnd(25)} Online: ${online}/${total} Degraded: ${degraded} Offline: ${offline}`);
}
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// MAIN EXECUTION
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function main() {
const manager = new FailoverManager();
if (!manager.loadReport()) {
console.error('\nβ Please run the monitor first: node api-monitor.js');
process.exit(1);
}
// Build failover chains
manager.buildFailoverChains();
// Export configuration
manager.exportFailoverConfig();
// Identify SPOFs
manager.identifySinglePointsOfFailure();
// Generate redundancy report
manager.generateRedundancyReport();
console.log('\nβ Failover analysis complete\n');
}
if (require.main === module) {
main().catch(console.error);
}
module.exports = FailoverManager;
|