use std::time::Duration;
use crate::backend::Job;
pub(crate) const TAKE: &str = "INSERT INTO vcon.lease (name, holder, taken_at, expires_at) \
VALUES ($1, $2, now(), now() + make_interval(secs => $3)) \
ON CONFLICT (name) DO UPDATE SET holder = EXCLUDED.holder, \
taken_at = CASE WHEN vcon.lease.holder = EXCLUDED.holder AND vcon.lease.expires_at \
> now() THEN vcon.lease.taken_at ELSE now() END, \
expires_at = EXCLUDED.expires_at \
WHERE vcon.lease.holder = EXCLUDED.holder OR vcon.lease.expires_at <= now() \
RETURNING holder";
pub(crate) const GIVE_UP: &str = "DELETE FROM vcon.lease WHERE name = $1 AND holder = $2";
pub(crate) const HOST_LEN: usize = 64;
#[must_use]
pub(crate) fn holder(random: [u8; 16], host: &str, pid: u32) -> String {
let hex: String = random.iter().map(|b| format!("{b:02x}")).collect();
format!("{hex}@{host}:{pid}")
}
#[must_use]
pub(crate) fn host_text(host: &[u8]) -> String {
if host.is_empty() {
return "unknown".to_owned();
}
host.iter()
.take(HOST_LEN)
.map(|&b| {
if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_') {
char::from(b)
} else {
'_'
}
})
.collect()
}
#[must_use]
pub(crate) fn new_holder() -> String {
let mut random = [0; 16];
aws_lc_rs::rand::fill(&mut random).expect("AWS-LC aborts instead of failing");
holder(random, &host_text(&host_name()), std::process::id())
}
fn host_name() -> Vec<u8> {
let mut buf = [0u8; 256];
let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) };
if rc != 0 {
return Vec::new();
}
let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
buf[..end].to_vec()
}
#[must_use]
pub(crate) fn seconds(ttl: Duration) -> f64 {
ttl.as_secs_f64()
}
#[must_use]
pub(crate) fn name(job: Job) -> &'static str {
match job {
Job::Sweep => "sweep",
Job::Pack => "pack",
}
}