artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
use std::{io, process::Stdio};

use super::*;

#[test]
#[ignore = "launched only by the admission fixture"]
fn write_marker() {
    let marker = std::fs::File::create_new("marker").unwrap();
    use std::io::Write;
    writeln!(&marker, "executed").unwrap();
}

#[tokio::test]
async fn parent_disconnect_before_admission_prevents_exec_and_reaps() {
    let root = tempfile::tempdir().unwrap();
    let marker = root.path().join("marker");
    let command = || {
        let mut command = resolved_command(
            &std::env::current_exe().unwrap(),
            [
                "--ignored",
                "--exact",
                "platform::process::tests::write_marker",
            ],
        )
        .unwrap();
        command
            .env_clear()
            .current_dir(root.path())
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        command
    };

    let (gate, spawning) = spawn_gated(command()).unwrap();
    let gate = gate.identify().await.unwrap();
    let pid = gate.pid();
    assert!(process_start_time(pid).is_ok());
    assert!(!marker.exists());
    drop(gate);
    assert!(spawning.await.unwrap().is_err());
    assert_eq!(
        process_start_time(pid).unwrap_err().kind(),
        io::ErrorKind::NotFound
    );
    assert!(!marker.exists());

    let (gate, spawning) = spawn_gated(command()).unwrap();
    gate.identify().await.unwrap().admit().unwrap();
    assert!(
        spawning
            .await
            .unwrap()
            .unwrap()
            .wait()
            .await
            .unwrap()
            .success()
    );
    assert_eq!(std::fs::read_to_string(marker).unwrap(), "executed\n");
}

// Bound a failed fixture without making the asserted state depend on scheduling.
const FIXTURE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(15);
const DESCENDANT_ADDRESS: &str = "FOUNDATION_DESCENDANT_ADDRESS";
const HOLD_LEADER: &str = "FOUNDATION_HOLD_LEADER";
const NEW_SESSION: &str = "FOUNDATION_NEW_SESSION";
const DESCENDANT_LEADER: &str = "platform::process::tests::descendant_leader";
const DESCENDANT_LEAF: &str = "platform::process::tests::descendant_leaf";

fn descendant_command(test: &str, address: std::net::SocketAddr) -> ResolvedCommand {
    let mut command = resolved_command(
        &std::env::current_exe().unwrap(),
        ["--ignored", "--exact", test],
    )
    .unwrap();
    command
        .env_clear()
        .env(DESCENDANT_ADDRESS, address.to_string())
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    // Winsock loads its providers through SystemRoot, even for loopback.
    #[cfg(windows)]
    command.env("SystemRoot", std::env::var_os("SystemRoot").unwrap());
    command
}

fn descendant_address() -> std::net::SocketAddr {
    std::env::var(DESCENDANT_ADDRESS).unwrap().parse().unwrap()
}

#[ignore = "launched only by the descendant cleanup fixture"]
#[tokio::test]
async fn descendant_leader() {
    let command = descendant_command(DESCENDANT_LEAF, descendant_address());
    // Unix allows a leaf to choose another group, or a different session entirely.
    #[cfg(unix)]
    let command = {
        let mut command = command;
        if std::env::var_os(NEW_SESSION).is_some() {
            // SAFETY: the fixture child only calls async-signal-safe setsid before exec.
            unsafe {
                command.command.pre_exec(|| {
                    if libc::setsid() < 0 {
                        Err(io::Error::last_os_error())
                    } else {
                        Ok(())
                    }
                });
            }
        } else {
            command.command.process_group(0);
        }
        command
    };
    let mut child = command.spawn().unwrap();
    if std::env::var_os(HOLD_LEADER).is_some() {
        child.wait().await.unwrap();
    }
    // Otherwise intentionally orphan the child to exercise cleanup after leader exit.
    drop(child);
}

#[test]
#[ignore = "launched only by the descendant cleanup fixture"]
fn descendant_leaf() {
    use std::io::{Read, Write};
    let mut connection = std::net::TcpStream::connect(descendant_address()).unwrap();
    connection
        .write_all(&std::process::id().to_ne_bytes())
        .unwrap();
    // Only our test owns the other end. If the test fails and closes it, the
    // fixture exits even without the cleanup implementation under test.
    let mut release = [0];
    let _ = connection.read(&mut release);
}

#[tokio::test]
async fn cleanup_stops_a_descendant_even_after_its_leader_exits() {
    let listener = listen().await;
    let mut child = spawn_now(descendant_command(
        DESCENDANT_LEADER,
        listener.local_addr().unwrap(),
    ))
    .await
    .unwrap();
    let (mut connection, descendant) = accept_leaf(&listener).await;
    assert!(child.wait_leader().await.unwrap().success());
    assert!(is_alive(Some(descendant)).unwrap());
    assert!(child.cleanup().await.unwrap().success());
    assert_leaf_stopped(&mut connection, descendant).await;
}

#[tokio::test]
async fn owner_cleanup_follows_regrouped_descendants_not_neighboring_work() {
    // The same API is a Job on Windows. The fixture's setsid branch applies only to Unix.
    for separate_session in [false, true] {
        let listener = listen().await;
        let address = listener.local_addr().unwrap();
        let mut command = descendant_command(DESCENDANT_LEADER, address);
        command.env(HOLD_LEADER, "yes");
        if separate_session {
            command.env(NEW_SESSION, "yes");
        }
        let mut child = spawn_in_owner_session(command).await.unwrap();
        let (mut connection, descendant) = accept_leaf(&listener).await;
        assert!(is_alive(Some(descendant)).unwrap());

        let mut neighbor = descendant_command(DESCENDANT_LEAF, address);
        neighbor.kill_on_drop(true).hide_console_window();
        let mut neighbor = neighbor.spawn().unwrap();
        let (neighbor_connection, neighbor_id) = accept_leaf(&listener).await;
        child.cleanup().await.unwrap();
        assert_leaf_stopped(&mut connection, descendant).await;
        assert!(is_alive(Some(neighbor_id)).unwrap());
        drop(neighbor_connection);
        assert!(neighbor.wait().await.unwrap().success());
    }
}

