ipfrs-network 0.2.0

Peer-to-peer networking layer with libp2p and QUIC for IPFRS
Documentation
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! QUIC Connection Migration for Mobile Support
//!
//! This module implements QUIC connection migration to handle network changes
//! seamlessly, particularly important for mobile devices switching between
//! WiFi, cellular, and other network interfaces.
//!
//! ## Features
//!
//! - Automatic detection of network interface changes
//! - Seamless connection migration without data loss
//! - State preservation during migration
//! - Retry logic for failed migrations
//! - Statistics tracking for migration events
//!
//! ## Use Cases
//!
//! - Mobile devices switching from WiFi to cellular
//! - Laptops moving between networks
//! - Devices with multiple network interfaces
//! - Network interface failures requiring fallback

use dashmap::DashMap;
use libp2p::{Multiaddr, PeerId};
use parking_lot::RwLock;
use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
use tracing::{debug, info, warn};

/// Errors that can occur during connection migration
#[derive(Debug, Error)]
pub enum MigrationError {
    #[error("No active connection to migrate")]
    NoActiveConnection,

    #[error("Migration already in progress")]
    MigrationInProgress,

    #[error("Migration failed: {0}")]
    MigrationFailed(String),

    #[error("Timeout during migration")]
    MigrationTimeout,

    #[error("Invalid migration state")]
    InvalidState,

    #[error("No suitable migration path available")]
    NoMigrationPath,
}

/// Connection migration configuration
#[derive(Debug, Clone)]
pub struct MigrationConfig {
    /// Enable automatic migration on network changes
    pub auto_migrate: bool,

    /// Maximum time to wait for migration to complete
    pub migration_timeout: Duration,

    /// Maximum number of migration retry attempts
    pub max_retry_attempts: usize,

    /// Backoff duration between retry attempts
    pub retry_backoff: Duration,

    /// Minimum time between migrations for the same connection
    pub migration_cooldown: Duration,

    /// Keep old path alive during migration (default: true for safety)
    pub keep_old_path: bool,

    /// Validate new path before closing old path
    pub validate_new_path: bool,
}

impl Default for MigrationConfig {
    fn default() -> Self {
        Self {
            auto_migrate: true,
            migration_timeout: Duration::from_secs(30),
            max_retry_attempts: 3,
            retry_backoff: Duration::from_secs(2),
            migration_cooldown: Duration::from_secs(10),
            keep_old_path: true,
            validate_new_path: true,
        }
    }
}

impl MigrationConfig {
    /// Create a mobile-optimized configuration
    ///
    /// Aggressive migration settings for mobile devices that frequently
    /// switch between WiFi and cellular networks.
    pub fn mobile() -> Self {
        Self {
            auto_migrate: true,
            migration_timeout: Duration::from_secs(15),
            max_retry_attempts: 5,
            retry_backoff: Duration::from_millis(500),
            migration_cooldown: Duration::from_secs(5),
            keep_old_path: true,
            validate_new_path: true,
        }
    }

    /// Create a conservative configuration
    ///
    /// More cautious migration settings for stable networks where
    /// migrations are rare.
    pub fn conservative() -> Self {
        Self {
            auto_migrate: false,
            migration_timeout: Duration::from_secs(60),
            max_retry_attempts: 2,
            retry_backoff: Duration::from_secs(5),
            migration_cooldown: Duration::from_secs(30),
            keep_old_path: true,
            validate_new_path: true,
        }
    }
}

/// State of a connection migration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MigrationState {
    /// No migration in progress
    Idle,
    /// Migration initiated
    Initiated,
    /// Validating new network path
    Validating,
    /// Transferring connection state
    Migrating,
    /// Migration completed successfully
    Completed,
    /// Migration failed
    Failed,
}

