~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
65 lines · 1.6 KB Raw History
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)
}