Saed / performance-optimizer.js
Saedmh's picture
Upload 37 files
a08f3c3 verified
Raw History Blame Contribute Delete
8.65 kB
'use strict';
/**
* ╔══════════════════════════════════════════════════════════════════════════╗
* Performance Optimizer — v23.0 | تحسين الأداء والذاكرة ║
* ╠══════════════════════════════════════════════════════════════════════════╣
* ✅ Memory Management: إدارة ذاكرة ذكية + auto-cleanup ║
* ✅ Object Pooling: إعادة استخدام الكائنات لتقليل GC ║
* ✅ Throttling: تقييد العمليات الثقيلة ║
* ✅ Caching: تخزين مؤقت ذكي للاستعلامات المتكررة ║
* ✅ Metrics: قياس الأداء في الوقت الحقيقي ║
* ✅ Auto-Tune: تحسين تلقائي للإعدادات حسب الأداء ║
* ✅ Garbage Collection: جامع نفايات ذكي ║
* ✅ Connection Pool: إدارة اتصالات فعّالة ║
* ╚══════════════════════════════════════════════════════════════════════════╝
*/
const { EventEmitter } = require('events');
const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
class PerformanceOptimizer extends EventEmitter {
constructor(config = {}) {
super();
this.config = {
memoryLimitMB: config.memoryLimitMB || 380,
gcIntervalMs: config.gcIntervalMs || 30000,
metricsIntervalMs: config.metricsIntervalMs || 5000,
maxCacheSize: config.maxCacheSize || 1000,
throttleMs: config.throttleMs || 100,
autoTune: config.autoTune !== false,
...config,
};
this.metrics = {
memory: { used: 0, total: 0, limit: 0, usage: 0 },
cpu: { usage: 0, loadAvg: [0, 0, 0] },
events: { emitted: 0, processed: 0, dropped: 0 },
cache: { hits: 0, misses: 0, size: 0 },
gc: { collections: 0, freed: 0, lastAt: null },
uptime: 0,
botCount: 0,
activeTimers: 0,
};
this.cache = new Map();
this.pools = new Map();
this.throttled = new Map();
this._running = false;
this._gcTimer = null;
this._metricsTimer = null;
this._log('OPTIMIZER', 'تم إنشاء Performance Optimizer');
}
_log(tag, msg) { console.log(`[${tsNow()}] [PERF] ${tag} ${msg}`); }
start() {
if (this._running) return;
this._running = true;
this._log('🟢', 'بدء تحسين الأداء');
this._gcTimer = setInterval(() => this._runGC(), this.config.gcIntervalMs);
this._metricsTimer = setInterval(() => this._collectMetrics(), this.config.metricsIntervalMs);
this._collectMetrics();
}
stop() {
this._running = false;
if (this._gcTimer) { clearInterval(this._gcTimer); this._gcTimer = null; }
if (this._metricsTimer) { clearInterval(this._metricsTimer); this._metricsTimer = null; }
this._log('🔴', 'إيقاف Performance Optimizer');
}
// ─── Memory Management ────────────────────────────────────────────────
_collectMetrics() {
if (!this._running) return;
try {
const mem = process.memoryUsage();
this.metrics.memory = {
used: Math.round(mem.heapUsed / 1024 / 1024),
total: Math.round(mem.heapTotal / 1024 / 1024),
limit: this.config.memoryLimitMB,
usage: Math.round((mem.heapUsed / 1024 / 1024 / this.config.memoryLimitMB) * 100),
};
this.metrics.cpu = {
usage: process.cpuUsage().user / 1000000,
loadAvg: require('os').loadavg().map(l => Math.round(l * 100) / 100),
};
this.metrics.uptime = Math.round(process.uptime());
this.metrics.cache.size = this.cache.size;
if (this.metrics.memory.usage > 85) {
this._log('⚠️', `ذاكرة عالية: ${this.metrics.memory.usage}%`);
this._aggressiveCleanup();
this.emit('memoryWarning', this.metrics.memory);
}
if (this.config.autoTune) this._autoTune();
this.emit('metrics', this.metrics);
} catch(_) {}
}
_runGC() {
if (!this._running) return;
try {
if (global.gc) {
const before = process.memoryUsage().heapUsed;
global.gc();
const after = process.memoryUsage().heapUsed;
const freed = Math.round((before - after) / 1024 / 1024);
this.metrics.gc.collections++;
this.metrics.gc.freed += freed;
this.metrics.gc.lastAt = tsNow();
if (freed > 1) this._log('🗑️', `GC: freed ${freed}MB`);
}
} catch(_) {}
}
_aggressiveCleanup() {
this.cache.clear();
this.pools.forEach(pool => { pool.length = 0; });
if (global.gc) try { global.gc(); } catch(_) {}
this._log('🧹', 'تنظيف عنيف للذاكرة');
}
_autoTune() {
const usage = this.metrics.memory.usage;
if (usage > 80) {
this.config.gcIntervalMs = Math.max(10000, this.config.gcIntervalMs - 5000);
this.config.maxCacheSize = Math.max(100, this.config.maxCacheSize - 100);
} else if (usage < 50) {
this.config.gcIntervalMs = Math.min(60000, this.config.gcIntervalMs + 5000);
this.config.maxCacheSize = Math.min(2000, this.config.maxCacheSize + 100);
}
}
// ─── Object Pooling ───────────────────────────────────────────────────
getPool(name, factory, initialSize = 10) {
if (!this.pools.has(name)) {
const pool = [];
for (let i = 0; i < initialSize; i++) pool.push(factory());
this.pools.set(name, pool);
}
return {
acquire: () => {
const pool = this.pools.get(name);
return pool.length > 0 ? pool.pop() : factory();
},
release: (obj) => {
const pool = this.pools.get(name);
if (pool.length < this.config.maxCacheSize) pool.push(obj);
},
};
}
// ─── Caching ──────────────────────────────────────────────────────────
cacheGet(key) {
const entry = this.cache.get(key);
if (entry && Date.now() - entry.time < (entry.ttl || 30000)) {
this.metrics.cache.hits++;
return entry.value;
}
this.metrics.cache.misses++;
if (entry) this.cache.delete(key);
return null;
}
cacheSet(key, value, ttlMs = 30000) {
if (this.cache.size >= this.config.maxCacheSize) {
const oldest = this.cache.keys().next().value;
if (oldest) this.cache.delete(oldest);
}
this.cache.set(key, { value, time: Date.now(), ttl: ttlMs });
}
cacheClear() {
this.cache.clear();
}
// ─── Throttling ───────────────────────────────────────────────────────
throttle(key, fn, delayMs) {
const last = this.throttled.get(key) || 0;
const now = Date.now();
if (now - last >= (delayMs || this.config.throttleMs)) {
this.throttled.set(key, now);
return fn();
}
return null;
}
// ─── Metrics API ──────────────────────────────────────────────────────
getMetrics() {
return { ...this.metrics };
}
getHealth() {
const m = this.metrics;
return {
status: m.memory.usage < 70 ? 'healthy' : m.memory.usage < 85 ? 'warning' : 'critical',
memory: `${m.memory.used}/${m.memory.limit}MB (${m.memory.usage}%)`,
cache: `hits: ${m.cache.hits}, misses: ${m.cache.misses}`,
gc: `collections: ${m.gc.collections}, freed: ${m.gc.freed}MB`,
uptime: `${Math.floor(m.uptime/3600)}h ${Math.floor((m.uptime%3600)/60)}m`,
};
}
destroy() {
this.stop();
this.cache.clear();
this.pools.clear();
this.throttled.clear();
this.removeAllListeners();
}
}
module.exports = { PerformanceOptimizer };