#[cfg(unix)]
use tokio::process::Child;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use std::process::Stdio;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use tokio::process::Command;
pub struct SleepGuard {
#[cfg(unix)]
child: Option<Child>,
}
impl SleepGuard {
#[must_use]
pub fn hold() -> Self {
#[cfg(unix)]
{
Self {
child: start_inhibitor(),
}
}
#[cfg(not(unix))]
{
Self {}
}
}
#[cfg(all(test, unix))]
pub(crate) fn inhibitor_pid(&self) -> Option<u32> {
self.child.as_ref().and_then(Child::id)
}
}
#[cfg(unix)]
impl Drop for SleepGuard {
fn drop(&mut self) {
drop(self.child.take());
}
}
#[cfg(target_os = "macos")]
fn start_inhibitor() -> Option<Child> {
let pid = std::process::id().to_string();
spawn("caffeinate", &caffeinate_args(&pid))
}
#[cfg(target_os = "macos")]
fn caffeinate_args(watched_pid: &str) -> [&str; 3] {
["-i", "-w", watched_pid]
}
#[cfg(target_os = "linux")]
fn start_inhibitor() -> Option<Child> {
spawn(
"systemd-inhibit",
&[
"--what=idle",
"--why=Codewhale turn in flight",
"--mode=block",
"cat",
],
)
}
#[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))]
fn start_inhibitor() -> Option<Child> {
None
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn spawn(program: &str, args: &[&str]) -> Option<Child> {
Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.ok()
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
fn alive(pid: u32) -> bool {
unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}
async fn released(pid: u32) -> bool {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
while alive(pid) {
if tokio::time::Instant::now() >= deadline {
return false;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
true
}
#[tokio::test]
#[cfg(any(target_os = "macos", target_os = "linux"))]
async fn the_inhibitor_lives_exactly_as_long_as_the_guard() {
let guard = SleepGuard::hold();
let pid = guard
.inhibitor_pid()
.expect("this platform starts an inhibitor");
assert!(alive(pid), "the inhibitor must be running while held");
drop(guard);
assert!(
released(pid).await,
"a released guard must not leave an inhibitor keeping the host awake"
);
}
#[tokio::test]
#[cfg(target_os = "linux")]
async fn a_released_guard_leaves_no_grandchild_behind() {
let guard = SleepGuard::hold();
let pid = guard
.inhibitor_pid()
.expect("this platform starts an inhibitor");
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let grandchildren: Vec<u32> =
tokio::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children"))
.await
.unwrap_or_default()
.split_whitespace()
.filter_map(|child| child.parse().ok())
.collect();
drop(guard);
assert!(released(pid).await, "the inhibitor itself must be gone");
for grandchild in grandchildren {
assert!(
released(grandchild).await,
"process {grandchild} outlived the guard: the inhibitor's command must end with the guard's pipe"
);
}
}
#[tokio::test]
#[cfg(target_os = "macos")]
async fn the_inhibitor_exits_when_its_owner_dies_without_dropping_the_guard() {
let mut owner = Command::new("sleep")
.arg("60")
.kill_on_drop(true)
.spawn()
.expect("start a stand-in owner process");
let owner_pid = owner.id().expect("owner pid").to_string();
let mut inhibitor = spawn("caffeinate", &caffeinate_args(&owner_pid))
.expect("start caffeinate watching the stand-in owner");
let pid = inhibitor.id().expect("inhibitor pid");
assert!(
alive(pid),
"the inhibitor must be running while its owner lives"
);
owner.kill().await.expect("kill the stand-in owner");
let exited =
tokio::time::timeout(std::time::Duration::from_secs(5), inhibitor.wait()).await;
assert!(
exited.is_ok(),
"an inhibitor whose owner died must not keep the host awake"
);
}
#[tokio::test]
#[cfg(target_os = "macos")]
async fn a_held_guard_watches_the_process_that_holds_it() {
let guard = SleepGuard::hold();
let pid = guard
.inhibitor_pid()
.expect("this platform starts an inhibitor");
let ps = std::process::Command::new("ps")
.args(["-o", "args=", "-p", &pid.to_string()])
.output()
.expect("run ps");
let args = String::from_utf8_lossy(&ps.stdout);
assert_eq!(
args.trim(),
format!("caffeinate -i -w {}", std::process::id()),
"the inhibitor must end with the process whose turn it holds"
);
}
#[tokio::test]
#[cfg(any(target_os = "macos", target_os = "linux"))]
async fn holding_twice_holds_two_independent_inhibitors() {
let first = SleepGuard::hold();
let second = SleepGuard::hold();
let (a, b) = (
first.inhibitor_pid().expect("first inhibitor"),
second.inhibitor_pid().expect("second inhibitor"),
);
assert_ne!(a, b, "each guard owns its own inhibitor process");
drop(first);
assert!(released(a).await, "the first guard released only its own");
assert!(alive(b), "the second guard still holds the host awake");
}
}