mito2/
time_provider.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Abstraction to get current time.
16
17use std::sync::Arc;
18use std::time::Duration;
19
20use common_time::util::current_time_millis;
21
22/// Trait to get current time and deal with durations.
23///
24/// We define the trait to simplify time related tests.
25pub trait TimeProvider: std::fmt::Debug + Send + Sync {
26    /// Returns current time in millis.
27    fn current_time_millis(&self) -> i64;
28
29    /// Returns millis elapsed since specify time.
30    fn elapsed_since(&self, current_millis: i64) -> i64;
31
32    /// Computes the actual duration to wait from an expected one.
33    fn wait_duration(&self, duration: Duration) -> Duration {
34        duration
35    }
36}
37
38pub type TimeProviderRef = Arc<dyn TimeProvider>;
39
40/// Default implementation of the time provider based on std.
41#[derive(Debug)]
42pub struct StdTimeProvider;
43
44impl TimeProvider for StdTimeProvider {
45    fn current_time_millis(&self) -> i64 {
46        current_time_millis()
47    }
48
49    fn elapsed_since(&self, current_millis: i64) -> i64 {
50        current_time_millis() - current_millis
51    }
52}