metrique-timesource 0.1.1

Utilities for mocking Instant and SystemTime (part of metrique)
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

#![deny(missing_docs)]
#![doc = include_str!("../README.md")]

use std::{
    cell::RefCell,
    fmt::Debug,
    ops::Add,
    time::{Duration, Instant as StdInstant, SystemTime as StdSystemTime, SystemTimeError},
};

/// Module containing fake time sources for testing
///
/// To enable this module, you must enable the `test-util` feature.
#[cfg(feature = "test-util")]
pub mod fakes;

/// Trait for providing custom time sources
///
/// Implementors of this trait can be used to provide custom time behavior
/// for testing or specialized use cases.
pub trait Time: Send + Sync + Debug {
    /// Get the current system time
    fn now(&self) -> StdSystemTime;

    /// Get the current instant
    fn instant(&self) -> StdInstant;
}

/// Tokio-specific time source implementations
///
/// This module provides integration with tokio's time utilities, including
/// support for tokio's time pause/advance functionality for testing.
///
/// This requires that the `tokio` feature be enabled.
#[cfg(feature = "tokio")]
pub mod tokio {
    use std::time::SystemTime;

    use tokio::time::Instant as TokioInstant;

    use crate::{Time, TimeSource};
    use std::time::Instant as StdInstant;

    impl TimeSource {
        /// Create a new TimeSource that uses tokio's time utilities
        ///
        /// This allows integration with tokio's time pause/advance functionality
        /// for testing time-dependent code.
        ///
        /// This requires that the `tokio` feature be enabled.
        ///
        /// # Arguments
        ///
        /// * `starting_timestamp` - The initial system time to use
        ///
        /// # Returns
        ///
        /// A new TimeSource that uses tokio's time utilities
        ///
        /// # Examples
        ///
        /// ```
        /// # #[tokio::main(flavor = "current_thread")]
        /// # async fn main() {
        /// use std::time::{Duration, UNIX_EPOCH};
        /// use metrique_timesource::TimeSource;
        ///
        /// tokio::time::pause();
        /// let ts = TimeSource::tokio(UNIX_EPOCH);
        /// let start = ts.instant();
        ///
        /// tokio::time::advance(Duration::from_secs(5)).await;
        /// assert_eq!(start.elapsed(), Duration::from_secs(5));
        /// # }
        /// ```
        pub fn tokio(starting_timestamp: SystemTime) -> Self {
            TimeSource::custom(TokioTime::initialize_at(starting_timestamp))
        }
    }

    /// A time source implementation that uses tokio's time utilities
    ///
    /// This time source integrates with tokio's time pause/advance functionality,
    /// making it useful for testing time-dependent code.
    ///
    /// This requires that the `tokio` feature be enabled.
    #[derive(Copy, Clone, Debug)]
    pub struct TokioTime {
        start_time: TokioInstant,
        start_system_time: SystemTime,
    }

    impl TokioTime {
        /// Initialize a new TokioTime with the current system time
        ///
        /// # Returns
        ///
        /// A new TokioTime instance initialized with the current system time
        ///
        /// # Examples
        ///
        /// ```
        /// use metrique_timesource::tokio::TokioTime;
        /// use metrique_timesource::TimeSource;
        ///
        /// let time = TokioTime::initialize();
        /// let ts = TimeSource::custom(time);
        /// ```
        pub fn initialize() -> Self {
            Self::initialize_at(SystemTime::now())
        }

        /// Initialize a new TokioTime with a specific system time
        ///
        /// # Arguments
        ///
        /// * `initial_time` - The initial system time to use
        ///
        /// # Returns
        ///
        /// A new TokioTime instance initialized with the specified system time
        ///
        /// # Examples
        ///
        /// ```
        /// # #[tokio::main(flavor = "current_thread")]
        /// # async fn main() {
        /// use std::time::{Duration, UNIX_EPOCH};
        /// use metrique_timesource::tokio::TokioTime;
        /// use metrique_timesource::TimeSource;
        ///
        /// tokio::time::pause();
        /// let time = TokioTime::initialize_at(UNIX_EPOCH);
        /// let ts = TimeSource::custom(time);
        ///
        /// assert_eq!(ts.system_time(), UNIX_EPOCH);
        /// # }
        /// ```
        pub fn initialize_at(initial_time: SystemTime) -> Self {
            Self {
                start_time: TokioInstant::now(),
                start_system_time: initial_time,
            }
        }
    }

