use std::time::{Duration, SystemTime};
use uuid::Uuid;
use anyhow::{anyhow, Result};
const LEASE_TTL: Duration = Duration::from_secs(60);
const STALE_GRACE: Duration = Duration::from_secs(30);
#[derive(Debug, Clone)]
pub struct AuthorityLease {
pub owner: String,
pub lease_id: Uuid,
pub expires_at: SystemTime,
pub ttl: Duration,
}
impl AuthorityLease {
pub fn acquire(owner: &str) -> Self {
Self {
owner: owner.to_string(),
lease_id: Uuid::new_v4(),
expires_at: SystemTime::now() + LEASE_TTL,
ttl: LEASE_TTL,
}
}
pub fn renew(&mut self, owner: &str) -> Result<()> {
if self.owner != owner {
return Err(anyhow!(
"authority held by '{}', cannot renew as '{}'",
self.owner,
owner
));
}
self.expires_at = SystemTime::now() + self.ttl;
Ok(())
}
pub fn force_release(&mut self) {
self.expires_at = SystemTime::UNIX_EPOCH;
}
pub fn is_expired(&self) -> bool {
SystemTime::now() >= self.expires_at
}
pub fn is_stale(&self) -> bool {
SystemTime::now() >= self.expires_at + STALE_GRACE
}
}