orch-cli 0.116.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Worker leases. The node that runs a task renews `lease_until` on it, and recovery on the leader
//! reads the lease in place of tmux for a run on another node

use std::time::Duration;

use chrono::{DateTime, Utc};

use crate::config;

/// How often the owner renews its leases
pub const DEFAULT_RENEW: Duration = Duration::from_secs(30);

/// How long a lease lasts after a renewal
pub const DEFAULT_TTL: Duration = Duration::from_secs(90);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Lease {
    pub renew: Duration,
    pub ttl: Duration,
}

impl Default for Lease {
    fn default() -> Self {
        Self {
            renew: DEFAULT_RENEW,
            ttl: DEFAULT_TTL,
        }
    }
}

impl Lease {
    /// `cluster.lease_renew_secs` and `cluster.lease_secs`. A lease shorter than two renewals
    /// would lapse on one late tick, so the ttl is raised to that
    pub fn load() -> Self {
        let secs = |key: &str, default: Duration| {
            config::get(key)
                .ok()
                .and_then(|v| v.parse::<u64>().ok())
                .filter(|s| *s > 0)
                .map_or(default, Duration::from_secs)
        };
        Self::new(
            secs("cluster.lease_renew_secs", DEFAULT_RENEW),
            secs("cluster.lease_secs", DEFAULT_TTL),
        )
    }

    pub fn new(renew: Duration, ttl: Duration) -> Self {
        Self {
            renew,
            ttl: ttl.max(renew * 2),
        }
    }

    pub fn ttl_secs(&self) -> i64 {
        i64::try_from(self.ttl.as_secs()).unwrap_or(i64::MAX)
    }

    /// The `lease_until` a renewal at `now` writes
    pub fn until(&self, now: DateTime<Utc>) -> String {
        let ttl = chrono::Duration::seconds(self.ttl_secs());
        now.checked_add_signed(ttl)
            .unwrap_or(now)
            .format("%Y-%m-%dT%H:%M:%SZ")
            .to_string()
    }
}

/// True while `lease_until` is in the future. A missing or unparsable lease has expired
pub fn valid(lease_until: Option<&str>, now: DateTime<Utc>) -> bool {
    lease_until
        .and_then(|l| DateTime::parse_from_rfc3339(l).ok())
        .is_some_and(|until| until > now)
}

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

    #[test]
    fn a_lease_in_the_future_is_valid_and_one_in_the_past_or_missing_is_not() {
        let now = Utc::now();
        let lease = Lease::default();
        assert!(valid(Some(&lease.until(now)), now));
        assert!(!valid(
            Some(&lease.until(now - chrono::Duration::hours(1))),
            now
        ));
        assert!(!valid(None, now));
        assert!(!valid(Some("not a time"), now));
    }

    #[test]
    fn the_ttl_covers_at_least_two_renewals() {
        let lease = Lease::new(Duration::from_secs(60), Duration::from_secs(30));
        assert_eq!(lease.ttl, Duration::from_secs(120));
    }
}