api_openai 0.3.0

OpenAI's API for accessing large language models (LLMs).
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Enhanced WebSocket Reliability Tests
//!
//! This module provides comprehensive testing for WebSocket reliability features including:
//! - Connection establishment and failure scenarios
//! - Automatic reconnection and backoff strategies
//! - Message delivery guarantees and buffering
//! - Connection health monitoring and keepalive
//! - Network interruption and recovery testing
//! - Concurrent connection management
//! - Error handling and graceful degradation

#![ allow( clippy::unreadable_literal ) ]
#![ allow( clippy::uninlined_format_args ) ]
#![ allow( clippy::std_instead_of_core ) ]
#![ allow( clippy::useless_vec ) ]
#![ allow( clippy::unused_async ) ]
#![ allow( clippy::must_use_candidate ) ]
#![ allow( clippy::missing_panics_doc ) ]
#![ allow( clippy::missing_errors_doc ) ]
#![ allow( clippy::doc_markdown ) ]
#![ allow( clippy::needless_continue ) ]
#![ allow( clippy::redundant_else ) ]

use api_openai::
{
  realtime ::WsSession,
  error ::{ OpenAIError, Result },
};
use std::
{
  collections ::VecDeque,
  sync ::{ Arc, Mutex },
  time ::{ Duration, Instant },
};
use tokio::
{
  sync ::{ RwLock, Semaphore },
  time ::{ timeout, sleep, interval },
};
// Note : Serialize/Deserialize removed since Instant doesn't support them

/// Configuration for WebSocket reliability testing
#[ derive( Debug, Clone ) ]
pub struct WsReliabilityConfig
{
  /// Maximum number of reconnection attempts
  pub max_reconnection_attempts : usize,
  /// Initial reconnection delay
  pub initial_reconnection_delay : Duration,
  /// Maximum reconnection delay
  pub max_reconnection_delay : Duration,
  /// Connection timeout duration
  pub connection_timeout : Duration,
  /// Heartbeat interval for keepalive
  pub heartbeat_interval : Duration,
  /// Message buffer size
  pub message_buffer_size : usize,
  /// Health check interval
  pub health_check_interval : Duration,
}

impl Default for WsReliabilityConfig
{
  fn default() -> Self
  {
    Self
    {
      max_reconnection_attempts : 5,
      initial_reconnection_delay : Duration::from_millis( 1000 ),
      max_reconnection_delay : Duration::from_secs( 30 ),
      connection_timeout : Duration::from_secs( 10 ),
      heartbeat_interval : Duration::from_secs( 30 ),
      message_buffer_size : 1000,
      health_check_interval : Duration::from_secs( 5 ),
    }
  }
}

/// WebSocket connection statistics for reliability monitoring
#[ derive( Debug, Clone ) ]
pub struct WsConnectionStats
{
  /// Total connection attempts
  pub connection_attempts : u64,
  /// Successful connections
  pub successful_connections : u64,
  /// Failed connections
  pub failed_connections : u64,
  /// Total reconnections
  pub reconnections : u64,
  /// Messages sent successfully
  pub messages_sent : u64,
  /// Messages received successfully
  pub messages_received : u64,
  /// Message send failures
  pub message_send_failures : u64,
  /// Connection interruptions
  pub connection_interruptions : u64,
  /// Average connection duration
  pub average_connection_duration : Duration,
  /// Last connection timestamp
  pub last_connection_time : Option< Instant >,
}

impl Default for WsConnectionStats
{
  fn default() -> Self
  {
    Self
    {
      connection_attempts : 0,
      successful_connections : 0,
      failed_connections : 0,
      reconnections : 0,
      messages_sent : 0,
      messages_received : 0,
      message_send_failures : 0,
      connection_interruptions : 0,
      average_connection_duration : Duration::from_secs( 0 ),
      last_connection_time : None,
    }
  }
}

/// Enhanced WebSocket session with reliability features
#[ derive( Debug ) ]
pub struct EnhancedWsSession
{
  /// Current WebSocket session
  current_session : Arc< RwLock< Option< WsSession > > >,
  /// Configuration
  config : WsReliabilityConfig,
  /// Connection statistics
  stats : Arc< RwLock< WsConnectionStats > >,
  /// Message buffer for reliability
  message_buffer : Arc< Mutex< VecDeque< String > > >,
  /// Connection URL
  url : String,
  /// Reconnection state
  reconnection_count : Arc< Mutex< usize > >,
  /// Last heartbeat timestamp
  last_heartbeat : Arc< Mutex< Option< Instant > > >,
}

