fastmcp-rust 0.3.1

Fast, cancel-correct MCP framework for Rust
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
//! Timing utilities for test measurements.
//!
//! Provides stopwatch functionality for measuring operation durations
//! in tests and benchmarks.

use std::time::{Duration, Instant};

/// Measures the duration of a closure execution.
///
/// # Example
///
/// ```ignore
/// use fastmcp_rust::testing::prelude::*;
///
/// let (result, duration) = measure_duration(|| {
///     // Some operation
///     42
/// });
///
/// assert_eq!(result, 42);
/// println!("Operation took {:?}", duration);
/// ```
pub fn measure_duration<T, F: FnOnce() -> T>(f: F) -> (T, Duration) {
    let start = Instant::now();
    let result = f();
    let duration = start.elapsed();
    (result, duration)
}

/// A stopwatch for measuring elapsed time with lap support.
///
/// # Example
///
/// ```ignore
/// use fastmcp_rust::testing::prelude::*;
///
/// let mut stopwatch = Stopwatch::new();
///
/// // Do first operation
/// stopwatch.lap("operation_1");
///
/// // Do second operation
/// stopwatch.lap("operation_2");
///
/// println!("Total time: {:?}", stopwatch.elapsed());
/// for (name, duration) in stopwatch.laps() {
///     println!("{}: {:?}", name, duration);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Stopwatch {
    /// Start time.
    start: Instant,
    /// Last lap time.
    last_lap: Instant,
    /// Recorded laps with names.
    laps: Vec<(String, Duration)>,
}

impl Default for Stopwatch {
    fn default() -> Self {
        Self::new()
    }
}

impl Stopwatch {
    /// Creates a new stopwatch and starts it immediately.
    #[must_use]
    pub fn new() -> Self {
        let now = Instant::now();
        Self {
            start: now,
            last_lap: now,
            laps: Vec::new(),
        }
    }

    /// Creates a stopped stopwatch that starts when `start()` is called.
    #[must_use]
    pub fn stopped() -> Self {
        // Use a sentinel value; will be overwritten by start()
        let now = Instant::now();
        Self {
            start: now,
            last_lap: now,
            laps: Vec::new(),
        }
    }

    /// Restarts the stopwatch, clearing all laps.
    pub fn restart(&mut self) {
        let now = Instant::now();
        self.start = now;
        self.last_lap = now;
        self.laps.clear();
    }

    /// Records a lap with the given name.
    ///
    /// The duration is measured from the last lap (or start if no laps).
    pub fn lap(&mut self, name: impl Into<String>) {
        let now = Instant::now();
        let duration = now - self.last_lap;
        self.laps.push((name.into(), duration));
        self.last_lap = now;
    }

    /// Returns the total elapsed time since the stopwatch started.
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        self.start.elapsed()
    }

    /// Returns the time since the last lap (or start if no laps).
    #[must_use]
    pub fn since_last_lap(&self) -> Duration {
        self.last_lap.elapsed()
    }

    /// Returns all recorded laps.
    #[must_use]
    pub fn laps(&self) -> &[(String, Duration)] {
        &self.laps
    }

    /// Returns the number of recorded laps.
    #[must_use]
    pub fn lap_count(&self) -> usize {
        self.laps.len()
    }

    /// Returns the lap with the given name, if it exists.
    #[must_use]
    pub fn get_lap(&self, name: &str) -> Option<Duration> {
        self.laps.iter().find(|(n, _)| n == name).map(|(_, d)| *d)
    }

    /// Returns the sum of all lap durations.
    #[must_use]
    pub fn total_lap_time(&self) -> Duration {
        self.laps.iter().map(|(_, d)| *d).sum()
    }

    /// Returns timing statistics.
    #[must_use]
    pub fn stats(&self) -> TimingStats {
        if self.laps.is_empty() {
            return TimingStats {
                count: 0,
                total: Duration::ZERO,
                min: None,
                max: None,
                mean: None,
            };
        }

        let durations: Vec<_> = self.laps.iter().map(|(_, d)| *d).collect();
        let total: Duration = durations.iter().sum();
        let min = durations.iter().min().copied();
        let max = durations.iter().max().copied();
        let mean = Some(total / durations.len() as u32);

        TimingStats {
            count: durations.len(),
            total,
            min,
            max,
            mean,
        }
    }

    /// Formats the stopwatch results as a human-readable report.
    #[must_use]
    pub fn report(&self) -> String {
        let mut lines = Vec::new();
        lines.push(format!("Total elapsed: {:?}", self.elapsed()));
        lines.push(format!("Laps: {}", self.lap_count()));

        if !self.laps.is_empty() {
            lines.push(String::new());
            for (name, duration) in &self.laps {
                lines.push(format!("  {name}: {duration:?}"));
            }

            let stats = self.stats();
            lines.push(String::new());
            lines.push("Statistics:".to_string());
            if let Some(min) = stats.min {
                lines.push(format!("  Min: {min:?}"));
            }
            if let Some(max) = stats.max {
                lines.push(format!("  Max: {max:?}"));
            }
            if let Some(mean) = stats.mean {
                lines.push(format!("  Mean: {mean:?}"));
            }
        }

        lines.join("\n")
    }
}

