File size: 9,568 Bytes
a08f3c3 | 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 | 'use strict';
/**
* ╔══════════════════════════════════════════════════════════════════════════╗
* Multi-Server Manager — v23.0 | دعم سيرفرات متعددة ║
* ╠══════════════════════════════════════════════════════════════════════════╣
* ✅ Multiple Servers: تشغيل سيرفرات متعددة في نفس الوقت ║
* ✅ Server Switching: التبديل بين السيرفرات ║
* ✅ Load Balancing: توزيع البوتات على السيرفرات ║
* ✅ Server Profiles: ملفات شخصية لكل سيرفر ║
* ✅ Cross-Server Chat: دردشة بين السيرفرات ║
* ✅ Resource Sharing: مشاركة الموارد بين السيرفرات ║
* ✅ Auto-Failover: تبديل تلقائي عند فشل سيرفر ║
* ✅ Health Monitoring: مراقبة صحة جميع السيرفرات ║
* ╚══════════════════════════════════════════════════════════════════════════╝
*/
const { EventEmitter } = require('events');
const fs = require('fs');
const path = require('path');
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class MultiServerManager extends EventEmitter {
constructor(config = {}) {
super();
this.configPath = config.configPath || path.join(__dirname, 'servers.json');
this.servers = new Map();
this.activeServers = new Map();
this.serverHistory = [];
this.maxHistory = 100;
this._running = false;
this._healthTimer = null;
this._log('MULTI', 'تم إنشاء Multi-Server Manager');
}
_log(tag, msg) { console.log(`[${tsNow()}] [MULTI] ${tag} ${msg}`); }
// ─── Server Management ────────────────────────────────────────────────
addServer(id, config) {
const server = {
id,
name: config.name || `Server ${id}`,
host: config.host,
port: config.port || 25565,
version: config.version || '1.21.4',
maxBots: config.maxBots || 4,
currentBots: 0,
status: 'offline',
priority: config.priority || 0,
lastCheck: null,
lastOnline: null,
consecutiveFailures: 0,
config: config,
botNames: config.botNames || [],
features: config.features || {},
metadata: {},
};
this.servers.set(id, server);
this._log('➕', `سيرفر جديد: ${server.name} (${server.host}:${server.port})`);
this.emit('serverAdded', server);
return server;
}
removeServer(id) {
const server = this.servers.get(id);
if (!server) return false;
this.servers.delete(id);
this._log('➖', `حذف سيرفر: ${server.name}`);
this.emit('serverRemoved', server);
return true;
}
getServer(id) {
return this.servers.get(id) || null;
}
getAllServers() {
return [...this.servers.values()];
}
getOnlineServers() {
return [...this.servers.values()].filter(s => s.status === 'online');
}
getAvailableServers() {
return [...this.servers.values()].filter(s =>
s.status === 'online' && s.currentBots < s.maxBots
);
}
// ─── Load Balancing ───────────────────────────────────────────────────
getNextServer() {
const available = this.getAvailableServers();
if (available.length === 0) return null;
available.sort((a, b) => {
if (a.priority !== b.priority) return b.priority - a.priority;
return (a.currentBots / a.maxBots) - (b.currentBots / b.maxBots);
});
return available[0];
}
distributeBots(botCount) {
const servers = this.getAvailableServers();
if (servers.length === 0) return [];
const distribution = [];
const perServer = Math.ceil(botCount / servers.length);
for (const server of servers) {
const botsForServer = Math.min(perServer, server.maxBots - server.currentBots);
if (botsForServer > 0) {
distribution.push({ server, count: botsForServer });
}
}
return distribution;
}
// ─── Server Status ────────────────────────────────────────────────────
updateServerStatus(id, status, metadata = {}) {
const server = this.servers.get(id);
if (!server) return;
const oldStatus = server.status;
server.status = status;
server.lastCheck = Date.now();
Object.assign(server.metadata, metadata);
if (status === 'online') {
server.lastOnline = Date.now();
server.consecutiveFailures = 0;
} else if (status === 'offline') {
server.consecutiveFailures++;
}
if (oldStatus !== status) {
this._log('🔄', `${server.name}: ${oldStatus} → ${status}`);
this.emit('statusChange', id, status, oldStatus);
}
this._recordEvent(id, 'status', { from: oldStatus, to: status });
}
_recordEvent(serverId, type, data) {
this.serverHistory.push({ serverId, type, data, time: Date.now() });
if (this.serverHistory.length > this.maxHistory) this.serverHistory.shift();
}
// ─── Cross-Server Chat ────────────────────────────────────────────────
broadcastMessage(fromServer, username, message) {
for (const [id, server] of this.servers) {
if (id !== fromServer && server.status === 'online') {
this.emit('crossServerMessage', { fromServer, toServer: id, username, message });
}
}
}
// ─── Health Monitoring ────────────────────────────────────────────────
startMonitoring(intervalMs = 30000) {
if (this._running) return;
this._running = true;
this._healthTimer = setInterval(() => this._checkHealth(), intervalMs);
this._log('🟢', 'بدء مراقبة السيرفرات');
}
stopMonitoring() {
this._running = false;
if (this._healthTimer) { clearInterval(this._healthTimer); this._healthTimer = null; }
this._log('🔴', 'إيقاف مراقبة السيرفرات');
}
_checkHealth() {
for (const [id, server] of this.servers) {
if (server.consecutiveFailures >= 5) {
this.emit('serverUnstable', id, server);
}
if (server.status === 'offline' && server.consecutiveFailures >= 3) {
this.emit('failoverNeeded', id, server);
}
}
}
// ─── File Persistence ─────────────────────────────────────────────────
saveConfig() {
try {
const data = {};
for (const [id, server] of this.servers) {
data[id] = {
name: server.name, host: server.host, port: server.port,
version: server.version, maxBots: server.maxBots,
priority: server.priority, config: server.config,
botNames: server.botNames, features: server.features,
};
}
fs.writeFileSync(this.configPath, JSON.stringify(data, null, 2));
this._log('💾', 'تم حفظ إعدادات السيرفرات');
} catch (e) {
this._log('❌', `خطأ في الحفظ: ${e.message}`);
}
}
loadConfig() {
try {
if (!fs.existsSync(this.configPath)) return;
const raw = fs.readFileSync(this.configPath, 'utf8');
const data = JSON.parse(raw);
for (const [id, cfg] of Object.entries(data)) {
this.addServer(id, cfg);
}
this._log('📂', `تم تحميل ${Object.keys(data).length} سيرفر`);
} catch (e) {
this._log('❌', `خطأ في التحميل: ${e.message}`);
}
}
// ─── Status ───────────────────────────────────────────────────────────
getStatus() {
const servers = [...this.servers.values()];
return {
total: servers.length,
online: servers.filter(s => s.status === 'online').length,
offline: servers.filter(s => s.status === 'offline').length,
starting: servers.filter(s => s.status === 'starting').length,
totalBots: servers.reduce((a, s) => a + s.currentBots, 0),
maxBots: servers.reduce((a, s) => a + s.maxBots, 0),
servers: servers.map(s => ({
id: s.id, name: s.name, host: s.host, port: s.port,
status: s.status, bots: `${s.currentBots}/${s.maxBots}`,
priority: s.priority, failures: s.consecutiveFailures,
})),
history: this.serverHistory.slice(-20),
};
}
destroy() {
this.stopMonitoring();
this.removeAllListeners();
}
}
module.exports = { MultiServerManager };
|