peerpigeon 0.0.8 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,11 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import { environmentDetector } from './EnvironmentDetector.js';
3
+ import DebugLogger from './DebugLogger.js';
3
4
 
4
5
  export class SignalingClient extends EventEmitter {
5
6
  constructor(peerId, maxPeers = 10, mesh = null) {
6
7
  super();
8
+ this.debug = DebugLogger.create('SignalingClient');
7
9
  this.peerId = peerId;
8
10
  this.maxPeers = maxPeers;
9
11
  this.mesh = mesh; // Reference to the mesh for peer coordination
@@ -32,7 +34,7 @@ export class SignalingClient extends EventEmitter {
32
34
 
33
35
  setConnectionType(type) {
34
36
  // WebSocket-only implementation, ignore connection type setting
35
- console.log(`WebSocket-only implementation - connection type setting ignored: ${type}`);
37
+ this.debug.log(`WebSocket-only implementation - connection type setting ignored: ${type}`);
36
38
  }
37
39
 
38
40
  createWebSocket(url) {
@@ -53,11 +55,11 @@ export class SignalingClient extends EventEmitter {
53
55
  return new WebSocket(url);
54
56
  } else {
55
57
  // In ES modules, dynamic import would be needed
56
- console.warn('WebSocket package detection not available in ES modules. Ensure "ws" is installed.');
58
+ this.debug.warn('WebSocket package detection not available in ES modules. Ensure "ws" is installed.');
57
59
  throw new Error('WebSocket not available in Node.js ES modules. Install the "ws" package and import it manually.');
58
60
  }
59
61
  } catch (error) {
60
- console.warn('ws package not found in Node.js environment. Install with: npm install ws');
62
+ this.debug.warn('ws package not found in Node.js environment. Install with: npm install ws');
61
63
  throw new Error('WebSocket not available in Node.js. Install the "ws" package.');
62
64
  }
63
65
  } else if (environmentDetector.isBrowser || environmentDetector.isWorker || environmentDetector.isNativeScript) {
@@ -71,7 +73,7 @@ export class SignalingClient extends EventEmitter {
71
73
  async sendSignalingMessage(message) {
72
74
  // Check connection health before sending
73
75
  if (!this.isConnected()) {
74
- console.log('WebSocket not connected, attempting to reconnect...');
76
+ this.debug.log('WebSocket not connected, attempting to reconnect...');
75
77
  if (!this.isReconnecting) {
76
78
  this.attemptReconnect();
77
79
  }
@@ -87,10 +89,10 @@ export class SignalingClient extends EventEmitter {
87
89
 
88
90
  try {
89
91
  this.websocket.send(JSON.stringify(payload));
90
- console.log('Sent WebSocket message:', payload.type);
92
+ this.debug.log('Sent WebSocket message:', payload.type);
91
93
  return { success: true };
92
94
  } catch (error) {
93
- console.error('Failed to send WebSocket message:', error);
95
+ this.debug.error('Failed to send WebSocket message:', error);
94
96
  // Trigger reconnection on send failure
95
97
  if (!this.isReconnecting) {
96
98
  this.attemptReconnect();
@@ -115,7 +117,7 @@ export class SignalingClient extends EventEmitter {
115
117
 
116
118
  // Prevent multiple simultaneous connection attempts
117
119
  if (this.connectionPromise) {
118
- console.log('Connection already in progress, waiting for completion...');
120
+ this.debug.log('Connection already in progress, waiting for completion...');
119
121
  return this.connectionPromise;
120
122
  }
121
123
 
@@ -159,7 +161,7 @@ export class SignalingClient extends EventEmitter {
159
161
  this.isReconnecting = false;
160
162
  this.connectionPromise = null;
161
163
 
162
- console.log('WebSocket connected');
164
+ this.debug.log('WebSocket connected');
163
165
  this.emit('statusChanged', { type: 'info', message: 'WebSocket connected' });
164
166
 
165
167
  // Send announce message
@@ -172,7 +174,7 @@ export class SignalingClient extends EventEmitter {
172
174
  this.emit('connected');
173
175
  resolve();
174
176
  }).catch(error => {
175
- console.error('Failed to send announce message:', error);
177
+ this.debug.error('Failed to send announce message:', error);
176
178
  this.startKeepAlive();
177
179
  // Removed health monitoring - keep-alive pings are sufficient
178
180
  this.emit('connected'); // Still emit connected even if announce fails
@@ -183,11 +185,11 @@ export class SignalingClient extends EventEmitter {
183
185
  this.websocket.onmessage = (event) => {
184
186
  try {
185
187
  const message = JSON.parse(event.data);
186
- console.log('Received WebSocket message:', message.type);
188
+ this.debug.log('Received WebSocket message:', message.type);
187
189
 
188
190
  if (message.type === 'connected') {
189
191
  // Connection confirmation from server
190
- console.log('WebSocket connection confirmed by server');
192
+ this.debug.log('WebSocket connection confirmed by server');
191
193
  } else if (message.type === 'pong') {
192
194
  // Handle pong response for health monitoring
193
195
  this.handlePong();
@@ -196,7 +198,7 @@ export class SignalingClient extends EventEmitter {
196
198
  this.emit('signalingMessage', message);
197
199
  }
198
200
  } catch (error) {
199
- console.error('Failed to parse WebSocket message:', error);
201
+ this.debug.error('Failed to parse WebSocket message:', error);
200
202
  }
201
203
  };
202
204
 
@@ -207,7 +209,7 @@ export class SignalingClient extends EventEmitter {
207
209
  this.stopKeepAlive();
208
210
  // Removed health monitoring stop - not using health monitoring
209
211
 
210
- console.log('WebSocket closed:', event.code, event.reason);
212
+ this.debug.log('WebSocket closed:', event.code, event.reason);
211
213
 
212
214
  if (event.code === 1000) {
213
215
  // Normal closure
@@ -223,7 +225,7 @@ export class SignalingClient extends EventEmitter {
223
225
 
224
226
  this.websocket.onerror = (error) => {
225
227
  clearTimeout(connectTimeout);
226
- console.error('WebSocket error:', error);
228
+ this.debug.error('WebSocket error:', error);
227
229
 
228
230
  if (this.websocket.readyState === WebSocket.CONNECTING) {
229
231
  this.connectionPromise = null;
@@ -247,10 +249,18 @@ export class SignalingClient extends EventEmitter {
247
249
 
248
250
  attemptReconnect() {
249
251
  if (this.isReconnecting) {
250
- console.log('Reconnection already in progress');
252
+ this.debug.log('Reconnection already in progress');
251
253
  return;
252
254
  }
253
255
 
256
+ // Check if we have healthy peer connections - if so, be less aggressive with reconnection
257
+ const hasHealthyPeers = this.mesh && this.mesh.connectionManager &&
258
+ this.mesh.connectionManager.getConnectedPeerCount() > 0;
259
+
260
+ if (hasHealthyPeers) {
261
+ this.debug.log('Have healthy peer connections, reducing reconnection urgency');
262
+ }
263
+
254
264
  // Clear any existing reconnect timeout
255
265
  if (this.reconnectTimeout) {
256
266
  clearTimeout(this.reconnectTimeout);
@@ -258,9 +268,10 @@ export class SignalingClient extends EventEmitter {
258
268
  }
259
269
 
260
270
  if (this.reconnectAttempts >= this.maxReconnectAttempts) {
261
- console.log('Max reconnection attempts reached, using exponential backoff');
262
- // Don't give up completely, but use longer delays
263
- const extendedDelay = Math.min(this.maxReconnectDelay * 2, 300000); // Max 5 minutes
271
+ this.debug.log('Max reconnection attempts reached, using exponential backoff');
272
+ // If we have healthy peers, use much longer delays to avoid disrupting the mesh
273
+ const baseExtendedDelay = hasHealthyPeers ? 600000 : this.maxReconnectDelay * 2; // 10 min vs 2x normal
274
+ const extendedDelay = Math.min(baseExtendedDelay, 600000); // Max 10 minutes
264
275
  this.reconnectTimeout = setTimeout(() => {
265
276
  this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2); // Reset to half max
266
277
  this.attemptReconnect();
@@ -270,9 +281,13 @@ export class SignalingClient extends EventEmitter {
270
281
 
271
282
  this.isReconnecting = true;
272
283
  this.reconnectAttempts++;
273
- const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), this.maxReconnectDelay);
274
284
 
275
- console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
285
+ // Use longer delays if we have healthy peer connections
286
+ const baseDelay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
287
+ const delayMultiplier = hasHealthyPeers ? 3 : 1; // 3x longer delay if peers are healthy
288
+ const delay = Math.min(baseDelay * delayMultiplier, hasHealthyPeers ? 300000 : this.maxReconnectDelay);
289
+
290
+ this.debug.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts}, healthy peers: ${hasHealthyPeers})`);
276
291
 
277
292
  this.reconnectTimeout = setTimeout(async () => {
278
293
  if (!this.connected && this.signalingUrl) {
@@ -280,7 +295,7 @@ export class SignalingClient extends EventEmitter {
280
295
  await this.connect(this.signalingUrl);
281
296
  this.emit('statusChanged', { type: 'info', message: 'WebSocket reconnected successfully' });
282
297
  } catch (error) {
283
- console.error('Reconnection failed:', error);
298
+ this.debug.error('Reconnection failed:', error);
284
299
  this.isReconnecting = false;
285
300
  this.attemptReconnect();
286
301
  }
@@ -325,7 +340,7 @@ export class SignalingClient extends EventEmitter {
325
340
  if (!this.connected) return;
326
341
 
327
342
  try {
328
- console.log('Sending goodbye message');
343
+ this.debug.log('Sending goodbye message');
329
344
 
330
345
  if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
331
346
  this.websocket.send(JSON.stringify({
@@ -338,7 +353,7 @@ export class SignalingClient extends EventEmitter {
338
353
  }));
339
354
  }
340
355
  } catch (error) {
341
- console.error('Failed to send goodbye message:', error);
356
+ this.debug.error('Failed to send goodbye message:', error);
342
357
  }
343
358
  }
344
359
 
@@ -357,28 +372,28 @@ export class SignalingClient extends EventEmitter {
357
372
  targetPeerId
358
373
  });
359
374
  } catch (error) {
360
- console.log(`Cleanup message failed for ${targetPeerId}:`, error.message);
375
+ this.debug.log(`Cleanup message failed for ${targetPeerId}:`, error.message);
361
376
  }
362
377
  }
363
378
 
364
379
  startKeepAlive() {
365
380
  if (this.keepAliveInterval) return;
366
381
 
367
- console.log('Starting keep-alive pings every', this.keepAliveIntervalMs / 1000, 'seconds');
382
+ this.debug.log('Starting keep-alive pings every', this.keepAliveIntervalMs / 1000, 'seconds');
368
383
 
369
384
  const keepAliveCallback = () => {
370
385
  if (this.connected) {
371
386
  // Check if this peer should send the ping
372
387
  if (this.shouldSendKeepAlivePing()) {
373
- console.log('Sending keep-alive ping (designated peer)');
388
+ this.debug.log('Sending keep-alive ping (designated peer)');
374
389
  this.sendSignalingMessage({
375
390
  type: 'ping',
376
391
  data: { peerId: this.peerId }
377
392
  }).catch(error => {
378
- console.error('Keep-alive ping failed:', error);
393
+ this.debug.error('Keep-alive ping failed:', error);
379
394
  });
380
395
  } else {
381
- console.log('Skipping keep-alive ping (not designated peer)');
396
+ this.debug.log('Skipping keep-alive ping (not designated peer)');
382
397
  }
383
398
  }
384
399
  };
@@ -417,7 +432,7 @@ export class SignalingClient extends EventEmitter {
417
432
  const designatedPeer = allPeerIds[0];
418
433
 
419
434
  const isDesignated = designatedPeer === this.peerId;
420
- console.log(`Keep-alive ping decision: ${isDesignated ? 'SEND' : 'SKIP'} (this: ${this.peerId.substring(0, 8)}, designated: ${designatedPeer.substring(0, 8)}, total peers: ${allPeerIds.length})`);
435
+ this.debug.log(`Keep-alive ping decision: ${isDesignated ? 'SEND' : 'SKIP'} (this: ${this.peerId.substring(0, 8)}, designated: ${designatedPeer.substring(0, 8)}, total peers: ${allPeerIds.length})`);
421
436
 
422
437
  return isDesignated;
423
438
  }
@@ -426,19 +441,19 @@ export class SignalingClient extends EventEmitter {
426
441
  if (this.keepAliveInterval) {
427
442
  clearInterval(this.keepAliveInterval);
428
443
  this.keepAliveInterval = null;
429
- console.log('Stopped keep-alive pings');
444
+ this.debug.log('Stopped keep-alive pings');
430
445
  }
431
446
  }
432
447
 
433
448
  startHealthMonitoring() {
434
449
  if (this.healthCheckInterval) return;
435
450
 
436
- console.log('Starting connection health monitoring');
451
+ this.debug.log('Starting connection health monitoring');
437
452
 
438
453
  const healthCheckCallback = () => {
439
454
  // Check WebSocket state first
440
455
  if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
441
- console.warn('WebSocket is not in OPEN state:', this.websocket?.readyState);
456
+ this.debug.warn('WebSocket is not in OPEN state:', this.websocket?.readyState);
442
457
  this.handleUnhealthyConnection();
443
458
  return;
444
459
  }
@@ -449,7 +464,7 @@ export class SignalingClient extends EventEmitter {
449
464
  // Only check for pong timeout if we have a pending ping
450
465
  if (this.pingTimeout) {
451
466
  // There's already a ping waiting for pong, don't send another
452
- console.log('Ping already pending, waiting for pong...');
467
+ this.debug.log('Ping already pending, waiting for pong...');
453
468
  return;
454
469
  }
455
470
 
@@ -457,7 +472,7 @@ export class SignalingClient extends EventEmitter {
457
472
  if (this.lastPingTime && this.lastPongTime &&
458
473
  (this.lastPingTime > this.lastPongTime) &&
459
474
  (now - this.lastPingTime > this.connectionQualityTimeout)) {
460
- console.warn('Connection unhealthy - ping/pong timeout');
475
+ this.debug.warn('Connection unhealthy - ping/pong timeout');
461
476
  this.handleUnhealthyConnection();
462
477
  return;
463
478
  }
@@ -478,7 +493,7 @@ export class SignalingClient extends EventEmitter {
478
493
  if (this.healthCheckInterval) {
479
494
  clearInterval(this.healthCheckInterval);
480
495
  this.healthCheckInterval = null;
481
- console.log('Stopped connection health monitoring');
496
+ this.debug.log('Stopped connection health monitoring');
482
497
  }
483
498
 
484
499
  if (this.pingTimeout) {
@@ -499,7 +514,7 @@ export class SignalingClient extends EventEmitter {
499
514
  }
500
515
 
501
516
  this.pingTimeout = setTimeout(() => {
502
- console.warn('Health ping timeout - connection may be unhealthy');
517
+ this.debug.warn('Health ping timeout - connection may be unhealthy');
503
518
  this.handleUnhealthyConnection();
504
519
  }, this.connectionQualityTimeout);
505
520
 
@@ -509,9 +524,9 @@ export class SignalingClient extends EventEmitter {
509
524
  data: { peerId: this.peerId, timestamp: this.lastPingTime }
510
525
  }));
511
526
 
512
- console.log('Sent health ping');
527
+ this.debug.log('Sent health ping');
513
528
  } catch (error) {
514
- console.error('Failed to send health ping:', error);
529
+ this.debug.error('Failed to send health ping:', error);
515
530
  this.handleUnhealthyConnection();
516
531
  }
517
532
  }
@@ -524,11 +539,11 @@ export class SignalingClient extends EventEmitter {
524
539
  this.pingTimeout = null;
525
540
  }
526
541
 
527
- console.log('Received pong - connection healthy');
542
+ this.debug.log('Received pong - connection healthy');
528
543
  }
529
544
 
530
545
  handleUnhealthyConnection() {
531
- console.warn('Detected unhealthy WebSocket connection, forcing reconnection');
546
+ this.debug.warn('Detected unhealthy WebSocket connection, forcing reconnection');
532
547
  this.emit('statusChanged', { type: 'warning', message: 'Connection health degraded - reconnecting...' });
533
548
 
534
549
  // Force close and reconnect
@@ -544,7 +559,7 @@ export class SignalingClient extends EventEmitter {
544
559
 
545
560
  forceHealthCheck() {
546
561
  if (!this.isConnected()) {
547
- console.log('Connection not healthy, triggering reconnection');
562
+ this.debug.log('Connection not healthy, triggering reconnection');
548
563
  if (!this.isReconnecting) {
549
564
  this.attemptReconnect();
550
565
  }
@@ -563,15 +578,15 @@ export class SignalingClient extends EventEmitter {
563
578
  if (!this.connected) return;
564
579
 
565
580
  if (this.shouldSendKeepAlivePing()) {
566
- console.log('Topology changed - sending immediate keep-alive ping as new designated peer');
581
+ this.debug.log('Topology changed - sending immediate keep-alive ping as new designated peer');
567
582
  this.sendSignalingMessage({
568
583
  type: 'ping',
569
584
  data: { peerId: this.peerId }
570
585
  }).catch(error => {
571
- console.error('Immediate keep-alive ping failed:', error);
586
+ this.debug.error('Immediate keep-alive ping failed:', error);
572
587
  });
573
588
  } else {
574
- console.log('Topology changed - not designated for keep-alive pings');
589
+ this.debug.log('Topology changed - not designated for keep-alive pings');
575
590
  }
576
591
  }
577
592