/// Information about a connection migration attempt
#[derive(Debug, Clone)]
pub struct MigrationAttempt {
    /// Peer being migrated
    pub peer_id: PeerId,
    /// Old network address
    pub old_address: Multiaddr,
    /// New network address
    pub new_address: Multiaddr,
    /// Current migration state
    pub state: MigrationState,
    /// When the migration started
    pub started_at: Instant,
    /// Number of retry attempts
    pub retry_count: usize,
    /// Error message if failed
    pub error: Option<String>,
}

/// Connection migration statistics
#[derive(Debug, Clone, Default)]
pub struct MigrationStats {
    /// Total number of migration attempts
    pub total_attempts: usize,
    /// Number of successful migrations
    pub successful_migrations: usize,
    /// Number of failed migrations
    pub failed_migrations: usize,
    /// Number of migrations in progress
    pub in_progress: usize,
    /// Average migration duration (milliseconds)
    pub avg_duration_ms: u64,
    /// Total retry attempts
    pub total_retries: usize,
}

/// Manages QUIC connection migration
pub struct ConnectionMigrationManager {
    /// Configuration
    config: MigrationConfig,
    /// Active migration attempts
    active_migrations: Arc<DashMap<PeerId, MigrationAttempt>>,
    /// Last migration time per peer (for cooldown)
    last_migration: Arc<DashMap<PeerId, Instant>>,
    /// Migration statistics
    stats: Arc<RwLock<MigrationStats>>,
    /// Migration history (for tracking durations)
    migration_durations: Arc<RwLock<Vec<u64>>>,
}

