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> }
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,
}
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 };
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) }
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 {
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);
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 };
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)); }
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 })
}
pub fn active(&self) -> bool { 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() }
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())))
}
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);
}
}