    impl Time for TokioTime {
        fn now(&self) -> SystemTime {
            self.start_system_time + self.start_time.elapsed()
        }

        fn instant(&self) -> StdInstant {
            TokioInstant::now().into_std()
        }
    }

    #[cfg(test)]
    mod test {
        use std::time::{Duration, UNIX_EPOCH};

        use crate::{SystemTime, TimeSource, get_time_source, set_time_source, tokio::TokioTime};

        #[tokio::test]
        async fn tokio_time_source() {
            tokio::time::pause();
            let ts = TimeSource::custom(TokioTime::initialize_at(UNIX_EPOCH));
            let start = ts.instant();
            assert_eq!(ts.system_time(), UNIX_EPOCH);
            tokio::time::advance(Duration::from_secs(1)).await;
            assert_eq!(ts.system_time(), UNIX_EPOCH + Duration::from_secs(1));
            assert_eq!(start.elapsed(), Duration::from_secs(1))
        }

        #[tokio::test]
        async fn with_tokio_ts() {
            struct MyMetric {
                start: SystemTime,
                end: Option<SystemTime>,
            }
            impl MyMetric {
                fn init() -> Self {
                    MyMetric {
                        start: get_time_source(None).system_time(),
                        end: None,
                    }
                }

                fn finish(&mut self) {
                    self.end = Some(get_time_source(None).system_time());
                }
            }

            tokio::time::pause();
            let start_time = UNIX_EPOCH + Duration::from_secs(1234);
            let _guard = set_time_source(TimeSource::custom(TokioTime::initialize_at(start_time)));
            let mut metric = MyMetric::init();
            assert_eq!(metric.start, start_time);
            tokio::time::advance(Duration::from_secs(5)).await;
            metric.finish();

            assert_eq!(
                metric.end.unwrap().duration_since(metric.start).unwrap(),
                Duration::from_secs(5)
            );
        }
    }
}

/// Enum representing different time source options
///
/// TimeSource provides a unified interface for accessing time, whether from the system
/// clock or from a custom time source for testing.
#[derive(Clone)]
pub enum TimeSource {
    /// Use the system time
    System,
    #[cfg(feature = "custom-timesource")]
    /// Use a custom time source
    Custom(std::sync::Arc<dyn Time + Send + Sync>),
}

impl std::fmt::Debug for TimeSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::System => write!(f, "TimeSource::System"),
            #[cfg(feature = "custom-timesource")]
            Self::Custom(_) => write!(f, "TimeSource::Custom(...)"),
        }
    }
}

impl TimeSource {
    /// Get the current [`SystemTime`] from this time source
    ///
    /// # Returns
    ///
    /// A wrapped SystemTime that maintains a reference to this time source
    ///
    /// # Examples
    ///
    /// ```
    /// use metrique_timesource::TimeSource;
    ///
    /// let ts = TimeSource::System;
    /// let now = ts.system_time();
    /// ```
    pub fn system_time(&self) -> SystemTime {
        match self {
            Self::System => SystemTime::new(StdSystemTime::now(), self),
            #[cfg(feature = "custom-timesource")]
            Self::Custom(ts) => SystemTime::new(ts.now(), self),
        }
    }

    /// Get the current instant from this time source
    ///
    /// # Returns
    ///
    /// A wrapped Instant that maintains a reference to this time source
    ///
    /// # Examples
    ///
    /// ```
    /// use metrique_timesource::TimeSource;
    /// use std::time::Duration;
    ///
    /// let ts = TimeSource::System;
    /// let start = ts.instant();
    /// // Do some work
    /// let elapsed = start.elapsed();
    /// ```
    pub fn instant(&self) -> Instant {
        match self {
            Self::System => Instant::new(StdInstant::now(), self),
            #[cfg(feature = "custom-timesource")]
            Self::Custom(ts) => Instant::new(ts.instant(), self),
        }
    }

