pmcp 2.4.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
//! Advanced reconnection logic with exponential backoff.
//!
//! This module provides sophisticated reconnection strategies for network transports,
//! including exponential backoff, jitter, and circuit breaker patterns.

use crate::error::{Error, ErrorCode, Result};
#[cfg(target_arch = "wasm32")]
use futures::lock::{Mutex, RwLock};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
#[cfg(not(target_arch = "wasm32"))]
use tokio::sync::{Mutex, RwLock};
#[cfg(not(target_arch = "wasm32"))]
use tokio::time::sleep;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::wasm_bindgen::JsValue;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::JsFuture;
#[cfg(target_arch = "wasm32")]
use web_sys::window;

use tracing::{debug, info, warn};

/// Reconnection configuration.
#[derive(Debug, Clone)]
pub struct ReconnectConfig {
    /// Initial delay before first reconnection attempt.
    pub initial_delay: Duration,

    /// Maximum delay between reconnection attempts.
    pub max_delay: Duration,

    /// Factor by which delay grows after each failure.
    pub growth_factor: f64,

    /// Maximum number of reconnection attempts (None for unlimited).
    pub max_retries: Option<u32>,

    /// Jitter factor (0.0 to 1.0) to randomize delays.
    pub jitter_factor: f64,

    /// Whether to reset delay after successful connection.
    pub reset_on_success: bool,

    /// Minimum time a connection must be alive to be considered successful.
    pub success_threshold: Duration,

    /// Circuit breaker threshold (failures before circuit opens).
    pub circuit_breaker_threshold: Option<u32>,

    /// Circuit breaker reset timeout.
    pub circuit_breaker_timeout: Duration,
}

impl Default for ReconnectConfig {
    fn default() -> Self {
        Self {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            growth_factor: 2.0,
            max_retries: None,
            jitter_factor: 0.1,
            reset_on_success: true,
            success_threshold: Duration::from_secs(60),
            circuit_breaker_threshold: Some(5),
            circuit_breaker_timeout: Duration::from_secs(60),
        }
    }
}

/// Connection state for reconnection logic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionState {
    /// Not connected and not attempting to connect.
    Disconnected,

    /// Currently attempting to connect.
    Connecting,

    /// Successfully connected.
    Connected,

    /// Connection failed, waiting before retry.
    WaitingRetry,

    /// Circuit breaker is open, not attempting connections.
    CircuitOpen,
}

/// Reconnection manager for handling connection lifecycle.
pub struct ReconnectManager {
    /// Configuration.
    config: ReconnectConfig,

    /// Current state.
    state: Arc<RwLock<ConnectionState>>,

    /// Current retry count.
    retry_count: AtomicU32,

    /// Consecutive failure count.
    failure_count: AtomicU32,

    /// Total connection attempts.
    total_attempts: AtomicU64,

    /// Total successful connections.
    total_successes: AtomicU64,

    /// Last connection attempt time.
    last_attempt: Arc<Mutex<Option<Instant>>>,

    /// Last successful connection time.
    last_success: Arc<Mutex<Option<Instant>>>,

    /// Circuit breaker opened time.
    circuit_opened_at: Arc<Mutex<Option<Instant>>>,

    /// Whether reconnection is enabled.
    enabled: AtomicBool,

    /// Callbacks.
    callbacks: Arc<ReconnectCallbacks>,
}

impl std::fmt::Debug for ReconnectManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReconnectManager")
            .field("config", &self.config)
            .field("state", &"Arc<RwLock<ConnectionState>>")
            .field("retry_count", &self.retry_count.load(Ordering::Relaxed))
            .field("failure_count", &self.failure_count.load(Ordering::Relaxed))
            .field(
                "total_attempts",
                &self.total_attempts.load(Ordering::Relaxed),
            )
            .field(
                "total_successes",
                &self.total_successes.load(Ordering::Relaxed),
            )
            .field("enabled", &self.enabled.load(Ordering::Relaxed))
            .finish()
    }
}

/// Callback types for reconnection events.
/// Callback invoked when attempting to connect with retry count
pub type ConnectingCallback = Box<dyn Fn(u32) + Send + Sync>;
/// Callback invoked on connection state changes
pub type ConnectionCallback = Box<dyn Fn() + Send + Sync>;
/// Callback invoked on connection failures with error details
pub type FailureCallback = Box<dyn Fn(&Error) + Send + Sync>;

