/** * Real-time Sync via Server-Sent Events (SSE) * Replaces high-load short polling with zero-latency push notifications from server. */ export class RealtimeSync { constructor(onUpdateCallback) { this.onUpdate = onUpdateCallback; this.source = null; this.reconnectTimer = null; this.statusIndicator = null; } connect() { if (this.source) { this.source.close(); } try { this.source = new EventSource('/executive/api/events'); this.source.onopen = () => { this.updateStatus(true); }; this.source.addEventListener('state_change', (e) => { if (typeof this.onUpdate === 'function') { this.onUpdate(JSON.parse(e.data)); } }); this.source.onerror = () => { this.updateStatus(false); this.source.close(); // Exponential backoff reconnect clearTimeout(this.reconnectTimer); this.reconnectTimer = setTimeout(() => this.connect(), 4000); }; } catch (err) { console.warn('SSE connection initialization error:', err); this.updateStatus(false); } } updateStatus(connected) { const el = document.getElementById('syncIndicator'); if (el) { if (connected) { el.className = 'flex items-center gap-2 text-xs text-emerald-400 bg-emerald-950/40 px-2.5 py-1 rounded-full border border-emerald-500/30'; el.innerHTML = ' همگام‌سازی زنده (SSE)'; } else { el.className = 'flex items-center gap-2 text-xs text-rose-400 bg-rose-950/40 px-2.5 py-1 rounded-full border border-rose-500/30'; el.innerHTML = ' قطع ارتباط موقت'; } } } disconnect() { if (this.source) { this.source.close(); this.source = null; } clearTimeout(this.reconnectTimer); } }