// Darwin cannot identify a descendant already reparented to init after it changes groups.
#[cfg(not(target_os = "macos"))]
#[tokio::test]
async fn owner_cleanup_retains_a_new_session_after_leader_exit() {
    use tokio::time::timeout;

    let listener = listen().await;
    let mut command = descendant_command(DESCENDANT_LEADER, listener.local_addr().unwrap());
    command.env(NEW_SESSION, "yes");
    #[cfg(target_os = "linux")]
    command.stdout(Stdio::piped());
    let mut child = spawn_in_owner_session(command).await.unwrap();
    let (mut connection, descendant) = accept_leaf(&listener).await;
    assert!(
        timeout(FIXTURE_DEADLINE, child.wait_leader())
            .await
            .unwrap()
            .unwrap()
            .success()
    );
    // Check the dedicated Linux reaper does not hold the workload's output pipe.
    #[cfg(target_os = "linux")]
    {
        use tokio::io::AsyncReadExt;
        let mut output = Vec::new();
        timeout(
            FIXTURE_DEADLINE,
            child.stdout().as_mut().unwrap().read_to_end(&mut output),
        )
        .await
        .unwrap()
        .unwrap();
    }
    assert!(is_alive(Some(descendant)).unwrap());
    assert!(child.cleanup().await.unwrap().success());
    assert_leaf_stopped(&mut connection, descendant).await;
}

async fn listen() -> tokio::net::TcpListener {
    tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
        .await
        .unwrap()
}

async fn accept_leaf(listener: &tokio::net::TcpListener) -> (tokio::net::TcpStream, ChildIdentity) {
    use tokio::{io::AsyncReadExt, time::timeout};
    let (mut connection, _) = timeout(FIXTURE_DEADLINE, listener.accept())
        .await
        .unwrap()
        .unwrap();
    let mut pid = [0; size_of::<u32>()];
    timeout(FIXTURE_DEADLINE, connection.read_exact(&mut pid))
        .await
        .unwrap()
        .unwrap();
    let descendant = child_identity(u32::from_ne_bytes(pid)).unwrap();
    (connection, descendant)
}

async fn assert_leaf_stopped(connection: &mut tokio::net::TcpStream, descendant: ChildIdentity) {
    use tokio::{io::AsyncReadExt, time::timeout};
    assert!(!is_alive(Some(descendant)).unwrap());
    // Terminating a process may close the connection cleanly or reset it.
    match timeout(FIXTURE_DEADLINE, connection.read(&mut [0]))
        .await
        .unwrap()
    {
        Ok(0) => {}
        Err(error) if error.kind() == io::ErrorKind::ConnectionReset => {}
        result => panic!("terminated descendant left its connection open: {result:?}"),
    }
    // Linux can reap adopted descendants itself rather than leaving zombies to init.
    #[cfg(target_os = "linux")]
    assert_eq!(
        process_start_time(descendant.pid.get()).unwrap_err().kind(),
        io::ErrorKind::NotFound
    );
}

// Only Windows has a Job breakaway creation flag.
#[cfg(windows)]
#[tokio::test]
#[ignore = "launched only inside the breakaway test's owned Job"]
async fn descendant_breakaway_is_denied() {
    use windows_sys::Win32::System::Threading::CREATE_BREAKAWAY_FROM_JOB;
    let mut command = descendant_command(DESCENDANT_LEAF, descendant_address());
    command.command.creation_flags(CREATE_BREAKAWAY_FROM_JOB);
    match command.spawn() {
        Err(error) => assert_eq!(error.kind(), io::ErrorKind::PermissionDenied),
        Ok(mut child) => {
            let _ = child.kill().await;
            panic!("a descendant broke away from its owned Job");
        }
    }
}

// Only Windows has a Job breakaway creation flag.
#[cfg(windows)]
#[tokio::test]
async fn the_job_disallows_breakaway() {
    let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap();
    let command = descendant_command(
        "platform::process::tests::descendant_breakaway_is_denied",
        listener.local_addr().unwrap(),
    );
    let mut child = spawn_now(command).await.unwrap();
    assert!(
        tokio::time::timeout(FIXTURE_DEADLINE, child.wait_leader())
            .await
            .unwrap()
            .unwrap()
            .success()
    );
    child.cleanup().await.unwrap();
}

// cmd.exe cannot honor a UNC working directory, even for a resolved ordinary batch file.
#[cfg(windows)]
#[tokio::test]
async fn an_ordinary_batch_launch_rejects_a_unc_working_directory() {
    let root = tempfile::tempdir().unwrap();
    let script = root.path().join("fixture.cmd");
    std::fs::write(&script, "@exit /b 0\r\n").unwrap();
    let command = || {
        let mut command = resolved_command(&script, std::iter::empty::<&str>()).unwrap();
        // Syntactic UNC refusal occurs before any network or native process operation.
        command.current_dir(r"\\fixture.invalid\share");
        command
    };
    assert_eq!(
        spawn_now(command()).await.err().unwrap().kind(),
        io::ErrorKind::Unsupported
    );
    assert_eq!(
        spawn_detached(command()).err().unwrap().kind(),
        io::ErrorKind::Unsupported
    );
}