aws_smithy_async/
time.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Time source abstraction to support WASM and testing
7use std::fmt::Debug;
8use std::sync::Arc;
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
11/// Trait with a `now()` function returning the current time
12pub trait TimeSource: Debug + Send + Sync {
13    /// Returns the current time
14    fn now(&self) -> SystemTime;
15}
16
17/// Time source that delegates to [`SystemTime::now`]
18#[non_exhaustive]
19#[derive(Debug, Default)]
20pub struct SystemTimeSource;
21
22impl SystemTimeSource {
23    /// Creates a new SystemTimeSource
24    pub fn new() -> Self {
25        SystemTimeSource
26    }
27}
28
29impl TimeSource for SystemTimeSource {
30    fn now(&self) -> SystemTime {
31        // this is the one OK usage
32        #[allow(clippy::disallowed_methods)]
33        SystemTime::now()
34    }
35}
36
37impl Default for SharedTimeSource {
38    fn default() -> Self {
39        SharedTimeSource(Arc::new(SystemTimeSource))
40    }
41}
42
43/// Time source that always returns the same time
44#[derive(Debug)]
45pub struct StaticTimeSource {
46    time: SystemTime,
47}
48
49impl StaticTimeSource {
50    /// Creates a new static time source that always returns the same time
51    pub fn new(time: SystemTime) -> Self {
52        Self { time }
53    }
54
55    /// Creates a new static time source from the provided number of seconds since the UNIX epoch
56    pub fn from_secs(epoch_secs: u64) -> Self {
57        Self::new(UNIX_EPOCH + Duration::from_secs(epoch_secs))
58    }
59}
60
61impl TimeSource for StaticTimeSource {
62    fn now(&self) -> SystemTime {
63        self.time
64    }
65}
66
67impl From<StaticTimeSource> for SharedTimeSource {
68    fn from(value: StaticTimeSource) -> Self {
69        SharedTimeSource::new(value)
70    }
71}
72
73#[derive(Debug, Clone)]
74/// Time source structure used inside SDK
75///
76/// This implements Default—the default implementation will use `SystemTime::now()`
77pub struct SharedTimeSource(Arc<dyn TimeSource>);
78
79impl SharedTimeSource {
80    /// Returns the current time
81    pub fn now(&self) -> SystemTime {
82        self.0.now()
83    }
84
85    /// Creates a new shared time source
86    pub fn new(source: impl TimeSource + 'static) -> Self {
87        Self(Arc::new(source))
88    }
89}
90
91impl TimeSource for SharedTimeSource {
92    fn now(&self) -> SystemTime {
93        self.0.now()
94    }
95}