licers 1.2.1

Licers license-key verification: Ed25519-signed responses, floating seats, usage credits, remote variables, offline licenses.
Documentation
use crate::client::{HeartbeatState, LicenseClient};
use crate::error::{Error, Result};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

const GRACE: Duration = Duration::from_secs(30);
const MIN_INTERVAL: u64 = 15;

#[derive(Default)]
struct State { lease_id: Option<String>, lost_reason: Option<String> }

/// A held floating seat, heartbeated on a background thread. The seat can be
/// lost while your code runs — check [`FloatingSession::active`] or call
/// [`FloatingSession::ensure_active`] at safe points. Loss is decided from
/// signed evidence only; an unreachable server keeps the seat only until its
/// last signed expiry. Dropping the session releases the seat.
pub struct FloatingSession {
    client: Arc<LicenseClient>,
    state: Arc<Mutex<State>>,
    stop: Arc<(Mutex<bool>, Condvar)>,
    stopped: AtomicBool,
    worker: Option<JoinHandle<()>>,
    pub seats_used: i64,
    pub seats_max: i64,
    not_after: Option<Instant>,
}

/// Parses the server's toISOString() ("2026-11-17T10:00:00.000Z") to unix ms.
fn iso_to_unix_ms(s: &str) -> Option<i64> {
    let b = s.as_bytes();
    if b.len() < 19 || b[4] != b'-' || b[10] != b'T' { return None; }
    let n = |a: usize, l: usize| s.get(a..a + l)?.parse::<i64>().ok();
    let (y, mo, d, h, mi, se) = (n(0, 4)?, n(5, 2)?, n(8, 2)?, n(11, 2)?, n(14, 2)?, n(17, 2)?);
    let ms = if b.len() >= 23 && b[19] == b'.' { n(20, 3).unwrap_or(0) } else { 0 };
    // Days from civil (Howard Hinnant's algorithm).
    let y2 = if mo <= 2 { y - 1 } else { y };
    let era = y2.div_euclid(400);
    let yoe = y2 - era * 400;
    let doy = (153 * (if mo > 2 { mo - 3 } else { mo + 9 }) + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    let days = era * 146_097 + doe - 719_468;
    Some(((days * 86_400 + h * 3600 + mi * 60 + se) * 1000) + ms)
}

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

/// (deadline, interval) from a SIGNED expiry; the advisory interval is clamped.
fn plan(expires_at: Option<&str>, interval: u64, prev_deadline: Option<Instant>) -> (Instant, Duration) {
    let remaining = expires_at.and_then(iso_to_unix_ms).map(|e| e - now_ms());
    let deadline = match remaining {
        Some(r) if r > 0 => Instant::now() + Duration::from_millis(r as u64) + GRACE,
        Some(_) => Instant::now() + GRACE,
        None => prev_deadline.unwrap_or_else(|| Instant::now() + Duration::from_secs(interval.max(MIN_INTERVAL) * 4)),
    };
    let mut iv = Duration::from_secs(interval.max(MIN_INTERVAL));
    if let Some(r) = remaining.filter(|r| *r > 0) {
        iv = iv.min(Duration::from_millis(((r / 2) as u64).max(1000)));
    }
    (deadline, iv)
}

impl FloatingSession {
    /// Check out a seat and start heartbeating. `on_lost` runs on the
    /// heartbeat thread if the seat goes away.
    pub fn start(client: Arc<LicenseClient>, key: &str, on_lost: Option<Box<dyn Fn(&str) + Send>>) -> Result<Self> {
        let lease = client.lease(key)?;
        let state = Arc::new(Mutex::new(State { lease_id: Some(lease.lease_id.clone()), lost_reason: None }));
        let stop = Arc::new((Mutex::new(false), Condvar::new()));
        let (mut deadline, mut interval) = plan(Some(&lease.expires_at), lease.interval, None);
        // From a license server: nothing (not even the grace for a lost
        // connection) runs past the end of its signed server file.
        let not_after = lease.not_after.as_deref().and_then(iso_to_unix_ms).map(|e| {
            let left = e - now_ms();
            if left > 0 { Instant::now() + Duration::from_millis(left as u64) } else { Instant::now() }
        });
        let cap = move |deadline: &mut Instant, interval: &mut Duration| {
            if let Some(na) = not_after {
                if *deadline > na { *deadline = na; }
                let left = na.saturating_duration_since(Instant::now()).max(Duration::from_millis(100));
                if left < *interval { *interval = left; }
            }
        };
        cap(&mut deadline, &mut interval);
        let (c, st, sp) = (client.clone(), state.clone(), stop.clone());
        let worker = thread::spawn(move || loop {
            {
                let (lock, cv) = &*sp;
                let guard = lock.lock().unwrap();
                let (guard, _) = cv.wait_timeout_while(guard, interval, |stopped| !*stopped).unwrap();
                if *guard { return; }
            }
            let Some(id) = st.lock().unwrap().lease_id.clone() else { return };
            if not_after.map_or(false, |na| Instant::now() >= na) {
                let mut s = st.lock().unwrap();
                s.lease_id = None;
                s.lost_reason = Some("The license server's license has ended.".into());
                drop(s);
                if let Some(f) = &on_lost { f("The license server's license has ended."); }
                return;
            }
            let (state_now, exp) = c.heartbeat(&id);
            if *sp.0.lock().unwrap() { return; }
            let lose = |reason: &str| {
                let mut s = st.lock().unwrap();
                s.lease_id = None;
                s.lost_reason = Some(reason.to_string());
                drop(s);
                if let Some(f) = &on_lost { f(reason); }
            };
            match state_now {
                HeartbeatState::Lost => { lose("The license server ended this session."); return; }
                HeartbeatState::Held => { (deadline, interval) = plan(exp.as_deref(), interval.as_secs(), Some(deadline)); cap(&mut deadline, &mut interval); }
                HeartbeatState::Unconfirmed => {
                    if Instant::now() > deadline { lose("Lost contact with the license server and the seat has expired."); return; }
                }
            }
        });
        Ok(Self { client, state, stop, stopped: AtomicBool::new(false), worker: Some(worker), seats_used: lease.seats_used, seats_max: lease.seats_max, not_after })
    }

    /// True while the seat is held.
    pub fn active(&self) -> bool {
        self.not_after.map_or(true, |na| Instant::now() < na) && self.state.lock().map(|s| s.lease_id.is_some()).unwrap_or(false)
    }
    pub fn lease_id(&self) -> Option<String> { self.state.lock().ok()?.lease_id.clone() }
    pub fn lost_reason(&self) -> Option<String> { self.state.lock().ok()?.lost_reason.clone() }

    /// [`Error::SeatUnavailable`] if the seat was lost. No network call.
    pub fn ensure_active(&self) -> Result<()> {
        if self.active() { return Ok(()); }
        Err(Error::SeatUnavailable(self.lost_reason().unwrap_or_else(|| "This session no longer holds a seat.".into())))
    }

    /// Stop heartbeating and free the seat.
    pub fn stop(&mut self) {
        if self.stopped.swap(true, Ordering::SeqCst) { return; }
        { let (lock, cv) = &*self.stop; *lock.lock().unwrap() = true; cv.notify_all(); }
        if let Some(w) = self.worker.take() { let _ = w.join(); }
        let id = self.state.lock().ok().and_then(|mut s| s.lease_id.take());
        if let Some(id) = id { self.client.release(&id); }
    }
}

impl Drop for FloatingSession {
    fn drop(&mut self) { self.stop(); }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn iso_parse() {
        assert_eq!(iso_to_unix_ms("1970-01-01T00:00:00.000Z"), Some(0));
        assert_eq!(iso_to_unix_ms("2026-11-17T10:00:00.250Z"), Some(1_794_909_600_250));
        assert_eq!(iso_to_unix_ms("garbage"), None);
    }
}