File size: 7,578 Bytes
b190b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/**

 * Polling Manager

 * Replaces WebSocket with intelligent HTTP polling

 * 

 * Features:

 * - Multiple concurrent polls with different intervals

 * - Auto-pause when page is hidden (Page Visibility API)

 * - Manual start/stop control

 * - Last update timestamp tracking

 * - Error handling and retry

 */

export class PollingManager {
  constructor() {
    this.polls = new Map();
    this.lastUpdates = new Map();
    this.isVisible = !document.hidden;
    this.updateCallbacks = new Map();
    
    // Listen to page visibility changes
    document.addEventListener('visibilitychange', () => {
      this.isVisible = !document.hidden;
      console.log(`[PollingManager] Page visibility changed: ${this.isVisible ? 'visible' : 'hidden'}`);
      
      if (this.isVisible) {
        this.resumeAll();
      } else {
        this.pauseAll();
      }
    });

    // Cleanup on page unload
    window.addEventListener('beforeunload', () => {
      this.stopAll();
    });

    console.log('[PollingManager] Initialized');
  }

  /**

   * Start polling an endpoint

   * @param {string} key - Unique identifier for this poll

   * @param {Function} fetchFunction - Async function that fetches data

   * @param {Function} callback - Function to call with fetched data

   * @param {number} interval - Polling interval in milliseconds

   */
  start(key, fetchFunction, callback, interval) {
    // Stop existing poll if any
    this.stop(key);

    const poll = {
      fetchFunction,
      callback,
      interval,
      timerId: null,
      isPaused: false,
      errorCount: 0,
      consecutiveErrors: 0,
      maxConsecutiveErrors: 5,
    };

    // Initial fetch (don't wait for interval)
    this._executePoll(key, poll);

    // Setup recurring interval
    poll.timerId = setInterval(() => {
      if (!poll.isPaused && this.isVisible) {
        this._executePoll(key, poll);
      }
    }, interval);

    this.polls.set(key, poll);
    console.log(`[PollingManager] Started polling: ${key} every ${interval}ms`);
  }

  /**

   * Execute a single poll

   */
  async _executePoll(key, poll) {
    try {
      console.log(`[PollingManager] Fetching: ${key}`);
      const data = await poll.fetchFunction();
      
      // Reset error count on success
      poll.consecutiveErrors = 0;
      
      // Update timestamp
      this.lastUpdates.set(key, Date.now());
      
      // Call success callback
      poll.callback(data, null);
      
      // Notify update callbacks
      this._notifyUpdateCallbacks(key);

    } catch (error) {
      poll.consecutiveErrors++;
      poll.errorCount++;
      
      console.error(`[PollingManager] Error in ${key} (${poll.consecutiveErrors}/${poll.maxConsecutiveErrors}):`, error);
      
      // Call error callback
      poll.callback(null, error);
      
      // Stop polling after too many consecutive errors
      if (poll.consecutiveErrors >= poll.maxConsecutiveErrors) {
        console.error(`[PollingManager] Too many consecutive errors, stopping ${key}`);
        this.stop(key);
      }
    }
  }

  /**

   * Stop polling for a specific key

   */
  stop(key) {
    const poll = this.polls.get(key);
    if (poll && poll.timerId) {
      clearInterval(poll.timerId);
      this.polls.delete(key);
      this.lastUpdates.delete(key);
      console.log(`[PollingManager] Stopped polling: ${key}`);
    }
  }

  /**

   * Pause a specific poll (keeps in memory, stops fetching)

   */
  pause(key) {
    const poll = this.polls.get(key);
    if (poll) {
      poll.isPaused = true;
      console.log(`[PollingManager] Paused: ${key}`);
    }
  }

  /**

   * Resume a specific poll

   */
  resume(key) {
    const poll = this.polls.get(key);
    if (poll) {
      poll.isPaused = false;
      // Immediate fetch on resume
      this._executePoll(key, poll);
      console.log(`[PollingManager] Resumed: ${key}`);
    }
  }

  /**

   * Pause all active polls (e.g., when page is hidden)

   */
  pauseAll() {
    console.log('[PollingManager] Pausing all polls');
    for (const [key, poll] of this.polls) {
      poll.isPaused = true;
    }
  }

  /**

   * Resume all paused polls (e.g., when page becomes visible)

   */
  resumeAll() {
    console.log('[PollingManager] Resuming all polls');
    for (const [key, poll] of this.polls) {
      if (poll.isPaused) {
        poll.isPaused = false;
        // Immediate fetch on resume
        this._executePoll(key, poll);
      }
    }
  }

  /**

   * Stop all polls and clear

   */
  stopAll() {
    console.log('[PollingManager] Stopping all polls');
    for (const key of this.polls.keys()) {
      this.stop(key);
    }
  }

  /**

   * Get last update timestamp for a poll

   */
  getLastUpdate(key) {
    return this.lastUpdates.get(key) || null;
  }

  /**

   * Get formatted "last updated" string

   */
  getLastUpdateText(key) {
    const timestamp = this.getLastUpdate(key);
    if (!timestamp) return 'Never';
    
    const seconds = Math.floor((Date.now() - timestamp) / 1000);
    
    if (seconds < 5) return 'Just now';
    if (seconds < 60) return `${seconds}s ago`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
    return `${Math.floor(seconds / 86400)}d ago`;
  }

  /**

   * Check if a poll is active

   */
  isActive(key) {
    return this.polls.has(key);
  }

  /**

   * Check if a poll is paused

   */
  isPaused(key) {
    const poll = this.polls.get(key);
    return poll ? poll.isPaused : false;
  }

  /**

   * Get all active poll keys

   */
  getActivePolls() {
    return Array.from(this.polls.keys());
  }

  /**

   * Get poll info

   */
  getPollInfo(key) {
    const poll = this.polls.get(key);
    if (!poll) return null;

    return {
      key,
      interval: poll.interval,
      isPaused: poll.isPaused,
      errorCount: poll.errorCount,
      consecutiveErrors: poll.consecutiveErrors,
      lastUpdate: this.getLastUpdateText(key),
      isActive: true,
    };
  }

  /**

   * Register callback for last update changes

   * Returns unsubscribe function

   */
  onLastUpdate(callback) {
    const id = Date.now() + Math.random();
    this.updateCallbacks.set(id, callback);
    
    // Return unsubscribe function
    return () => this.updateCallbacks.delete(id);
  }

  /**

   * Notify all update callbacks

   */
  _notifyUpdateCallbacks(key) {
    const text = this.getLastUpdateText(key);
    for (const callback of this.updateCallbacks.values()) {
      try {
        callback(key, text);
      } catch (error) {
        console.error('[PollingManager] Error in update callback:', error);
      }
    }
  }

  /**

   * Update all UI elements showing "last updated"

   * Call this in an interval (e.g., every second)

   */
  updateAllLastUpdateTexts() {
    for (const key of this.polls.keys()) {
      this._notifyUpdateCallbacks(key);
    }
  }
}

// ============================================================================
// EXPORT SINGLETON INSTANCE
// ============================================================================

export const pollingManager = new PollingManager();

// Auto-update "last updated" text every second
setInterval(() => {
  pollingManager.updateAllLastUpdateTexts();
}, 1000);

export default pollingManager;