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