    /// Create a new TimeSource with a custom time implementation
    ///
    /// This method is only available when the `custom-timesource` feature is enabled.
    ///
    /// # Arguments
    ///
    /// * `custom` - An implementation of the `Time` trait
    ///
    /// # Returns
    ///
    /// A new TimeSource that uses the provided custom time implementation
    ///
    /// # Examples
    ///
    /// ```
    /// use metrique_timesource::{TimeSource, fakes::StaticTimeSource};
    /// use std::time::{SystemTime, UNIX_EPOCH};
    ///
    /// let static_time = StaticTimeSource::at_time(UNIX_EPOCH);
    /// let ts = TimeSource::custom(static_time);
    /// assert_eq!(ts.system_time(), UNIX_EPOCH);
    /// ```
    #[cfg(feature = "custom-timesource")]
    pub fn custom(custom: impl Time + 'static) -> TimeSource {
        Self::Custom(std::sync::Arc::new(custom))
    }
}

impl Default for TimeSource {
    fn default() -> Self {
        Self::System
    }
}

// Thread-local time source override
thread_local! {
    static THREAD_LOCAL_TIME_SOURCE: RefCell<Option<TimeSource>> = const { RefCell::new(None) };
}

/// Guard for thread-local time source override
#[must_use]
pub struct ThreadLocalTimeSourceGuard {
    previous: Option<TimeSource>,
}

impl Drop for ThreadLocalTimeSourceGuard {
    fn drop(&mut self) {
        THREAD_LOCAL_TIME_SOURCE.with(|cell| {
            *cell.borrow_mut() = self.previous.take();
        });
    }
}

#[cfg(feature = "custom-timesource")]
/// Set a thread-local time source override and return a guard
/// When the guard is dropped, the thread-local override will be cleared
///
/// # Examples
/// ```
/// use metrique_timesource::{TimeSource, fakes::StaticTimeSource, time_source, set_time_source};
/// use std::time::UNIX_EPOCH;
///
/// let ts = TimeSource::custom(StaticTimeSource::at_time(UNIX_EPOCH));
/// let _guard = set_time_source(ts);
///
/// assert_eq!(time_source().system_time(), UNIX_EPOCH);
/// ```
pub fn set_time_source(time_source: TimeSource) -> ThreadLocalTimeSourceGuard {
    let previous = THREAD_LOCAL_TIME_SOURCE.with(|cell| cell.borrow_mut().replace(time_source));
    ThreadLocalTimeSourceGuard { previous }
}

#[cfg(feature = "custom-timesource")]
/// Run a closure with a thread-local time source override
pub fn with_time_source<F, R>(time_source: TimeSource, f: F) -> R
where
    F: FnOnce() -> R,
{
    let _guard = set_time_source(time_source);
    f()
}

/// Get the current time source, following the priority order:
/// 1. Explicitly provided time source
/// 2. Thread-local override
/// 3. System default
#[inline]
pub fn get_time_source(ts: Option<TimeSource>) -> TimeSource {
    // 1. Explicitly provided time source
    if let Some(ts) = ts {
        return ts;
    }

    #[cfg(feature = "custom-timesource")]
    {
        // 2. Thread-local override
        let thread_local = THREAD_LOCAL_TIME_SOURCE.with(|cell| cell.borrow().clone());
        if let Some(ts) = thread_local {
            return ts;
        }
    }

    // 3. System default
    TimeSource::System
}

/// Get the current time source
///
/// This is a convenience function that calls `get_time_source(None)`.
///
/// # Returns
///
/// The current time source, which will be either the thread-local override
/// if one is set, or the system default.
///
/// # Examples
///
/// ```
/// use metrique_timesource::time_source;
///
/// let ts = time_source();
/// let now = ts.system_time();
/// ```
#[inline]
pub fn time_source() -> TimeSource {
    get_time_source(None)
}