/// Callbacks for reconnection events.
#[derive(Default)]
pub struct ReconnectCallbacks {
    /// Called before connection attempt.
    pub on_connecting: Option<ConnectingCallback>,

    /// Called on successful connection.
    pub on_connected: Option<ConnectionCallback>,

    /// Called on connection failure.
    pub on_failed: Option<FailureCallback>,

    /// Called when circuit breaker opens.
    pub on_circuit_open: Option<ConnectionCallback>,

    /// Called when circuit breaker closes.
    pub on_circuit_close: Option<ConnectionCallback>,
}

impl std::fmt::Debug for ReconnectCallbacks {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReconnectCallbacks")
            .field("on_connecting", &self.on_connecting.is_some())
            .field("on_connected", &self.on_connected.is_some())
            .field("on_failed", &self.on_failed.is_some())
            .field("on_circuit_open", &self.on_circuit_open.is_some())
            .field("on_circuit_close", &self.on_circuit_close.is_some())
            .finish()
    }
}

impl ReconnectManager {
    /// Create a new reconnection manager.
    pub fn new(config: ReconnectConfig) -> Self {
        Self {
            config,
            state: Arc::new(RwLock::new(ConnectionState::Disconnected)),
            retry_count: AtomicU32::new(0),
            failure_count: AtomicU32::new(0),
            total_attempts: AtomicU64::new(0),
            total_successes: AtomicU64::new(0),
            last_attempt: Arc::new(Mutex::new(None)),
            last_success: Arc::new(Mutex::new(None)),
            circuit_opened_at: Arc::new(Mutex::new(None)),
            enabled: AtomicBool::new(true),
            callbacks: Arc::new(ReconnectCallbacks::default()),
        }
    }

    /// Set callbacks for reconnection events.
    pub fn set_callbacks(&mut self, callbacks: ReconnectCallbacks) {
        self.callbacks = Arc::new(callbacks);
    }

    /// Enable or disable reconnection.
    pub fn set_enabled(&self, enabled: bool) {
        self.enabled.store(enabled, Ordering::Relaxed);
    }

    /// Get current connection state.
    pub async fn state(&self) -> ConnectionState {
        *self.state.read().await
    }

    /// Check if reconnection should be attempted.
    pub async fn should_reconnect(&self) -> bool {
        if !self.enabled.load(Ordering::Relaxed) {
            return false;
        }

        let state = *self.state.read().await;
        match state {
            ConnectionState::Connected | ConnectionState::Connecting => false,
            ConnectionState::CircuitOpen => {
                // Check if circuit should be closed
                let opened_at_opt = *self.circuit_opened_at.lock().await;
                if let Some(opened_at) = opened_at_opt {
                    if opened_at.elapsed() >= self.config.circuit_breaker_timeout {
                        info!("Circuit breaker timeout reached, closing circuit");
                        *self.circuit_opened_at.lock().await = None;
                        *self.state.write().await = ConnectionState::Disconnected;

                        if let Some(callback) = &self.callbacks.on_circuit_close {
                            callback();
                        }

                        true
                    } else {
                        false
                    }
                } else {
                    false
                }
            },
            _ => {
                // Check retry limit
                if let Some(max_retries) = self.config.max_retries {
                    self.retry_count.load(Ordering::Relaxed) < max_retries
                } else {
                    true
                }
            },
        }
    }

    /// Calculate next retry delay with exponential backoff and jitter.
    pub fn calculate_delay(&self) -> Duration {
        let retry_count = self.retry_count.load(Ordering::Relaxed);

        // Calculate base delay with exponential backoff
        let base_delay = self.config.initial_delay.as_secs_f64()
            * self
                .config
                .growth_factor
                .powi(i32::try_from(retry_count).unwrap_or(i32::MAX));

        // Cap at maximum delay
        let capped_delay = base_delay.min(self.config.max_delay.as_secs_f64());

        // Add jitter
        let jitter_range = capped_delay * self.config.jitter_factor;
        // Simple jitter calculation without external dependency
        let jitter = {
            use std::time::{SystemTime, UNIX_EPOCH};
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .subsec_nanos();
            let random_factor = nanos as f64 / 1_000_000_000.0; // 0.0 to 1.0
            (random_factor * jitter_range).mul_add(2.0, -jitter_range)
        };
        let final_delay = (capped_delay + jitter).max(0.0);

        Duration::from_secs_f64(final_delay)
    }

