File size: 8,645 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
'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 };