capy-cli 0.1.0

Project scaffolding, generators, and development commands for the Capy web framework.
Documentation
//! Ownership of development subprocesses. The server is a direct, reapable child.
use anyhow::{bail, Context, Result};
use std::{
    path::Path,
    process::{Command, ExitCode, ExitStatus, Stdio},
};

pub(crate) fn serve(root: &Path) -> Result<ExitCode> {
    let mut owner = platform::Owner::new()?;
    let metadata = tempfile::tempfile()?;
    let status = owner.run(
        Command::new("cargo")
            .args(["metadata", "--no-deps", "--format-version=1"])
            .current_dir(root)
            .stdout(Stdio::from(metadata.try_clone()?)),
    )?;
    if !status.success() || owner.interrupted() {
        return Ok(exit_code(status));
    }
    let data: serde_json::Value = read_json(metadata)?;
    let manifest = root.join("Cargo.toml").canonicalize()?;
    let package = data["packages"]
        .as_array()
        .context("Cargo metadata has no packages")?
        .iter()
        .find(|p| {
            p["manifest_path"]
                .as_str()
                .is_some_and(|s| Path::new(s) == manifest)
        })
        .context("Cannot locate application package in Cargo metadata")?;
    let bins: Vec<_> = package["targets"]
        .as_array()
        .context("Cargo metadata has no targets")?
        .iter()
        .filter(|t| {
            t["kind"]
                .as_array()
                .is_some_and(|k| k.iter().any(|k| k == "bin"))
        })
        .filter_map(|t| t["name"].as_str())
        .collect();
    let bin = if let Some(default) = package["default_run"].as_str() {
        default
    } else if bins.len() == 1 {
        bins[0]
    } else {
        bail!("Application has multiple binaries. Set `package.default-run` in Cargo.toml for `capy serve`.");
    };
    let artifacts = tempfile::tempfile()?;
    let status = owner.run(
        Command::new("cargo")
            .args([
                "build",
                "--quiet",
                "--bin",
                bin,
                "--message-format=json-render-diagnostics",
            ])
            .current_dir(root)
            .stdout(Stdio::from(artifacts.try_clone()?)),
    )?;
    if !status.success() || owner.interrupted() {
        return Ok(exit_code(status));
    }
    use std::io::{BufRead, BufReader, Seek};
    let mut artifacts = artifacts;
    artifacts.rewind()?;
    let mut executable = None;
    for line in BufReader::new(artifacts).lines() {
        let item: serde_json::Value = serde_json::from_str(&line?)?;
        if item["reason"] == "compiler-artifact" && item["target"]["name"] == bin {
            if let Some(path) = item["executable"].as_str() {
                executable = Some(path.to_owned());
            }
        }
    }
    let executable = executable.context("Cargo did not produce an application binary")?;
    // No Cargo intermediary: Capy forwards to the group, then waits on this server.
    Ok(exit_code(owner.run(
        Command::new(executable).arg("serve").current_dir(root),
    )?))
}

fn read_json(mut file: std::fs::File) -> Result<serde_json::Value> {
    use std::io::Seek;
    file.rewind()?;
    Ok(serde_json::from_reader(file)?)
}

pub(crate) fn exit_code(status: ExitStatus) -> ExitCode {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        ExitCode::from(
            status
                .code()
                .unwrap_or_else(|| 128 + status.signal().unwrap_or(1)) as u8,
        )
    }
    #[cfg(not(unix))]
    ExitCode::from(u8::try_from(status.code().unwrap_or(1)).unwrap_or(1))
}

#[cfg(unix)]
mod platform {
    use anyhow::{Context, Result};
    use nix::{
        sys::signal::{killpg, Signal},
        unistd::Pid,
    };
    use signal_hook::{
        consts::{SIGINT, SIGTERM},
        iterator::Signals,
    };
    use std::{
        os::unix::process::CommandExt,
        process::{Command, ExitStatus},
        time::{Duration, Instant},
    };

    pub(super) struct Owner {
        signals: Signals,
        interrupted: bool,
    }
    impl Owner {
        pub fn new() -> Result<Self> {
            Ok(Self {
                signals: Signals::new([SIGINT, SIGTERM])?,
                interrupted: false,
            })
        }
        pub fn interrupted(&self) -> bool {
            self.interrupted
        }
        pub fn run(&mut self, command: &mut Command) -> Result<ExitStatus> {
            let mut child = command
                .process_group(0)
                .spawn()
                .context("Could not start development subprocess")?;
            let group = Pid::from_raw(i32::try_from(child.id())?);
            let mut shutdown = None;
            loop {
                for signal in self.signals.pending() {
                    self.interrupted = true;
                    let _ = killpg(group, Signal::try_from(signal)?);
                    shutdown.get_or_insert_with(Instant::now);
                }
                if shutdown.is_some_and(|start: Instant| start.elapsed() >= Duration::from_secs(5))
                {
                    let _ = killpg(group, Signal::SIGKILL);
                }
                if let Some(status) = child.try_wait()? {
                    // Remove any remaining processes in this owned group (e.g. build
                    // helpers). The application itself was a direct child and is reaped.
                    let _ = killpg(group, Signal::SIGKILL);
                    return Ok(status);
                }
                std::thread::sleep(Duration::from_millis(20));
            }
        }
    }
}

#[cfg(not(unix))]
mod platform {
    use anyhow::Result;
    use std::process::{Command, ExitStatus};
    pub(super) struct Owner;
    impl Owner {
        pub fn new() -> Result<Self> {
            Ok(Self)
        }
        pub fn interrupted(&self) -> bool {
            false
        }
        pub fn run(&mut self, command: &mut Command) -> Result<ExitStatus> {
            // Windows console Ctrl-C reaches both processes. Forced process-manager
            // termination is not supported without a Windows Job Object.
            Ok(command.status()?)
        }
    }
}