/// Timing statistics for a set of measurements.
#[derive(Debug, Clone)]
pub struct TimingStats {
    /// Number of measurements.
    pub count: usize,
    /// Total duration.
    pub total: Duration,
    /// Minimum duration.
    pub min: Option<Duration>,
    /// Maximum duration.
    pub max: Option<Duration>,
    /// Mean duration.
    pub mean: Option<Duration>,
}

impl TimingStats {
    /// Returns whether there are any measurements.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }
}

/// A simple timer that fires after a duration.
///
/// Useful for timeout testing.
#[derive(Debug, Clone)]
pub struct Timer {
    /// Start time.
    start: Instant,
    /// Target duration.
    duration: Duration,
}

impl Timer {
    /// Creates a new timer with the given duration.
    #[must_use]
    pub fn new(duration: Duration) -> Self {
        Self {
            start: Instant::now(),
            duration,
        }
    }

    /// Creates a timer from seconds.
    #[must_use]
    pub fn from_secs(secs: u64) -> Self {
        Self::new(Duration::from_secs(secs))
    }

    /// Creates a timer from milliseconds.
    #[must_use]
    pub fn from_millis(ms: u64) -> Self {
        Self::new(Duration::from_millis(ms))
    }

    /// Returns whether the timer has expired.
    #[must_use]
    pub fn is_expired(&self) -> bool {
        self.start.elapsed() >= self.duration
    }

    /// Returns the remaining time, or zero if expired.
    #[must_use]
    pub fn remaining(&self) -> Duration {
        let elapsed = self.start.elapsed();
        if elapsed >= self.duration {
            Duration::ZERO
        } else {
            self.duration - elapsed
        }
    }

