fundaia 0.10.0

Command line for the Fundaia deployment platform: projects, services, variables, deployments, logs and metrics
//! Instants and durations, as a person reads them.
//!
//! Parsed by hand rather than through a date crate: every value here arrives
//! from `Date.toISOString()`, so the shape is fixed, and what the tool needs is
//! a difference and a phrase — never a calendar, a locale or a time zone.

use std::time::{SystemTime, UNIX_EPOCH};

pub fn format_millis(millis: i64) -> String {
    if millis < 0 {
        return "".to_owned();
    }
    if millis < 1_000 {
        return format!("{millis}ms");
    }
    if millis < 60_000 {
        return format!("{:.1}s", millis as f64 / 1_000.0);
    }

    let minutes = millis / 60_000;
    let seconds = (millis % 60_000) / 1_000;
    format!("{minutes}m {seconds}s")
}

/// Difference between two ISO-8601 instants, in milliseconds.
///
/// Parsed by hand rather than through a date crate's format machinery: both
/// values come from `Date.toISOString()`, so the shape is fixed, and the only
/// thing needed is the difference — never the calendar.
pub fn millis_between(from: &str, to: &str) -> Option<i64> {
    Some(epoch_millis(to)? - epoch_millis(from)?)
}

/// `2026-07-30T10:04:31.512Z` as milliseconds since the epoch.
pub fn epoch_millis(iso: &str) -> Option<i64> {
    let (date, rest) = iso.split_once('T')?;
    let mut date_parts = date.split('-');
    let year: i64 = date_parts.next()?.parse().ok()?;
    let month: i64 = date_parts.next()?.parse().ok()?;
    let day: i64 = date_parts.next()?.parse().ok()?;

    let time = rest.trim_end_matches('Z');
    let (clock, fraction) = match time.split_once('.') {
        Some((clock, fraction)) => (clock, fraction),
        None => (time, "0"),
    };

    let mut clock_parts = clock.split(':');
    let hour: i64 = clock_parts.next()?.parse().ok()?;
    let minute: i64 = clock_parts.next()?.parse().ok()?;
    let second: i64 = clock_parts.next()?.parse().ok()?;

    let millis: i64 = fraction
        .chars()
        .take(3)
        .collect::<String>()
        .parse()
        .unwrap_or(0);

    Some(
        days_from_civil(year, month, day) * 86_400_000
            + hour * 3_600_000
            + minute * 60_000
            + second * 1_000
            + millis,
    )
}

/// Howard Hinnant's `days_from_civil`, which is the standard answer.
///
/// Reproduced rather than pulled in: it is eight lines, it is exact for every
/// proleptic Gregorian date, and the alternative is a date crate whose whole
/// calendar comes along for a subtraction.
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let year = if month <= 2 { year - 1 } else { year };
    let era = if year >= 0 { year } else { year - 399 } / 400;
    let year_of_era = year - era * 400;
    let day_of_year = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;

    era * 146_097 + day_of_era - 719_468
}

/// `hace 3 días`, and never a timestamp nobody was going to read.
///
/// The same vocabulary the web uses for the same facts, so a member list read
/// in a terminal and one read in a browser do not disagree about how long
/// somebody has been away.
pub fn relative_time(iso: &str) -> Option<String> {
    let then = epoch_millis(iso)?;
    let minutes = (now_millis() - then) / 60_000;

    if minutes < 1 {
        return Some("ahora mismo".to_owned());
    }
    if minutes < 60 {
        return Some(format!("hace {minutes} min"));
    }
    if minutes < 60 * 24 {
        return Some(format!("hace {} h", minutes / 60));
    }

    let days = minutes / (60 * 24);
    Some(if days == 1 {
        "hace 1 día".to_owned()
    } else {
        format!("hace {days} días")
    })
}

fn now_millis() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|since| since.as_millis() as i64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_should_read_the_epoch_itself_as_zero() {
        assert_eq!(epoch_millis("1970-01-01T00:00:00.000Z"), Some(0));
    }

    #[test]
    fn it_should_read_one_second_after_the_epoch() {
        assert_eq!(epoch_millis("1970-01-01T00:00:01.000Z"), Some(1_000));
    }

    #[test]
    fn it_should_read_a_date_without_a_fractional_part() {
        assert_eq!(epoch_millis("1970-01-02T00:00:00Z"), Some(86_400_000));
    }

    #[test]
    fn it_should_measure_the_gap_between_two_instants() {
        let gap = millis_between("2026-07-30T10:00:00.000Z", "2026-07-30T10:00:12.500Z");
        assert_eq!(gap, Some(12_500));
    }

    #[test]
    fn it_should_refuse_something_that_is_not_an_instant() {
        assert_eq!(epoch_millis("yesterday"), None);
    }

    #[test]
    fn it_should_print_a_short_gap_in_milliseconds() {
        assert_eq!(format_millis(420), "420ms");
    }

    #[test]
    fn it_should_print_a_medium_gap_in_seconds() {
        assert_eq!(format_millis(12_500), "12.5s");
    }

    #[test]
    fn it_should_print_a_long_gap_in_minutes_and_seconds() {
        assert_eq!(format_millis(185_000), "3m 5s");
    }

    #[test]
    fn it_should_refuse_to_describe_something_that_is_not_an_instant() {
        assert_eq!(relative_time("yesterday"), None);
    }

    #[test]
    fn it_should_describe_the_epoch_as_a_long_time_ago() {
        let described = relative_time("1970-01-01T00:00:00.000Z").unwrap_or_default();
        assert!(described.starts_with("hace "));
    }
}