impl EnhancedWsSession
{
  /// Create a new enhanced WebSocket session
  pub fn new( url : String, config : WsReliabilityConfig ) -> Self
  {
    Self
    {
      current_session : Arc::new( RwLock::new( None ) ),
      config,
      stats : Arc::new( RwLock::new( WsConnectionStats::default() ) ),
      message_buffer : Arc::new( Mutex::new( VecDeque::new() ) ),
      url,
      reconnection_count : Arc::new( Mutex::new( 0 ) ),
      last_heartbeat : Arc::new( Mutex::new( None ) ),
    }
  }

  /// Connect with reliability features
  pub async fn connect_with_reliability( &self ) -> Result< () >
  {
    let mut attempts = 0;
    let mut delay = self.config.initial_reconnection_delay;

    loop
    {
      {
        let mut stats = self.stats.write().await;
        stats.connection_attempts += 1;
      }

      match timeout( self.config.connection_timeout, WsSession::connect( &self.url ) ).await
      {
        Ok( Ok( session ) ) =>
        {
          {
            let mut current = self.current_session.write().await;
            *current = Some( session );
          }
          {
            let mut stats = self.stats.write().await;
            stats.successful_connections += 1;
            stats.last_connection_time = Some( Instant::now() );
          }
          {
            let mut reconnection_count = self.reconnection_count.lock().unwrap();
            *reconnection_count = 0;
          }
          return Ok( () );
        },
        Ok( Err( error ) ) =>
        {
          {
            let mut stats = self.stats.write().await;
            stats.failed_connections += 1;
          }

          attempts += 1;
          if attempts >= self.config.max_reconnection_attempts
          {
            return Err( error );
          }

          sleep( delay ).await;
          delay = std::cmp::min( delay * 2, self.config.max_reconnection_delay );
        },
        Err( _ ) =>
        {
          {
            let mut stats = self.stats.write().await;
            stats.failed_connections += 1;
          }

          attempts += 1;
          if attempts >= self.config.max_reconnection_attempts
          {
            return Err( error_tools::Error::from( OpenAIError::Internal(
              format!( "Failed to connect after {} attempts", attempts )
            ) ) );
          }

          sleep( delay ).await;
          delay = std::cmp::min( delay * 2, self.config.max_reconnection_delay );
        }
      }
    }
  }

  /// Send message with reliability guarantees
  pub async fn send_message_reliable( &self, message : &str ) -> Result< () >
  {
    // Add to buffer first
    {
      let mut buffer = self.message_buffer.lock().unwrap();
      if buffer.len() >= self.config.message_buffer_size
      {
        buffer.pop_front(); // Remove oldest message
      }
      buffer.push_back( message.to_string() );
    }

    // Attempt to send immediately
    let session_opt = self.current_session.read().await;
    if let Some( ref session ) = *session_opt
    {
      // Since send_event expects RealtimeClientEvent, we'll simulate with a test message
      // In a real implementation, this would be converted appropriately
      match self.simulate_message_send( session, message ).await
      {
        Ok( () ) =>
        {
          let mut stats = self.stats.write().await;
          stats.messages_sent += 1;
          return Ok( () );
        },
        Err( _error ) =>
        {
          let mut stats = self.stats.write().await;
          stats.message_send_failures += 1;
          // Will attempt reconnection and retry
        }
      }
    }

    // If sending failed, attempt reconnection
    self.handle_connection_failure().await?;

    // Retry sending after reconnection
    let session_opt = self.current_session.read().await;
    if let Some( ref session ) = *session_opt
    {
      self.simulate_message_send( session, message ).await?;
      let mut stats = self.stats.write().await;
      stats.messages_sent += 1;
    }

    Ok( () )
  }

  /// Simulate message sending for testing purposes
  async fn simulate_message_send( &self, _session : &WsSession, _message : &str ) -> Result< () >
  {
    // In real implementation, this would use session.send_event()
    // For testing, we'll simulate success/failure scenarios
    Ok( () )
  }

  /// Handle connection failure and attempt reconnection
  async fn handle_connection_failure( &self ) -> Result< () >
  {
    {
      let mut stats = self.stats.write().await;
      stats.connection_interruptions += 1;
    }

    {
      let mut current = self.current_session.write().await;
      *current = None; // Clear current session
    }

    {
      let mut reconnection_count = self.reconnection_count.lock().unwrap();
      *reconnection_count += 1;

      if *reconnection_count > self.config.max_reconnection_attempts
      {
        return Err( error_tools::Error::from( OpenAIError::Internal(
          "Maximum reconnection attempts exceeded".to_string()
        ) ) );
      }
    }

    {
      let mut stats = self.stats.write().await;
      stats.reconnections += 1;
    }

    self.connect_with_reliability().await
  }