/// `Instant` wrapper
///
/// This may be freely converted into `std::time::Instant` with `.into()`. However,
/// this will cause `elapsed()` to no longer return correct results if a custom time source is used.
///
/// When `custom-timesource` is not enabled, this is exactly the same size as `Instant`. When `custom-timesource` _is_ enabled, it retains a pointer
/// to the timesource it came from to allow `elapsed()` to work properly.
#[derive(Clone)]
#[cfg_attr(not(feature = "custom-timesource"), derive(Copy), repr(transparent))]
pub struct Instant {
    value: StdInstant,
    #[cfg(feature = "custom-timesource")]
    time_source: TimeSource,
}

impl From<Instant> for StdInstant {
    fn from(instant: Instant) -> std::time::Instant {
        instant.as_std()
    }
}

impl std::fmt::Debug for Instant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(f)
    }
}

impl Instant {
    /// Create a new Instant from the given TimeSource
    ///
    /// # Arguments
    ///
    /// * `ts` - The TimeSource to use
    ///
    /// # Returns
    ///
    /// A new Instant representing the current time from the given TimeSource
    ///
    /// # Examples
    ///
    /// ```
    /// use metrique_timesource::{Instant, TimeSource};
    ///
    /// let ts = TimeSource::System;
    /// let now = Instant::now(&ts);
    /// ```
    pub fn now(ts: &TimeSource) -> Self {
        ts.instant()
    }

    /// Returns the amount of time elapsed since this instant was created
    ///
    /// # Returns
    ///
    /// The elapsed time as a Duration
    ///
    /// # Examples
    ///
    /// ```
    /// use metrique_timesource::{TimeSource, time_source};
    /// use std::thread;
    /// use std::time::Duration;
    ///
    /// let ts = time_source();
    /// let start = ts.instant();
    /// thread::sleep(Duration::from_millis(10));
    /// let elapsed = start.elapsed();
    /// assert!(elapsed.as_millis() >= 10);
    /// ```
    pub fn elapsed(&self) -> Duration {
        #[cfg(not(feature = "custom-timesource"))]
        let ts = TimeSource::System;
        #[cfg(feature = "custom-timesource")]
        let ts = &self.time_source;

        ts.instant().as_std() - self.value
    }

    /// Convert this Instant to a std::time::Instant
    ///
    /// # Returns
    ///
    /// A std::time::Instant representing the same point in time
    ///
    /// # Note
    ///
    /// After conversion, elapsed() will no longer respect custom time sources
    /// if they were being used.
    pub fn as_std(&self) -> StdInstant {
        self.value
    }

    fn new(std: StdInstant, ts: &TimeSource) -> Self {
        #[cfg(not(feature = "custom-timesource"))]
        let _ = ts;
        Self {
            value: std,
            #[cfg(feature = "custom-timesource")]
            time_source: ts.clone(),
        }
    }
}

/// `SystemTime` wrapper
///
/// This may be freely converted into `std::time::SystemTime` with `.into()`. However,
/// this will cause `elapsed()` to no longer return correct results if a custom time source is used.
///
/// When `custom-timesource` is not enabled, this is exactly the same size as `SystemTime`. When `custom-timesource` _is_ enabled, it retains a pointer
/// to the timesource it came from to allow `elapsed()` to work properly.
#[derive(Clone)]
#[cfg_attr(not(feature = "custom-timesource"), derive(Copy), repr(transparent))]
pub struct SystemTime {
    value: StdSystemTime,
    #[cfg(feature = "custom-timesource")]
    time_source: TimeSource,
}

impl PartialEq for SystemTime {
    fn eq(&self, other: &SystemTime) -> bool {
        self.value.eq(&other.value)
    }
}

impl Eq for SystemTime {}

impl PartialOrd for SystemTime {
    fn partial_cmp(&self, other: &SystemTime) -> Option<std::cmp::Ordering> {
        Some(self.value.cmp(&other.value))
    }
}

impl Ord for SystemTime {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.value.cmp(&other.value)
    }
}

impl PartialEq<StdSystemTime> for SystemTime {
    fn eq(&self, other: &StdSystemTime) -> bool {
        self.value.eq(other)
    }
}

impl PartialOrd<StdSystemTime> for SystemTime {
    fn partial_cmp(&self, other: &StdSystemTime) -> Option<std::cmp::Ordering> {
        Some(self.value.cmp(other))
    }
}

