capy-cli 0.5.0

The command-line interface for the Capy web framework.
Documentation
//! Own every process group until it is stopped and its direct child is reaped.
use anyhow::{bail, Context, Result};
use std::{
    process::{Command, ExitStatus},
    time::{Duration, Instant},
};

pub(crate) struct Owner {
    signals: platform::Signals,
    children: Vec<Option<platform::Child>>,
    shutdown: Option<Instant>,
}

impl Owner {
    pub fn new() -> Result<Self> {
        Ok(Self {
            signals: platform::Signals::new()?,
            children: Vec::new(),
            shutdown: None,
        })
    }

    pub fn interrupted(&self) -> bool {
        self.shutdown.is_some()
    }

    pub fn spawn(&mut self, command: &mut Command) -> Result<usize> {
        self.poll_signals();
        if self.interrupted() {
            bail!("Command interrupted.");
        }
        let child = platform::Child::spawn(command).with_context(|| {
            format!(
                "Could not start {}",
                command.get_program().to_string_lossy()
            )
        })?;
        self.children.push(Some(child));
        Ok(self.children.len() - 1)
    }

    fn poll_signals(&mut self) {
        for signal in self.signals.pending() {
            self.shutdown.get_or_insert_with(Instant::now);
            for child in self.children.iter_mut().flatten() {
                child.signal(signal);
            }
        }
        if self
            .shutdown
            .is_some_and(|start| start.elapsed() >= Duration::from_secs(5))
        {
            for child in self.children.iter_mut().flatten() {
                child.kill();
            }
        }
    }

    fn try_wait(&mut self, index: usize) -> Result<Option<ExitStatus>> {
        let Some(child) = self.children[index].as_mut() else {
            return Ok(None);
        };
        if let Some(status) = child.try_wait()? {
            // The group may still contain pnpm's Vite child or Cargo's helpers.
            child.kill();
            self.children[index] = None;
            Ok(Some(status))
        } else {
            Ok(None)
        }
    }

    pub fn run(&mut self, command: &mut Command) -> Result<ExitStatus> {
        let index = self.spawn(command)?;
        loop {
            self.poll_signals();
            if let Some(status) = self.try_wait(index)? {
                return Ok(status);
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }
}

impl Drop for Owner {
    fn drop(&mut self) {
        // This also covers errors after starting only one child and panics.
        for child in self.children.iter_mut().flatten() {
            child.terminate();
        }
        let deadline = Instant::now() + Duration::from_secs(5);
        while self.children.iter().any(Option::is_some) && Instant::now() < deadline {
            for index in 0..self.children.len() {
                let _ = self.try_wait(index);
            }
            if self.children.iter().any(Option::is_some) {
                std::thread::sleep(Duration::from_millis(20));
            }
        }
        for child in self.children.iter_mut().flatten() {
            child.kill();
            let _ = child.wait();
        }
    }
}

#[cfg(unix)]
mod platform {
    use nix::{
        sys::signal::{killpg, Signal},
        unistd::Pid,
    };
    use signal_hook::{
        consts::{SIGHUP, SIGINT, SIGTERM},
        iterator,
    };
    use std::{
        io,
        os::unix::process::CommandExt,
        process::{Command, ExitStatus},
    };

    pub struct Signals(iterator::Signals);
    impl Signals {
        pub fn new() -> io::Result<Self> {
            iterator::Signals::new([SIGINT, SIGTERM, SIGHUP]).map(Self)
        }
        pub fn pending(&mut self) -> Vec<i32> {
            self.0.pending().collect()
        }
    }

    pub struct Child(std::process::Child);
    impl Child {
        pub fn spawn(command: &mut Command) -> io::Result<Self> {
            command.process_group(0).spawn().map(Self)
        }
        pub fn signal(&mut self, signal: i32) {
            if let Ok(signal) = Signal::try_from(signal) {
                let _ = killpg(Pid::from_raw(self.0.id() as i32), signal);
            }
        }
        pub fn terminate(&mut self) {
            self.signal(SIGTERM);
        }
        pub fn kill(&mut self) {
            self.signal(signal_hook::consts::SIGKILL);
        }
        pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
            self.0.try_wait()
        }
        pub fn wait(&mut self) -> io::Result<ExitStatus> {
            self.0.wait()
        }
    }
}

#[cfg(windows)]
mod platform {
    use command_group::{CommandGroup, GroupChild};
    use std::{
        io,
        process::{Command, ExitStatus},
        sync::{
            atomic::{AtomicBool, Ordering},
            Arc,
        },
    };

    pub struct Signals(Arc<AtomicBool>);
    impl Signals {
        pub fn new() -> anyhow::Result<Self> {
            let flag = Arc::new(AtomicBool::new(false));
            let handler = flag.clone();
            ctrlc::set_handler(move || {
                handler.store(true, Ordering::SeqCst);
            })?;
            Ok(Self(flag))
        }
        pub fn pending(&mut self) -> Vec<i32> {
            if self.0.swap(false, Ordering::SeqCst) {
                vec![2]
            } else {
                vec![]
            }
        }
    }

    // A job object owns descendants, including the pnpm shim and Node process.
    pub struct Child(GroupChild);
    impl Child {
        pub fn spawn(command: &mut Command) -> io::Result<Self> {
            command.group().kill_on_drop(true).spawn().map(Self)
        }
        pub fn signal(&mut self, _: i32) {
            self.kill();
        }
        pub fn terminate(&mut self) {
            self.kill();
        }
        pub fn kill(&mut self) {
            let _ = self.0.kill();
        }
        pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
            self.0.try_wait()
        }
        pub fn wait(&mut self) -> io::Result<ExitStatus> {
            self.0.wait()
        }
    }
}