artifactize-tools 0.27.0

Portable scoped tools and safe file access for artifactize.
Documentation
//! The standalone command's process tree: start a program with an explicit environment,
//! capture its output, and kill it with its children when it ends, times out or is
//! cancelled.

use std::{collections::BTreeMap, ffi::OsString, process::Stdio};

use tokio::io::{AsyncRead, AsyncReadExt};
use tokio_util::sync::CancellationToken;

use crate::launch::{Finished, Launch, LaunchError, ProcessOutcome};

/// Read one extra byte to detect output beyond the requested limit.
const OUTPUT_PROBE_BYTES: usize = 1;

/// Run one program to completion in its own process group or Job Object.
pub(crate) async fn run(
    launch: Launch,
    cancellation: &CancellationToken,
) -> Result<Finished, LaunchError> {
    if cancellation.is_cancelled() {
        return Err(LaunchError::Cancelled);
    }
    let limit = launch.output_limit;
    let capture_limit = limit.checked_add(OUTPUT_PROBE_BYTES).ok_or_else(|| {
        LaunchError::Failed("Output limit leaves no room for the truncation probe.".into())
    })? as u64;
    let mut command = tokio::process::Command::new(&launch.program);
    command
        .args(&launch.args)
        .current_dir(&launch.cwd)
        .env_clear()
        .envs(passed_environment())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    let mut tree =
        super::spawn_tree(&mut command).map_err(|error| LaunchError::Failed(error.to_string()))?;
    let (stdout, stderr) = tree.take_output();
    let execution = async {
        let finish = async {
            tree.exited().await.map_err(failed)?;
            // Descendants can inherit the output pipes. Stop them at leader exit, while
            // its group identity is still reserved, then let capture drain buffered bytes.
            tree.reap().await.map_err(cleanup_failed)
        };
        tokio::try_join!(
            async { capture(stdout, capture_limit).await.map_err(failed) },
            async { capture(stderr, capture_limit).await.map_err(failed) },
            finish,
        )
    };
    let result = tokio::select! {
        _ = cancellation.cancelled() => Err(LaunchError::Cancelled),
        result = tokio::time::timeout(launch.timeout, execution) => {
            result.unwrap_or(Err(LaunchError::TimedOut))
        }
    };
    if result.is_err() {
        tree.reap().await.map_err(cleanup_failed)?;
    }
    let (stdout, stderr, status) = result?;
    Ok(Finished {
        status: ProcessOutcome::from_native(status),
        truncated: stdout.len() > limit || stderr.len() > limit,
        stdout,
        stderr,
    })
}

fn failed(error: std::io::Error) -> LaunchError {
    LaunchError::Failed(error.to_string())
}

fn cleanup_failed(error: std::io::Error) -> LaunchError {
    LaunchError::Failed(format!(
        "Could not clean up the command's processes: {error}"
    ))
}

async fn capture(reader: impl AsyncRead + Unpin, limit: u64) -> std::io::Result<Vec<u8>> {
    let mut bytes = Vec::new();
    reader.take(limit).read_to_end(&mut bytes).await?;
    Ok(bytes)
}

pub(crate) fn handoff_cancelled() -> std::io::Error {
    std::io::Error::new(
        std::io::ErrorKind::Interrupted,
        "Desktop opener was interrupted.",
    )
}

pub(crate) fn handoff_timeout() -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::TimedOut, "Desktop opener timed out.")
}

/// Wait for the launcher, not its stdout; cancel and reap its tree before returning.
// Windows normally uses a native handoff rather than an owned launcher process.
#[cfg(any(unix, feature = "fixture-opener"))]
pub(crate) async fn handoff(
    command: &mut tokio::process::Command,
    deadline: std::time::Duration,
    cancellation: &CancellationToken,
) -> std::io::Result<std::process::ExitStatus> {
    if cancellation.is_cancelled() {
        return Err(handoff_cancelled());
    }
    command.kill_on_drop(true);
    let mut tree = super::spawn_tree(command)?;
    let result = tokio::select! {
        biased;
        _ = cancellation.cancelled() => Err(handoff_cancelled()),
        result = tokio::time::timeout(deadline, tree.exited()) => {
            result.unwrap_or_else(|_| Err(handoff_timeout()))
        }
    };
    let status = tree.reap().await?;
    result?;
    Ok(status)
}

/// The variables a standalone program receives: the person's whole environment, as in the
/// author's terminal, without artifactize's own `ARTIFACTIZE_*` variables (its credentials and
/// settings).
pub(crate) fn passed_environment() -> BTreeMap<OsString, OsString> {
    super::environment::user()
        .into_iter()
        .filter(|(name, _)| {
            !name
                .to_str()
                .is_some_and(|name| name.to_ascii_uppercase().starts_with("ARTIFACTIZE_"))
        })
        .collect()
}