    /// Notify that a connection attempt is starting.
    pub async fn on_connecting(&self) {
        *self.state.write().await = ConnectionState::Connecting;
        *self.last_attempt.lock().await = Some(Instant::now());
        self.total_attempts.fetch_add(1, Ordering::Relaxed);

        let retry_count = self.retry_count.load(Ordering::Relaxed);
        debug!("Connection attempt {} starting", retry_count + 1);

        if let Some(callback) = &self.callbacks.on_connecting {
            callback(retry_count);
        }
    }

    /// Notify that a connection was successful.
    pub async fn on_connected(&self) {
        *self.state.write().await = ConnectionState::Connected;
        *self.last_success.lock().await = Some(Instant::now());

        self.total_successes.fetch_add(1, Ordering::Relaxed);
        self.failure_count.store(0, Ordering::Relaxed);

        if self.config.reset_on_success {
            self.retry_count.store(0, Ordering::Relaxed);
        }

        info!("Connection established successfully");

        if let Some(callback) = &self.callbacks.on_connected {
            callback();
        }
    }

    /// Notify that a connection attempt failed.
    pub async fn on_connection_failed(&self, error: &Error) {
        *self.state.write().await = ConnectionState::WaitingRetry;

        self.retry_count.fetch_add(1, Ordering::Relaxed);
        let failure_count = self.failure_count.fetch_add(1, Ordering::Relaxed) + 1;

        warn!("Connection attempt failed: {}", error);

        // Check circuit breaker
        if let Some(threshold) = self.config.circuit_breaker_threshold {
            if failure_count >= threshold {
                *self.state.write().await = ConnectionState::CircuitOpen;
                *self.circuit_opened_at.lock().await = Some(Instant::now());

                warn!("Circuit breaker opened after {} failures", failure_count);

                if let Some(callback) = &self.callbacks.on_circuit_open {
                    callback();
                }
            }
        }

        if let Some(callback) = &self.callbacks.on_failed {
            callback(error);
        }
    }

    /// Notify that the connection was lost.
    pub async fn on_disconnected(&self) {
        let state = *self.state.read().await;
        if state == ConnectionState::Connected {
            // Check if connection was successful long enough
            let last_success_opt = *self.last_success.lock().await;
            if let Some(last_success) = last_success_opt {
                if last_success.elapsed() >= self.config.success_threshold {
                    // Reset retry count for long-lived connections
                    self.retry_count.store(0, Ordering::Relaxed);
                    debug!("Long-lived connection ended, resetting retry count");
                }
            }
        }

        *self.state.write().await = ConnectionState::Disconnected;
        info!("Connection lost");
    }

    /// Execute reconnection with the provided connect function.
    pub async fn reconnect_with<F, Fut>(&self, connect: F) -> Result<()>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<()>>,
    {
        loop {
            if !self.should_reconnect().await {
                return Err(Error::protocol(
                    ErrorCode::INTERNAL_ERROR,
                    "Reconnection disabled or limit reached",
                ));
            }

            self.on_connecting().await;

            match connect().await {
                Ok(()) => {
                    self.on_connected().await;
                    return Ok(());
                },
                Err(e) => {
                    self.on_connection_failed(&e).await;

                    if !self.should_reconnect().await {
                        return Err(e);
                    }

                    let delay = self.calculate_delay();
                    info!("Retrying connection in {:?}", delay);
                    sleep(delay).await;
                },
            }
        }
    }

    /// Get reconnection statistics.
    pub fn stats(&self) -> ReconnectStats {
        ReconnectStats {
            total_attempts: self.total_attempts.load(Ordering::Relaxed),
            total_successes: self.total_successes.load(Ordering::Relaxed),
            current_retry_count: self.retry_count.load(Ordering::Relaxed),
            consecutive_failures: self.failure_count.load(Ordering::Relaxed),
        }
    }

    /// Reset all counters.
    pub fn reset(&self) {
        self.retry_count.store(0, Ordering::Relaxed);
        self.failure_count.store(0, Ordering::Relaxed);
    }
}

/// Reconnection statistics.
#[derive(Debug, Clone)]
pub struct ReconnectStats {
    /// Total connection attempts.
    pub total_attempts: u64,

    /// Total successful connections.
    pub total_successes: u64,