  /// Start heartbeat monitoring
  pub async fn start_heartbeat_monitoring( &self )
  {
    let heartbeat_interval = self.config.heartbeat_interval;
    let last_heartbeat = Arc::clone( &self.last_heartbeat );
    let current_session = Arc::clone( &self.current_session );

    tokio ::spawn( async move
    {
      let mut interval = interval( heartbeat_interval );
      loop
      {
        interval.tick().await;

        {
          let mut last_hb = last_heartbeat.lock().unwrap();
          *last_hb = Some( Instant::now() );
        }

        // In real implementation, send ping/heartbeat message
        let session_opt = current_session.read().await;
        if session_opt.is_some()
        {
          // Simulate heartbeat check
          continue;
        }
        else
        {
          // Connection lost, should trigger reconnection
          break;
        }
      }
    });
  }

  /// Check connection health
  pub async fn check_connection_health( &self ) -> bool
  {
    let session_opt = self.current_session.read().await;
    if session_opt.is_none()
    {
      return false;
    }

    // Check heartbeat timing
    let last_hb = self.last_heartbeat.lock().unwrap();
    if let Some( last_time ) = *last_hb
    {
      let elapsed = last_time.elapsed();
      return elapsed < self.config.heartbeat_interval * 3; // Allow 3x heartbeat tolerance
    }

    true // No heartbeat data yet, assume healthy
  }

  /// Get connection statistics
  pub async fn get_stats( &self ) -> WsConnectionStats
  {
    self.stats.read().await.clone()
  }

  /// Get buffered message count
  pub fn get_buffered_message_count( &self ) -> usize
  {
    self.message_buffer.lock().unwrap().len()
  }

  /// Flush message buffer
  pub async fn flush_message_buffer( &self ) -> Result< () >
  {
    let messages : Vec< String > = {
      let mut buffer = self.message_buffer.lock().unwrap();
      buffer.drain( .. ).collect()
    };

    for message in messages
    {
      self.send_message_reliable( &message ).await?;
    }

    Ok( () )
  }
}

/// WebSocket reliability test utilities
#[ derive( Debug ) ]
pub struct WsReliabilityTestUtils;

impl WsReliabilityTestUtils
{
  /// Create a test configuration with short timeouts for testing
  pub fn create_test_config() -> WsReliabilityConfig
  {
    WsReliabilityConfig
    {
      max_reconnection_attempts : 3,
      initial_reconnection_delay : Duration::from_millis( 100 ),
      max_reconnection_delay : Duration::from_millis( 500 ),
      connection_timeout : Duration::from_millis( 1000 ),
      heartbeat_interval : Duration::from_millis( 500 ),
      message_buffer_size : 10,
      health_check_interval : Duration::from_millis( 200 ),
    }
  }

  /// Create a mock WebSocket URL for testing
  pub fn create_mock_ws_url() -> String
  {
    "wss://api.openai.com/v1/realtime/test".to_string()
  }

  /// Simulate network interruption
  pub async fn simulate_network_interruption( duration : Duration )
  {
    // In real testing, this would actually interrupt network connectivity
    sleep( duration ).await;
  }

  /// Measure connection establishment time
  pub async fn measure_connection_time< F, Fut >( connection_fn : F ) -> Duration
  where
    F : FnOnce() -> Fut,
    Fut : std::future::Future< Output = Result< () > >,
  {
    let start = Instant::now();
    let _ = connection_fn().await;
    start.elapsed()
  }
}

// Test cases following TDD principles

#[ tokio::test ]
async fn test_enhanced_ws_session_creation()
{
  let config = WsReliabilityTestUtils::create_test_config();
  let url = WsReliabilityTestUtils::create_mock_ws_url();

  let session = EnhancedWsSession::new( url.clone(), config.clone() );

  assert_eq!( session.url, url );
  assert_eq!( session.config.max_reconnection_attempts, 3 );
  assert_eq!( session.get_buffered_message_count(), 0 );

  let stats = session.get_stats().await;
  assert_eq!( stats.connection_attempts, 0 );
  assert_eq!( stats.successful_connections, 0 );
}

#[ tokio::test ]
async fn test_ws_reliability_config_defaults()
{
  let config = WsReliabilityConfig::default();

  assert_eq!( config.max_reconnection_attempts, 5 );
  assert_eq!( config.initial_reconnection_delay, Duration::from_millis( 1000 ) );
  assert_eq!( config.max_reconnection_delay, Duration::from_secs( 30 ) );
  assert_eq!( config.connection_timeout, Duration::from_secs( 10 ) );
  assert_eq!( config.heartbeat_interval, Duration::from_secs( 30 ) );
  assert_eq!( config.message_buffer_size, 1000 );
}