impl Add<Duration> for SystemTime {
    type Output = Self;

    fn add(mut self, rhs: Duration) -> Self::Output {
        self.value += rhs;
        self
    }
}

impl Debug for SystemTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(f)
    }
}

impl SystemTime {
    /// See [`std::time::SystemTime::duration_since`]
    pub fn duration_since(
        &self,
        earlier: impl Into<StdSystemTime>,
    ) -> Result<Duration, SystemTimeError> {
        self.value.duration_since(earlier.into())
    }

    /// See [`std::time::SystemTime::elapsed`]
    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
        let now = self.time_source().system_time();
        now.duration_since(self.value)
    }

    /// Convert this SystemTime to a std::time::SystemTime
    ///
    /// # Returns
    ///
    /// A std::time::SystemTime representing the same point in time
    ///
    /// # Note
    ///
    /// After conversion, elapsed() will no longer respect custom time sources
    /// if they were being used.
    pub fn as_std(&self) -> StdSystemTime {
        self.value
    }

    fn time_source(&self) -> &TimeSource {
        #[cfg(feature = "custom-timesource")]
        {
            &self.time_source
        }

        #[cfg(not(feature = "custom-timesource"))]
        &TimeSource::System
    }

    /// Creates this SystemTime from a std::time::SystemTime
    /// and a provided time source. This is useful for loading
    /// system times from an external source, that you want
    /// to interact with using this library's time sources.
    ///
    /// # Returns
    ///
    /// A SystemTime representing the same point in time,
    /// managed by the provided time source.
    ///
    /// # Example
    ///
    /// ```
    /// use metrique_timesource::{SystemTime, time_source};
    ///
    /// let now = std::time::SystemTime::now();
    /// let system_time = SystemTime::new(now, &time_source());
    /// ```
    pub fn new(std: StdSystemTime, ts: &TimeSource) -> Self {
        #[cfg(not(feature = "custom-timesource"))]
        let _ = ts;
        Self {
            value: std,
            #[cfg(feature = "custom-timesource")]
            time_source: ts.clone(),
        }
    }
}

impl From<SystemTime> for StdSystemTime {
    fn from(val: SystemTime) -> Self {
        val.value
    }
}

#[cfg(test)]
mod tests {

    use std::time::UNIX_EPOCH;

    use crate::{
        TimeSource, fakes, get_time_source, set_time_source, time_source, with_time_source,
    };

    #[test]
    fn test_default_time_source() {
        let ts = time_source();
        match ts {
            TimeSource::System => {} // Expected
            _ => panic!("Expected default time source to be System"),
        }
    }

    #[test]
    fn test_explicit_time_source() {
        let ts = fakes::StaticTimeSource::at_time(UNIX_EPOCH);
        let ts = TimeSource::custom(ts);
        let ts = get_time_source(Some(ts));
        match ts {
            TimeSource::Custom(_) => {} // Expected
            _ => panic!("Expected explicit time source to be used"),
        }
    }

    #[test]
    fn test_thread_local_time_source() {
        let ts = fakes::StaticTimeSource::at_time(UNIX_EPOCH);
        let ts = TimeSource::custom(ts);

        {
            let _guard = set_time_source(ts);
            let ts = get_time_source(None);
            assert_eq!(ts.system_time(), UNIX_EPOCH);
        }

        // After guard is dropped, should go back to default
        let ts = get_time_source(None);
        match ts {
            TimeSource::System => {} // Expected
            _ => panic!("Expected default time source after guard is dropped"),
        }
    }

    #[test]
    fn test_thread_local_time_source_scoped() {
        let ts = fakes::StaticTimeSource::at_time(UNIX_EPOCH);
        let thread_local = TimeSource::custom(ts);

        with_time_source(thread_local, || {
            let ts = get_time_source(None);
            match ts {
                TimeSource::Custom(_) => {} // Expected
                _ => panic!(),
            }
        });

        // After scope, should go back to default
        let ts = get_time_source(None);
        match ts {
            TimeSource::System => {} // Expected
            _ => panic!("Expected default time source after scope"),
        }
    }
}