impl ConnectionMigrationManager {
    /// Create a new connection migration manager
    pub fn new(config: MigrationConfig) -> Self {
        Self {
            config,
            active_migrations: Arc::new(DashMap::new()),
            last_migration: Arc::new(DashMap::new()),
            stats: Arc::new(RwLock::new(MigrationStats::default())),
            migration_durations: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Create with mobile-optimized configuration
    pub fn mobile() -> Self {
        Self::new(MigrationConfig::mobile())
    }

    /// Create with conservative configuration
    pub fn conservative() -> Self {
        Self::new(MigrationConfig::conservative())
    }

    /// Initiate migration for a peer connection
    ///
    /// # Arguments
    ///
    /// * `peer_id` - The peer to migrate
    /// * `old_address` - Current network address
    /// * `new_address` - New network address to migrate to
    ///
    /// # Returns
    ///
    /// Ok if migration was initiated, Err if migration cannot start
    pub fn initiate_migration(
        &self,
        peer_id: PeerId,
        old_address: Multiaddr,
        new_address: Multiaddr,
    ) -> Result<(), MigrationError> {
        // Check if migration is already in progress
        if self.active_migrations.contains_key(&peer_id) {
            return Err(MigrationError::MigrationInProgress);
        }

        // Check cooldown period
        if let Some(last) = self.last_migration.get(&peer_id) {
            if last.elapsed() < self.config.migration_cooldown {
                debug!(
                    "Migration cooldown active for peer {} ({:?} remaining)",
                    peer_id,
                    self.config.migration_cooldown - last.elapsed()
                );
                return Err(MigrationError::InvalidState);
            }
        }

        info!(
            "Initiating connection migration for peer {} from {} to {}",
            peer_id, old_address, new_address
        );

        // Create migration attempt
        let attempt = MigrationAttempt {
            peer_id,
            old_address,
            new_address,
            state: MigrationState::Initiated,
            started_at: Instant::now(),
            retry_count: 0,
            error: None,
        };

        // Record the attempt
        self.active_migrations.insert(peer_id, attempt);

        // Update statistics
        let mut stats = self.stats.write();
        stats.total_attempts += 1;
        stats.in_progress += 1;

        Ok(())
    }

    /// Update the state of an ongoing migration
    pub fn update_migration_state(
        &self,
        peer_id: &PeerId,
        new_state: MigrationState,
    ) -> Result<(), MigrationError> {
        if let Some(mut attempt) = self.active_migrations.get_mut(peer_id) {
            debug!(
                "Migration state change for peer {}: {:?} -> {:?}",
                peer_id, attempt.state, new_state
            );
            attempt.state = new_state;
            Ok(())
        } else {
            Err(MigrationError::NoActiveConnection)
        }
    }

    /// Mark a migration as completed successfully
    pub fn complete_migration(&self, peer_id: &PeerId) -> Result<(), MigrationError> {
        if let Some((_, attempt)) = self.active_migrations.remove(peer_id) {
            let duration_ms = attempt.started_at.elapsed().as_millis() as u64;

            info!(
                "Migration completed for peer {} in {} ms",
                peer_id, duration_ms
            );

            // Update last migration time
            self.last_migration.insert(*peer_id, Instant::now());

            // Update statistics
            {
                let mut stats = self.stats.write();
                stats.successful_migrations += 1;
                stats.in_progress = stats.in_progress.saturating_sub(1);
                stats.total_retries += attempt.retry_count;
            }

            // Record duration for average calculation
            {
                let mut durations = self.migration_durations.write();
                durations.push(duration_ms);

                // Keep only last 100 durations to prevent unbounded growth
                if durations.len() > 100 {
                    durations.remove(0);
                }

                // Update average
                let avg = durations.iter().sum::<u64>() / durations.len() as u64;
                self.stats.write().avg_duration_ms = avg;
            }

            Ok(())
        } else {
            Err(MigrationError::NoActiveConnection)
        }
    }

    /// Mark a migration as failed
    pub fn fail_migration(&self, peer_id: &PeerId, error: String) -> Result<(), MigrationError> {
        if let Some((_, mut attempt)) = self.active_migrations.remove(peer_id) {
            warn!("Migration failed for peer {}: {}", peer_id, error);

            attempt.error = Some(error);
            attempt.state = MigrationState::Failed;

            // Update statistics
            let mut stats = self.stats.write();
            stats.failed_migrations += 1;
            stats.in_progress = stats.in_progress.saturating_sub(1);
            stats.total_retries += attempt.retry_count;

            Ok(())
        } else {
            Err(MigrationError::NoActiveConnection)
        }
    }

    /// Retry a failed migration
    pub fn retry_migration(&self, peer_id: &PeerId) -> Result<(), MigrationError> {
        if let Some(mut attempt) = self.active_migrations.get_mut(peer_id) {
            if attempt.retry_count >= self.config.max_retry_attempts {
                return Err(MigrationError::MigrationFailed(
                    "Max retry attempts reached".to_string(),
                ));
            }

            attempt.retry_count += 1;
            attempt.state = MigrationState::Initiated;
            attempt.error = None;

            info!(
                "Retrying migration for peer {} (attempt {})",
                peer_id,
                attempt.retry_count + 1
            );

            Ok(())
        } else {
            Err(MigrationError::NoActiveConnection)
        }
    }

    /// Check if a migration is in progress for a peer
    pub fn is_migrating(&self, peer_id: &PeerId) -> bool {
        self.active_migrations.contains_key(peer_id)
    }

    /// Get the current migration state for a peer
    pub fn get_migration_state(&self, peer_id: &PeerId) -> Option<MigrationState> {
        self.active_migrations
            .get(peer_id)
            .map(|attempt| attempt.state)
    }

    /// Get all active migration attempts
    pub fn get_active_migrations(&self) -> Vec<MigrationAttempt> {
        self.active_migrations
            .iter()
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Get migration statistics
    pub fn stats(&self) -> MigrationStats {
        self.stats.read().clone()
    }

    /// Check if a peer can be migrated (respects cooldown)
    pub fn can_migrate(&self, peer_id: &PeerId) -> bool {
        if self.active_migrations.contains_key(peer_id) {
            return false;
        }

        if let Some(last) = self.last_migration.get(peer_id) {
            last.elapsed() >= self.config.migration_cooldown
        } else {
            true
        }
    }

    /// Get the configuration
    pub fn config(&self) -> &MigrationConfig {
        &self.config
    }

    /// Clean up timed-out migrations
    pub fn cleanup_timeouts(&self) {
        let timeout = self.config.migration_timeout;
        let mut timed_out = Vec::new();

        for entry in self.active_migrations.iter() {
            if entry.value().started_at.elapsed() > timeout {
                timed_out.push(*entry.key());
            }
        }

        for peer_id in timed_out {
            self.fail_migration(&peer_id, "Migration timeout".to_string())
                .ok();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    fn test_peer_id() -> PeerId {
        PeerId::random()
    }

    fn test_addr() -> Multiaddr {
        Multiaddr::from_str("/ip4/127.0.0.1/tcp/4001").expect("test: valid multiaddr literal")
    }

    fn test_addr2() -> Multiaddr {
        Multiaddr::from_str("/ip4/192.168.1.1/tcp/4001").expect("test: valid multiaddr literal")
    }

    #[test]
    fn test_migration_config_default() {
        let config = MigrationConfig::default();
        assert!(config.auto_migrate);
        assert!(config.keep_old_path);
        assert!(config.validate_new_path);
    }

    #[test]
    fn test_migration_config_mobile() {
        let config = MigrationConfig::mobile();
        assert!(config.auto_migrate);
        assert_eq!(config.max_retry_attempts, 5);
        assert_eq!(config.migration_cooldown, Duration::from_secs(5));
    }

    #[test]
    fn test_migration_config_conservative() {
        let config = MigrationConfig::conservative();
        assert!(!config.auto_migrate);
        assert_eq!(config.max_retry_attempts, 2);
        assert_eq!(config.migration_cooldown, Duration::from_secs(30));
    }

    #[test]
    fn test_initiate_migration() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer = test_peer_id();
        let old_addr = test_addr();
        let new_addr = test_addr2();

        let result = manager.initiate_migration(peer, old_addr, new_addr);
        assert!(result.is_ok());

        let stats = manager.stats();
        assert_eq!(stats.total_attempts, 1);
        assert_eq!(stats.in_progress, 1);
    }

    #[test]
    fn test_migration_in_progress_error() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer = test_peer_id();
        let old_addr = test_addr();
        let new_addr = test_addr2();

        manager
            .initiate_migration(peer, old_addr.clone(), new_addr.clone())
            .expect("test: first migration initiation should succeed");

        let result = manager.initiate_migration(peer, old_addr, new_addr);
        assert!(matches!(result, Err(MigrationError::MigrationInProgress)));
    }

    #[test]
    fn test_complete_migration() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer = test_peer_id();

        manager
            .initiate_migration(peer, test_addr(), test_addr2())
            .expect("test: migration initiation should succeed");
        let result = manager.complete_migration(&peer);

        assert!(result.is_ok());

        let stats = manager.stats();
        assert_eq!(stats.successful_migrations, 1);
        assert_eq!(stats.in_progress, 0);
    }

    #[test]
    fn test_fail_migration() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer = test_peer_id();

        manager
            .initiate_migration(peer, test_addr(), test_addr2())
            .expect("test: migration initiation should succeed");
        let result = manager.fail_migration(&peer, "Test error".to_string());

        assert!(result.is_ok());

        let stats = manager.stats();
        assert_eq!(stats.failed_migrations, 1);
        assert_eq!(stats.in_progress, 0);
    }

    #[test]
    fn test_retry_migration() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer = test_peer_id();

        manager
            .initiate_migration(peer, test_addr(), test_addr2())
            .expect("test: migration initiation should succeed");

        let result = manager.retry_migration(&peer);
        assert!(result.is_ok());

        let attempt = manager
            .active_migrations
            .get(&peer)
            .expect("test: active migration entry should exist");
        assert_eq!(attempt.retry_count, 1);
    }

