ZIm/crates/clock/src/system_clock.rs
Conrad Irwin 6a2c712990
Use Instant not chrono for telemetry (#20756)
We occasionally see dates in the future appearing in our telemetry. One
hypothesis is that this is caused by a clock change while Zed is running
causing date math based on chrono to be incorrect.

Instant *should* be a more stable source of relative timestamps.

Release Notes:

- N/A
2024-11-19 08:23:12 -07:00

53 lines
1.2 KiB
Rust

use std::time::Instant;
pub trait SystemClock: Send + Sync {
/// Returns the current date and time in UTC.
fn utc_now(&self) -> Instant;
}
pub struct RealSystemClock;
impl SystemClock for RealSystemClock {
fn utc_now(&self) -> Instant {
Instant::now()
}
}
#[cfg(any(test, feature = "test-support"))]
pub struct FakeSystemClockState {
now: Instant,
}
#[cfg(any(test, feature = "test-support"))]
pub struct FakeSystemClock {
// Use an unfair lock to ensure tests are deterministic.
state: parking_lot::Mutex<FakeSystemClockState>,
}
#[cfg(any(test, feature = "test-support"))]
impl FakeSystemClock {
pub fn new() -> Self {
let state = FakeSystemClockState {
now: Instant::now(),
};
Self {
state: parking_lot::Mutex::new(state),
}
}
pub fn set_now(&self, now: Instant) {
self.state.lock().now = now;
}
pub fn advance(&self, duration: std::time::Duration) {
self.state.lock().now += duration;
}
}
#[cfg(any(test, feature = "test-support"))]
impl SystemClock for FakeSystemClock {
fn utc_now(&self) -> Instant {
self.state.lock().now
}
}