    /// Current retry count.
    pub current_retry_count: u32,

    /// Consecutive failure count.
    pub consecutive_failures: u32,
}

/// Reconnection guard that automatically notifies disconnection on drop.
pub struct ReconnectGuard {
    manager: Arc<ReconnectManager>,
}

impl std::fmt::Debug for ReconnectGuard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReconnectGuard")
            .field("manager", &"Arc<ReconnectManager>")
            .finish()
    }
}

impl ReconnectGuard {
    /// Create a new reconnection guard.
    pub fn new(manager: Arc<ReconnectManager>) -> Self {
        Self { manager }
    }
}

impl Drop for ReconnectGuard {
    fn drop(&mut self) {
        let manager = self.manager.clone();
        tokio::spawn(async move {
            manager.on_disconnected().await;
        });
    }
}

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

    #[tokio::test]
    async fn test_exponential_backoff() {
        let config = ReconnectConfig {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(1),
            growth_factor: 2.0,
            jitter_factor: 0.0, // No jitter for predictable testing
            ..Default::default()
        };

        let manager = ReconnectManager::new(config);

        // First delay should be initial delay
        assert_eq!(manager.calculate_delay(), Duration::from_millis(100));

        // Simulate failures
        manager.retry_count.store(1, Ordering::Relaxed);
        assert_eq!(manager.calculate_delay(), Duration::from_millis(200));

        manager.retry_count.store(2, Ordering::Relaxed);
        assert_eq!(manager.calculate_delay(), Duration::from_millis(400));

        // Should cap at max delay
        manager.retry_count.store(10, Ordering::Relaxed);
        assert_eq!(manager.calculate_delay(), Duration::from_secs(1));
    }

    #[tokio::test]
    async fn test_circuit_breaker() {
        let config = ReconnectConfig {
            circuit_breaker_threshold: Some(3),
            circuit_breaker_timeout: Duration::from_millis(100),
            ..Default::default()
        };

        let manager = ReconnectManager::new(config);

        // Simulate failures
        for _ in 0..3 {
            manager.on_connection_failed(&Error::internal("test")).await;
        }

        // Circuit should be open
        assert_eq!(manager.state().await, ConnectionState::CircuitOpen);
        assert!(!manager.should_reconnect().await);

        // Wait for circuit timeout
        sleep(Duration::from_millis(150)).await;

        // Circuit should close
        assert!(manager.should_reconnect().await);
    }

    #[tokio::test]
    async fn test_retry_limit() {
        let config = ReconnectConfig {
            max_retries: Some(3),
            ..Default::default()
        };

        let manager = ReconnectManager::new(config);

        // Should allow retries up to limit
        for i in 0..3 {
            assert!(manager.should_reconnect().await);
            manager.retry_count.store(i, Ordering::Relaxed);
        }

        // Should not allow beyond limit
        manager.retry_count.store(3, Ordering::Relaxed);
        assert!(!manager.should_reconnect().await);
    }

    #[tokio::test]
    async fn test_success_reset() {
        let config = ReconnectConfig {
            reset_on_success: true,
            ..Default::default()
        };

        let manager = ReconnectManager::new(config);

        // Simulate some failures
        manager.retry_count.store(5, Ordering::Relaxed);
        manager.failure_count.store(3, Ordering::Relaxed);

        // Successful connection should reset counters
        manager.on_connected().await;

        assert_eq!(manager.retry_count.load(Ordering::Relaxed), 0);
        assert_eq!(manager.failure_count.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn test_reconnect_with() {
        let manager = Arc::new(ReconnectManager::new(ReconnectConfig {
            initial_delay: Duration::from_millis(10),
            max_retries: Some(3),
            ..Default::default()
        }));

        let attempt_count = Arc::new(AtomicU32::new(0));
        let attempt_count_clone = attempt_count.clone();

        // Simulate connection that fails twice then succeeds
        let result = manager
            .reconnect_with(|| {
                let count = attempt_count_clone.fetch_add(1, Ordering::Relaxed);
                async move {
                    if count < 2 {
                        Err(Error::internal("Connection failed"))
                    } else {
                        Ok(())
                    }
                }
            })
            .await;

        assert!(result.is_ok());
        assert_eq!(attempt_count.load(Ordering::Relaxed), 3);
        assert_eq!(manager.state().await, ConnectionState::Connected);
    }
}