    #[test]
    fn test_retry_limit() {
        let config = MigrationConfig {
            max_retry_attempts: 2,
            ..Default::default()
        };
        let manager = ConnectionMigrationManager::new(config);
        let peer = test_peer_id();

        manager
            .initiate_migration(peer, test_addr(), test_addr2())
            .expect("test: migration initiation should succeed");

        // First retry should succeed
        assert!(manager.retry_migration(&peer).is_ok());
        // Second retry should succeed
        assert!(manager.retry_migration(&peer).is_ok());
        // Third retry should fail (max reached)
        assert!(matches!(
            manager.retry_migration(&peer),
            Err(MigrationError::MigrationFailed(_))
        ));
    }

    #[test]
    fn test_is_migrating() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer = test_peer_id();

        assert!(!manager.is_migrating(&peer));

        manager
            .initiate_migration(peer, test_addr(), test_addr2())
            .expect("test: migration initiation should succeed");
        assert!(manager.is_migrating(&peer));

        manager
            .complete_migration(&peer)
            .expect("test: complete_migration should succeed");
        assert!(!manager.is_migrating(&peer));
    }

    #[test]
    fn test_migration_state_updates() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer = test_peer_id();

        manager
            .initiate_migration(peer, test_addr(), test_addr2())
            .expect("test: migration initiation should succeed");

        assert_eq!(
            manager.get_migration_state(&peer),
            Some(MigrationState::Initiated)
        );

        manager
            .update_migration_state(&peer, MigrationState::Validating)
            .expect("test: update_migration_state to Validating should succeed");
        assert_eq!(
            manager.get_migration_state(&peer),
            Some(MigrationState::Validating)
        );

        manager
            .update_migration_state(&peer, MigrationState::Migrating)
            .expect("test: update_migration_state to Migrating should succeed");
        assert_eq!(
            manager.get_migration_state(&peer),
            Some(MigrationState::Migrating)
        );
    }

    #[test]
    fn test_can_migrate() {
        let config = MigrationConfig {
            migration_cooldown: Duration::from_millis(100),
            ..Default::default()
        };
        let manager = ConnectionMigrationManager::new(config);
        let peer = test_peer_id();

        assert!(manager.can_migrate(&peer));

        manager
            .initiate_migration(peer, test_addr(), test_addr2())
            .expect("test: migration initiation should succeed");
        assert!(!manager.can_migrate(&peer));

        manager
            .complete_migration(&peer)
            .expect("test: complete_migration should succeed");
        assert!(!manager.can_migrate(&peer)); // Cooldown active

        std::thread::sleep(Duration::from_millis(150));
        assert!(manager.can_migrate(&peer)); // Cooldown expired
    }

    #[test]
    fn test_get_active_migrations() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer1 = test_peer_id();
        let peer2 = test_peer_id();

        manager
            .initiate_migration(peer1, test_addr(), test_addr2())
            .expect("test: peer1 migration initiation should succeed");
        manager
            .initiate_migration(peer2, test_addr(), test_addr2())
            .expect("test: peer2 migration initiation should succeed");

        let active = manager.get_active_migrations();
        assert_eq!(active.len(), 2);
    }

    #[test]
    fn test_average_duration_calculation() {
        let manager = ConnectionMigrationManager::new(MigrationConfig::default());
        let peer1 = test_peer_id();
        let peer2 = test_peer_id();

        manager
            .initiate_migration(peer1, test_addr(), test_addr2())
            .expect("test: peer1 migration initiation should succeed");
        std::thread::sleep(Duration::from_millis(10));
        manager
            .complete_migration(&peer1)
            .expect("test: peer1 complete_migration should succeed");

        manager
            .initiate_migration(peer2, test_addr(), test_addr2())
            .expect("test: peer2 migration initiation should succeed");
        std::thread::sleep(Duration::from_millis(10));
        manager
            .complete_migration(&peer2)
            .expect("test: peer2 complete_migration should succeed");

        let stats = manager.stats();
        assert!(stats.avg_duration_ms > 0);
    }
}