Skip to main content

rocketmq_runtime/resource_budget/
clock.rs

1// Copyright 2023 The RocketMQ Rust Authors
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
15use std::time::Duration;
16use std::time::Instant;
17
18/// Monotonic time source used by rate and queue-age budgets.
19///
20/// Production code normally uses [`SystemMonotonicClock`]. Tests can inject a
21/// deterministic clock without sleeping or changing wall-clock time.
22pub trait MonotonicClock: Send + Sync + 'static {
23    /// Returns the now.
24    fn now(&self) -> Duration;
25}
26
27/// Represents system monotonic clock.
28#[derive(Debug)]
29pub struct SystemMonotonicClock {
30    origin: Instant,
31}
32
33impl SystemMonotonicClock {
34    #[must_use]
35    /// Creates a new `SystemMonotonicClock`.
36    pub fn new() -> Self {
37        Self { origin: Instant::now() }
38    }
39}
40
41impl Default for SystemMonotonicClock {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl MonotonicClock for SystemMonotonicClock {
48    fn now(&self) -> Duration {
49        self.origin.elapsed()
50    }
51}