#[ tokio::test ]
async fn test_ws_connection_stats_initialization()
{
  let stats = WsConnectionStats::default();

  assert_eq!( stats.connection_attempts, 0 );
  assert_eq!( stats.successful_connections, 0 );
  assert_eq!( stats.failed_connections, 0 );
  assert_eq!( stats.reconnections, 0 );
  assert_eq!( stats.messages_sent, 0 );
  assert_eq!( stats.messages_received, 0 );
  assert_eq!( stats.message_send_failures, 0 );
  assert_eq!( stats.connection_interruptions, 0 );
  assert!(stats.last_connection_time.is_none());
}

#[ tokio::test ]
async fn test_message_buffering_functionality()
{
  let config = WsReliabilityTestUtils::create_test_config();
  let url = WsReliabilityTestUtils::create_mock_ws_url();
  let session = EnhancedWsSession::new( url, config );

  // Simulate adding messages to buffer
  {
    let mut buffer = session.message_buffer.lock().unwrap();
    buffer.push_back( "test_message_1".to_string() );
    buffer.push_back( "test_message_2".to_string() );
  }

  assert_eq!( session.get_buffered_message_count(), 2 );

  // Test buffer size limit by using the send_message_reliable function
  // which implements the buffer size limit logic
  for i in 0..20
  {
    // Add to buffer through normal logic which should enforce size limits
    let mut buffer = session.message_buffer.lock().unwrap();
    if buffer.len() >= session.config.message_buffer_size
    {
      buffer.pop_front(); // Remove oldest message
    }
    buffer.push_back( format!( "message_{}", i ) );
  }

  // Should be limited by config.message_buffer_size (10)
  assert!( session.get_buffered_message_count() <= 10 );
}

#[ tokio::test ]
async fn test_connection_health_monitoring()
{
  let config = WsReliabilityTestUtils::create_test_config();
  let url = WsReliabilityTestUtils::create_mock_ws_url();
  let session = EnhancedWsSession::new( url, config );

  // Initially no connection, should be unhealthy
  let health = session.check_connection_health().await;
  assert!( !health );

  // Simulate healthy heartbeat
  {
    let mut last_hb = session.last_heartbeat.lock().unwrap();
    *last_hb = Some( Instant::now() );
  }

  // With recent heartbeat but no connection, still unhealthy
  let health = session.check_connection_health().await;
  assert!( !health );
}

#[ tokio::test ]
async fn test_reliability_test_utils()
{
  let config = WsReliabilityTestUtils::create_test_config();
  assert_eq!( config.max_reconnection_attempts, 3 );
  assert_eq!( config.initial_reconnection_delay, Duration::from_millis( 100 ) );

  let url = WsReliabilityTestUtils::create_mock_ws_url();
  assert!( url.starts_with( "wss://" ) );
  assert!( url.contains( "openai.com" ) );

  // Test network interruption simulation
  let start = Instant::now();
  WsReliabilityTestUtils::simulate_network_interruption( Duration::from_millis( 50 ) ).await;
  let elapsed = start.elapsed();
  assert!( elapsed >= Duration::from_millis( 50 ) );
}

#[ tokio::test ]
async fn test_concurrent_reliability_sessions()
{
  let config = WsReliabilityTestUtils::create_test_config();
  let url = WsReliabilityTestUtils::create_mock_ws_url();

  let session1 = Arc::new( EnhancedWsSession::new( url.clone(), config.clone() ) );
  let session2 = Arc::new( EnhancedWsSession::new( url, config ) );

  let semaphore = Arc::new( Semaphore::new( 2 ) );
  let mut handles = Vec::new();

  for session in vec![ session1, session2 ]
  {
    let semaphore_clone = Arc::clone( &semaphore );
    let handle = tokio::spawn( async move
    {
      let _permit = semaphore_clone.acquire().await.unwrap();

      // Simulate concurrent operations
      let stats = session.get_stats().await;
      assert_eq!( stats.connection_attempts, 0 );

      let health = session.check_connection_health().await;
      assert!( !health ); // No connection established

      session.start_heartbeat_monitoring().await;

      // Give heartbeat monitor time to start
      sleep( Duration::from_millis( 100 ) ).await;
    });

    handles.push( handle );
  }

  // Wait for all concurrent operations to complete
  for handle in handles
  {
    handle.await.expect( "Task should complete successfully" );
  }
}

