capy-cli 0.3.0

The command-line interface for the Capy web framework.
Documentation
//! OS-specific process ownership and termination signals stay out of the UI.
use std::{io, process::ExitStatus, time::Duration};
use tokio::process::{ChildStderr, ChildStdout, Command};

pub struct Child {
    inner: imp::Child,
}
impl Child {
    pub fn spawn(command: &mut Command) -> io::Result<Self> {
        imp::Child::spawn(command).map(|inner| Self { inner })
    }
    pub fn id(&self) -> Option<u32> {
        self.inner.id()
    }
    pub fn stdout(&mut self) -> Option<ChildStdout> {
        self.inner.child().stdout.take()
    }
    pub fn stderr(&mut self) -> Option<ChildStderr> {
        self.inner.child().stderr.take()
    }
    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
        self.inner.child().try_wait()
    }
    pub fn kill(&mut self) {
        self.inner.kill();
    }
    pub async fn stop(&mut self) {
        self.inner.terminate().await;
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        loop {
            let exited = self.try_wait().ok().flatten().is_some();
            if exited && !self.inner.alive() {
                break;
            }
            if tokio::time::Instant::now() >= deadline {
                break;
            }
            tokio::time::sleep(Duration::from_millis(30)).await;
        }
        // Always clean descendants, even if the group leader exited first.
        self.inner.kill();
        let _ = self.inner.child().wait().await;
    }
}
impl Drop for Child {
    fn drop(&mut self) {
        self.inner.kill();
    }
}

#[cfg(unix)]
mod imp {
    use super::*;
    use nix::{
        sys::signal::{killpg, Signal},
        unistd::Pid,
    };
    pub struct Child {
        child: tokio::process::Child,
        group: Pid,
        armed: bool,
    }
    impl Child {
        pub fn spawn(command: &mut Command) -> io::Result<Self> {
            let child = command.process_group(0).kill_on_drop(true).spawn()?;
            let group = Pid::from_raw(child.id().expect("new child has a PID") as i32);
            Ok(Self {
                child,
                group,
                armed: true,
            })
        }
        pub fn child(&mut self) -> &mut tokio::process::Child {
            &mut self.child
        }
        pub fn id(&self) -> Option<u32> {
            self.child.id()
        }
        pub async fn terminate(&mut self) {
            if self.armed {
                let _ = killpg(self.group, Signal::SIGTERM);
            }
        }
        pub fn alive(&self) -> bool {
            self.armed && killpg(self.group, None).is_ok()
        }
        pub fn kill(&mut self) {
            if self.armed {
                let _ = killpg(self.group, Signal::SIGKILL);
                self.armed = false;
            }
        }
    }
}

#[cfg(windows)]
mod imp {
    use super::*;
    use command_group::{AsyncCommandGroup, AsyncGroupChild};
    pub struct Child {
        group: AsyncGroupChild,
    }
    impl Child {
        pub fn spawn(command: &mut Command) -> io::Result<Self> {
            command
                .kill_on_drop(true)
                .group()
                .kill_on_drop(true)
                .spawn()
                .map(|group| Self { group })
        }
        pub fn child(&mut self) -> &mut tokio::process::Child {
            self.group.inner()
        }
        pub fn id(&self) -> Option<u32> {
            self.group.id()
        }
        pub async fn terminate(&mut self) {
            // Best-effort non-forced termination. The job object is the authority
            // for forced cleanup, including pnpm.cmd and all Node descendants.
            if let Some(pid) = self.id() {
                let _ = tokio::time::timeout(
                    Duration::from_secs(1),
                    Command::new("taskkill")
                        .args(["/PID", &pid.to_string(), "/T"])
                        .stdin(std::process::Stdio::null())
                        .stdout(std::process::Stdio::null())
                        .stderr(std::process::Stdio::null())
                        .kill_on_drop(true)
                        .status(),
                )
                .await;
            }
        }
        pub fn alive(&self) -> bool {
            self.group.id().is_some()
        }
        pub fn kill(&mut self) {
            let _ = self.group.start_kill();
        }
    }
}

pub struct Signals {
    #[cfg(unix)]
    interrupt: tokio::signal::unix::Signal,
    #[cfg(unix)]
    terminate: tokio::signal::unix::Signal,
    #[cfg(unix)]
    hangup: tokio::signal::unix::Signal,
    #[cfg(windows)]
    interrupt: tokio::signal::windows::CtrlC,
    #[cfg(windows)]
    close: tokio::signal::windows::CtrlClose,
    #[cfg(windows)]
    shutdown: tokio::signal::windows::CtrlShutdown,
    #[cfg(windows)]
    logoff: tokio::signal::windows::CtrlLogoff,
    #[cfg(windows)]
    ctrl_break: tokio::signal::windows::CtrlBreak,
}
impl Signals {
    pub fn new() -> io::Result<Self> {
        #[cfg(unix)]
        {
            use tokio::signal::unix::{signal, SignalKind};
            Ok(Self {
                interrupt: signal(SignalKind::interrupt())?,
                terminate: signal(SignalKind::terminate())?,
                hangup: signal(SignalKind::hangup())?,
            })
        }
        #[cfg(windows)]
        {
            use tokio::signal::windows::*;
            Ok(Self {
                interrupt: ctrl_c()?,
                close: ctrl_close()?,
                shutdown: ctrl_shutdown()?,
                logoff: ctrl_logoff()?,
                ctrl_break: ctrl_break()?,
            })
        }
    }
    pub async fn recv(&mut self) {
        #[cfg(unix)]
        tokio::select! { _ = self.interrupt.recv() => {}, _ = self.terminate.recv() => {}, _ = self.hangup.recv() => {} }
        #[cfg(windows)]
        tokio::select! { _ = self.interrupt.recv() => {}, _ = self.close.recv() => {}, _ = self.shutdown.recv() => {}, _ = self.logoff.recv() => {}, _ = self.ctrl_break.recv() => {} }
    }
}