Skip to main content

flux_limiter/
clock.rs

1// src/clock.rs
2
3// clock module definition and implementations
4
5// dependencies
6use std::fmt;
7use std::time::{SystemTime, UNIX_EPOCH};
8
9/// Clock trait to abstract time retrieval.
10/// Implementors must be thread-safe (Send + Sync).
11/// The `now` method returns the current time in nanoseconds as a u64.
12/// This trait allows for different clock implementations, such as system time or a test clock.
13/// The Clock trait is used by the RateLimiter to get the current time.
14pub trait Clock: Send + Sync {
15    fn now(&self) -> Result<u64, ClockError>;
16}
17
18/// Clock error type
19#[derive(Debug)]
20pub enum ClockError {
21    SystemTimeError,
22}
23
24impl fmt::Display for ClockError {
25    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26        match self {
27            ClockError::SystemTimeError => write!(f, "System time error"),
28        }
29    }
30}
31
32impl std::error::Error for ClockError {}
33
34/// SystemClock implementation using the system time.
35/// Returns the current time in nanoseconds since the Unix epoch.
36/// Panics if the system clock is before the Unix epoch.
37/// This is the default clock used in the RateLimiter.
38/// Implements the Clock trait.
39/// Thread-safe and can be shared across threads.
40#[derive(Debug, Clone)]
41pub struct SystemClock;
42
43impl Clock for SystemClock {
44    fn now(&self) -> Result<u64, ClockError> {
45        SystemTime::now()
46            .duration_since(UNIX_EPOCH)
47            .map(|d| d.as_nanos() as u64)
48            .map_err(|_| ClockError::SystemTimeError)
49    }
50}