#[ tokio::test ]
async fn test_message_reliability_under_failure()
{
  let config = WsReliabilityTestUtils::create_test_config();
  let url = WsReliabilityTestUtils::create_mock_ws_url();
  let session = EnhancedWsSession::new( url, config );

  // Test message queuing when no connection exists
  {
    let mut buffer = session.message_buffer.lock().unwrap();
    buffer.push_back( "queued_message_1".to_string() );
    buffer.push_back( "queued_message_2".to_string() );
  }

  assert_eq!( session.get_buffered_message_count(), 2 );

  // Simulate message send failure stats tracking
  {
    let mut stats = session.stats.write().await;
    stats.message_send_failures += 1;
    stats.connection_interruptions += 1;
  }

  let final_stats = session.get_stats().await;
  assert_eq!( final_stats.message_send_failures, 1 );
  assert_eq!( final_stats.connection_interruptions, 1 );
}

#[ tokio::test ]
async fn test_exponential_backoff_timing()
{
  let config = WsReliabilityTestUtils::create_test_config();

  let mut delay = config.initial_reconnection_delay;
  assert_eq!( delay, Duration::from_millis( 100 ) );

  // Simulate exponential backoff progression
  delay = std::cmp::min( delay * 2, config.max_reconnection_delay );
  assert_eq!( delay, Duration::from_millis( 200 ) );

  delay = std::cmp::min( delay * 2, config.max_reconnection_delay );
  assert_eq!( delay, Duration::from_millis( 400 ) );

  delay = std::cmp::min( delay * 2, config.max_reconnection_delay );
  assert_eq!( delay, Duration::from_millis( 500 ) ); // Capped at max

  delay = std::cmp::min( delay * 2, config.max_reconnection_delay );
  assert_eq!( delay, Duration::from_millis( 500 ) ); // Still capped
}

#[ tokio::test ]
async fn test_connection_timeout_handling()
{
  let config = WsReliabilityTestUtils::create_test_config();
  assert_eq!( config.connection_timeout, Duration::from_millis( 1000 ) );

  // Test timeout simulation
  let start = Instant::now();
  let result = timeout( config.connection_timeout, async move
  {
    // Simulate slow connection
    sleep( Duration::from_millis( 1500 ) ).await;
    Ok::<(), OpenAIError >( () )
  }).await;

  let elapsed = start.elapsed();
  assert!( result.is_err() ); // Should timeout
  assert!( elapsed >= config.connection_timeout );
  assert!( elapsed < Duration::from_millis( 1200 ) ); // Should not wait much longer
}

#[ tokio::test ]
async fn test_heartbeat_interval_configuration()
{
  let config = WsReliabilityTestUtils::create_test_config();
  let url = WsReliabilityTestUtils::create_mock_ws_url();
  let session = EnhancedWsSession::new( url, config.clone() );

  assert_eq!( config.heartbeat_interval, Duration::from_millis( 500 ) );

  // Start heartbeat monitoring
  session.start_heartbeat_monitoring().await;

  // Wait for potential heartbeat
  sleep( Duration::from_millis( 600 ) ).await;

  // Check if heartbeat was recorded (in real implementation)
  let _last_hb = session.last_heartbeat.lock().unwrap();
  // Note : In this test, heartbeat might not be recorded since no real connection exists
  // This test primarily validates the heartbeat monitoring can be started without panic
}

#[ tokio::test ]
async fn test_statistics_accuracy_tracking()
{
  let config = WsReliabilityTestUtils::create_test_config();
  let url = WsReliabilityTestUtils::create_mock_ws_url();
  let session = EnhancedWsSession::new( url, config );

  // Simulate various connection events
  {
    let mut stats = session.stats.write().await;
    stats.connection_attempts = 5;
    stats.successful_connections = 3;
    stats.failed_connections = 2;
    stats.reconnections = 2;
    stats.messages_sent = 100;
    stats.messages_received = 95;
    stats.message_send_failures = 5;
    stats.connection_interruptions = 1;
    stats.last_connection_time = Some( Instant::now() );
  }

  let final_stats = session.get_stats().await;
  assert_eq!( final_stats.connection_attempts, 5 );
  assert_eq!( final_stats.successful_connections, 3 );
  assert_eq!( final_stats.failed_connections, 2 );
  assert_eq!( final_stats.reconnections, 2 );
  assert_eq!( final_stats.messages_sent, 100 );
  assert_eq!( final_stats.messages_received, 95 );
  assert_eq!( final_stats.message_send_failures, 5 );
  assert_eq!( final_stats.connection_interruptions, 1 );
  assert!( final_stats.last_connection_time.is_some() );
}