    /// Resets the timer.
    pub fn reset(&mut self) {
        self.start = Instant::now();
    }
}

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

    #[test]
    fn test_measure_duration() {
        let (result, duration) = measure_duration(|| {
            sleep(Duration::from_millis(10));
            42
        });

        assert_eq!(result, 42);
        assert!(duration >= Duration::from_millis(10));
    }

    #[test]
    fn test_stopwatch_basic() {
        let mut sw = Stopwatch::new();
        sleep(Duration::from_millis(10));
        sw.lap("first");
        sleep(Duration::from_millis(10));
        sw.lap("second");

        assert_eq!(sw.lap_count(), 2);
        assert!(sw.elapsed() >= Duration::from_millis(20));
    }

    #[test]
    fn test_stopwatch_get_lap() {
        let mut sw = Stopwatch::new();
        sleep(Duration::from_millis(5));
        sw.lap("test_lap");

        let lap = sw.get_lap("test_lap");
        assert!(lap.is_some());
        assert!(lap.unwrap() >= Duration::from_millis(5));

        assert!(sw.get_lap("nonexistent").is_none());
    }

    #[test]
    fn test_stopwatch_stats() {
        let mut sw = Stopwatch::new();
        sw.lap("a");
        sw.lap("b");
        sw.lap("c");

        let stats = sw.stats();
        assert_eq!(stats.count, 3);
        assert!(stats.min.is_some());
        assert!(stats.max.is_some());
        assert!(stats.mean.is_some());
    }

    #[test]
    fn test_stopwatch_empty_stats() {
        let sw = Stopwatch::new();
        let stats = sw.stats();
        assert_eq!(stats.count, 0);
        assert!(stats.is_empty());
    }

    #[test]
    fn test_stopwatch_restart() {
        let mut sw = Stopwatch::new();
        sw.lap("first");
        sw.restart();

        assert_eq!(sw.lap_count(), 0);
    }

    #[test]
    fn test_timer_basic() {
        let timer = Timer::from_millis(50);
        assert!(!timer.is_expired());
        assert!(timer.remaining() > Duration::ZERO);

        sleep(Duration::from_millis(60));
        assert!(timer.is_expired());
        assert_eq!(timer.remaining(), Duration::ZERO);
    }

    #[test]
    fn test_timer_reset() {
        let mut timer = Timer::from_millis(100);
        sleep(Duration::from_millis(50));
        timer.reset();

        // After reset, remaining should be close to full duration
        assert!(timer.remaining() > Duration::from_millis(80));
    }

    #[test]
    fn test_stopwatch_report() {
        let mut sw = Stopwatch::new();
        sw.lap("setup");
        sw.lap("execute");
        sw.lap("teardown");

        let report = sw.report();
        assert!(report.contains("Total elapsed"));
        assert!(report.contains("Laps: 3"));
        assert!(report.contains("setup"));
        assert!(report.contains("execute"));
        assert!(report.contains("teardown"));
    }

    // =========================================================================
    // Additional coverage tests (bd-1fnm)
    // =========================================================================

    #[test]
    fn stopwatch_stopped_constructor() {
        let sw = Stopwatch::stopped();
        assert_eq!(sw.lap_count(), 0);
        assert!(sw.laps().is_empty());
    }

    #[test]
    fn stopwatch_default_matches_new() {
        let def = Stopwatch::default();
        let new = Stopwatch::new();
        assert_eq!(def.lap_count(), new.lap_count());
    }

    #[test]
    fn stopwatch_since_last_lap() {
        let sw = Stopwatch::new();
        let since = sw.since_last_lap();
        assert!(since < Duration::from_secs(1));
    }

    #[test]
    fn stopwatch_total_lap_time() {
        let mut sw = Stopwatch::new();
        sw.lap("a");
        sw.lap("b");
        let total = sw.total_lap_time();
        assert!(total > Duration::ZERO);
    }

    #[test]
    fn stopwatch_debug_and_clone() {
        let mut sw = Stopwatch::new();
        sw.lap("x");
        let debug = format!("{sw:?}");
        assert!(debug.contains("Stopwatch"));

        let cloned = sw.clone();
        assert_eq!(cloned.lap_count(), 1);
    }

    #[test]
    fn timing_stats_debug_clone_and_is_empty() {
        let mut sw = Stopwatch::new();
        sw.lap("a");
        let stats = sw.stats();
        let debug = format!("{stats:?}");
        assert!(debug.contains("TimingStats"));

        let cloned = stats.clone();
        assert_eq!(cloned.count, 1);
        assert!(!cloned.is_empty());
    }

    #[test]
    fn timer_from_secs() {
        let timer = Timer::from_secs(60);
        assert!(!timer.is_expired());
        assert!(timer.remaining() > Duration::from_secs(59));
    }

    #[test]
    fn timer_debug_and_clone() {
        let timer = Timer::from_millis(100);
        let debug = format!("{timer:?}");
        assert!(debug.contains("Timer"));

        let cloned = timer.clone();
        assert!(!cloned.is_expired());
    }

    #[test]
    fn report_empty_laps() {
        let sw = Stopwatch::new();
        let report = sw.report();
        assert!(report.contains("Laps: 0"));
        assert!(!report.contains("Statistics"));
    }
}