1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, NaiveDateTime, SecondsFormat, Utc};
use rand::RngExt;
#[async_trait]
pub trait Time: Send + Sync {
fn now_unix(&self) -> f64;
fn now_utc(&self) -> DateTime<Utc>;
async fn sleep(&self, duration: Duration);
fn jitter(&self, scale: f64) -> f64;
}
pub struct RealTime;
#[async_trait]
impl Time for RealTime {
fn now_unix(&self) -> f64 {
Utc::now().timestamp_millis() as f64 / 1000.0
}
fn now_utc(&self) -> DateTime<Utc> {
Utc::now()
}
async fn sleep(&self, duration: Duration) {
tokio::time::sleep(duration).await;
}
fn jitter(&self, scale: f64) -> f64 {
if scale <= 0.0 {
return 0.0;
}
rand::rng().random_range(0.0..scale)
}
}
pub fn utc_iso(ts: f64) -> String {
let millis = (ts * 1000.0).round() as i64;
DateTime::from_timestamp_millis(millis)
.unwrap_or_else(|| DateTime::from_timestamp(0, 0).expect("epoch"))
.to_rfc3339_opts(SecondsFormat::Millis, true)
}
pub fn nvd_time(dt: DateTime<Utc>) -> String {
dt.format("%Y-%m-%dT%H:%M:%S%.3f").to_string()
}
pub fn parse_nvd_time(raw: &str) -> anyhow::Result<DateTime<Utc>> {
if let Ok(dt) = DateTime::parse_from_rfc3339(raw) {
return Ok(dt.with_timezone(&Utc));
}
let naive = NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S%.f")
.map_err(|err| anyhow::anyhow!("invalid NVD timestamp {raw:?}: {err}"))?;
Ok(naive.and_utc())
}
pub fn created_at(dt: DateTime<Utc>) -> String {
format!("{}Z", nvd_time(dt))
}
pub fn jitter(scale: f64) -> f64 {
RealTime.jitter(scale)
}