'use strict'; /** * ╔══════════════════════════════════════════════════════════════════════════╗ * Connection Manager — v19.0 | Smart Connection Pool + Version Cache ║ * ╠══════════════════════════════════════════════════════════════════════════╣ * ✅ DNS Cache: يحفظ DNS lookups لتسريع الاتصال ║ * ✅ Version Cache: يحفظ إصدار السيرفر المكتشف ║ * ✅ Connection Pool: إدارة اتصالات البوتات بذكاء ║ * ✅ Fast Reconnect: إعادة اتصال فورية مع state restore ║ * ✅ Smart Backoff: Exponential backoff + jitter ║ * ✅ Health Monitor: مراقبة صحة الاتصالات ║ * ╚══════════════════════════════════════════════════════════════════════════╝ */ const dns = require('dns'); const { EventEmitter } = require('events'); const sleep = ms => new Promise(r => setTimeout(r, Math.max(0, ms))); const randInt = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a; const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19); class ConnectionManager extends EventEmitter { constructor() { super(); this.dnsCache = new Map(); this.dnsCacheTTL = 300000; this.versionCache = new Map(); this.versionCacheTTL = 600000; this.connections = new Map(); this.healthHistory = new Map(); this._log('POOL', 'تم إنشاء Connection Manager'); } _log(tag, msg) { const ts = tsNow(); console.log(`[${ts}] [CONN] ${tag} ${msg}`); } async resolveDns(host) { const cached = this.dnsCache.get(host); if (cached && (Date.now() - cached.time) < this.dnsCacheTTL) { this._log('💾', `DNS cache hit: ${host} → ${cached.ip}`); return cached.ip; } return new Promise((resolve) => { dns.resolve4(host, (err, addresses) => { if (err) { this._log('⚠️', `DNS lookup failed: ${host} — ${err.code}`); this.emit('dnsFailed', host, err); resolve(host); return; } const ip = addresses[0]; this.dnsCache.set(host, { ip, time: Date.now() }); this._log('🌐', `DNS resolved: ${host} → ${ip}`); this.emit('dnsResolved', host, ip); resolve(ip); }); }); } cacheVersion(host, port, version) { const key = `${host}:${port}`; this.versionCache.set(key, { version, time: Date.now() }); this._log('💾', `Version cached: ${key} → ${version}`); } getCachedVersion(host, port) { const key = `${host}:${port}`; const cached = this.versionCache.get(key); if (cached && (Date.now() - cached.time) < this.versionCacheTTL) { return cached.version; } return null; } clearVersionCache(host, port) { if (host && port) { this.versionCache.delete(`${host}:${port}`); } else { this.versionCache.clear(); } } trackConnection(botId, data) { const existing = this.connections.get(botId) || { connects: 0, disconnects: 0, kicks: 0, errors: 0, avgPing: null, pings: [], lastConnect: null, lastDisconnect: null }; existing.connects++; existing.lastConnect = Date.now(); if (data.ping) { existing.pings.push(data.ping); if (existing.pings.length > 20) existing.pings.shift(); existing.avgPing = Math.round(existing.pings.reduce((a, b) => a + b, 0) / existing.pings.length); } this.connections.set(botId, existing); this.emit('connectionTracked', botId, 'connect', existing); } trackDisconnect(botId, reason) { const existing = this.connections.get(botId) || { connects: 0, disconnects: 0, kicks: 0, errors: 0, avgPing: null, pings: [], lastConnect: null, lastDisconnect: null }; existing.disconnects++; existing.lastDisconnect = Date.now(); const reasonLower = (reason || '').toLowerCase(); if (reasonLower.includes('kick')) existing.kicks++; if (reasonLower.includes('error') || reasonLower.includes('fail')) existing.errors++; this.connections.set(botId, existing); this.emit('connectionTracked', botId, 'disconnect', existing); } getConnectionStats(botId) { return this.connections.get(botId) || null; } getAllStats() { const stats = {}; for (const [id, data] of this.connections) { stats[id] = { ...data }; } return stats; } getReconnectDelay(attempt, baseMs = 10000, maxMs = 120000) { const exp = Math.min(attempt, 8); const base = baseMs * Math.pow(1.5, exp); const jitter = randInt(0, Math.floor(base * 0.2)); return Math.min(base + jitter, maxMs); } clearDnsCache() { this.dnsCache.clear(); this._log('🗑️', 'تم مسح DNS cache'); } getStatus() { return { dnsCacheSize: this.dnsCache.size, versionCacheSize: this.versionCache.size, connectionsTracked: this.connections.size, stats: this.getAllStats() }; } } module.exports = { ConnectionManager };