use std::fs::{self, File, TryLockError};
use std::time::{Duration, Instant};
use rig_harness_protocol::{Home, RunDir, SessionDir, is_free, lock_file};
use super::Result;
use super::build::BuildOutput;
pub struct Run {
dir: RunDir,
_lock: File,
}
impl Run {
pub fn dir(&self) -> &RunDir {
&self.dir
}
}
impl Drop for Run {
fn drop(&mut self) {
if !self.dir.log().exists() {
fs::remove_dir_all(self.dir.path()).ok();
}
}
}
pub fn hold_run(home: &Home) -> Result<Run> {
let dir = home.run(std::process::id());
fs::create_dir_all(dir.path())?;
let lock = lock_file(&dir.lock(), true)?;
lock.try_lock()?;
Ok(Run { dir, _lock: lock })
}
pub fn sweep(home: &Home) -> Result<()> {
if let Ok(entries) = fs::read_dir(home.bin()) {
for entry in entries {
let entry = entry?;
let Some(session) = entry.file_name().to_str().and_then(Home::owner_of) else {
continue;
};
if is_free(&home.session(&session).launcher_lock()) {
fs::remove_file(entry.path())?;
}
}
}
if let Ok(entries) = fs::read_dir(home.runs()) {
for entry in entries {
let Some(launcher) = entry?.file_name().to_str().and_then(|id| id.parse().ok()) else {
continue;
};
let run = home.run(launcher);
if is_free(&run.lock()) && !run.log().exists() {
fs::remove_dir_all(run.path())?;
}
}
}
if let Ok(entries) = fs::read_dir(home.sessions()) {
for entry in entries {
let session = SessionDir::at(entry?.path());
let lock = session.launcher_lock();
if lock.exists() && is_free(&lock) && !session.is_saved() && !session.is_deleting() {
fs::remove_dir_all(session.path())?;
}
}
}
Ok(())
}
const QUIET_WAIT: Duration = Duration::from_secs(3);
const LOCK_POLL: Duration = Duration::from_millis(50);
pub fn hold_build_lock(home: &Home, output: BuildOutput) -> Result<File> {
fs::create_dir_all(home.bin())?;
let file = lock_file(&home.build_lock(), true)?;
let quiet = match output {
BuildOutput::Live => Duration::ZERO,
BuildOutput::LogOnly => QUIET_WAIT,
};
take(&file, quiet, || {
eprintln!(
"Waiting for another rig on {} to finish building…",
home.root().display()
);
})?;
Ok(file)
}
fn take(lock: &File, quiet: Duration, say: impl FnOnce()) -> Result<()> {
let deadline = Instant::now() + quiet;
loop {
match lock.try_lock() {
Ok(()) => return Ok(()),
Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
std::thread::sleep(LOCK_POLL);
}
Err(TryLockError::WouldBlock) => {
say();
lock.lock()?;
return Ok(());
}
Err(TryLockError::Error(failure)) => return Err(failure.into()),
}
}
}
#[cfg(test)]
mod tests;