1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
56//! Time source abstraction to support WASM and testing
7use std::fmt::Debug;
8use std::sync::Arc;
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
1011/// Trait with a `now()` function returning the current time
12pub trait TimeSource: Debug + Send + Sync {
13/// Returns the current time
14fn now(&self) -> SystemTime;
15}
1617/// Time source that delegates to [`SystemTime::now`]
18#[non_exhaustive]
19#[derive(Debug, Default)]
20pub struct SystemTimeSource;
2122impl SystemTimeSource {
23/// Creates a new SystemTimeSource
24pub fn new() -> Self {
25 SystemTimeSource
26 }
27}
2829impl TimeSource for SystemTimeSource {
30fn now(&self) -> SystemTime {
31// this is the one OK usage
32#[allow(clippy::disallowed_methods)]
33SystemTime::now()
34 }
35}
3637impl Default for SharedTimeSource {
38fn default() -> Self {
39 SharedTimeSource(Arc::new(SystemTimeSource))
40 }
41}
4243/// Time source that always returns the same time
44#[derive(Debug)]
45pub struct StaticTimeSource {
46 time: SystemTime,
47}
4849impl StaticTimeSource {
50/// Creates a new static time source that always returns the same time
51pub fn new(time: SystemTime) -> Self {
52Self { time }
53 }
5455/// Creates a new static time source from the provided number of seconds since the UNIX epoch
56pub fn from_secs(epoch_secs: u64) -> Self {
57Self::new(UNIX_EPOCH + Duration::from_secs(epoch_secs))
58 }
59}
6061impl TimeSource for StaticTimeSource {
62fn now(&self) -> SystemTime {
63self.time
64 }
65}
6667impl From<StaticTimeSource> for SharedTimeSource {
68fn from(value: StaticTimeSource) -> Self {
69 SharedTimeSource::new(value)
70 }
71}
7273#[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>);
7879impl SharedTimeSource {
80/// Returns the current time
81pub fn now(&self) -> SystemTime {
82self.0.now()
83 }
8485/// Creates a new shared time source
86pub fn new(source: impl TimeSource + 'static) -> Self {
87Self(Arc::new(source))
88 }
89}
9091impl TimeSource for SharedTimeSource {
92fn now(&self) -> SystemTime {
93self.0.now()
94 }
95}