canic-cli 0.288.2

Canic command line deployment tool
//! Interactive application frontend for a verified local deployment.
use canic_host::{Error, LocalFrontend, Result};
use std::{
    path::{Path, PathBuf},
    process::Stdio,
    time::Duration,
};
use tokio::{io::AsyncReadExt as _, process::Command as AsyncCommand};

pub(crate) struct Frontend {
    program: PathBuf,
    directory: PathBuf,
    port: u16,
}

pub(crate) fn resolve(config: &Path, frontend: &LocalFrontend) -> Result<Frontend> {
    let directory = config
        .canonicalize()
        .map_err(io_error)?
        .parent()
        .expect("absolute config file")
        .to_owned();
    let program = directory.join(&frontend.program);
    Ok(Frontend {
        program,
        directory,
        port: frontend.port.get(),
    })
}

impl Frontend {
    pub(crate) fn check_port(&self) -> Result<()> {
        let url = format!("http://localhost:{}/", self.port);
        std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, self.port)).map_err(|error| {
            if error.kind() == std::io::ErrorKind::AddrInUse {
                Error::Blocked(format!("Frontend port {} is already in use ({url}). Stop the process listening there, then rerun the same command with --open.", self.port))
            } else {
                Error::Invalid(format!("Could not bind the frontend at {url}: {error}"))
            }
        })?;
        Ok(())
    }

    pub(crate) async fn serve(&self, connection: &Path) -> Result<()> {
        let url = format!("http://localhost:{}/", self.port);
        // The address may have become occupied during backend startup.
        self.check_port().map_err(|error| match error {
            Error::Blocked(reason) => Error::Blocked(format!("The fleet is running. {reason}")),
            other => other,
        })?;
        let mut command = AsyncCommand::new(&self.program);
        #[cfg(unix)]
        command.process_group(0);
        let mut child = command
            .current_dir(&self.directory)
            .arg(connection.canonicalize().map_err(io_error)?)
            .arg(self.port.to_string())
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .kill_on_drop(true)
            .spawn()
            .map_err(|error| {
                Error::Invalid(format!(
                    "could not start frontend {:?}: {error}",
                    self.program
                ))
            })?;
        let mut stdout = child.stdout.take().expect("piped stdout");
        let mut ready = [0; 6];
        tokio::select! {
            signal = tokio::signal::ctrl_c() => {signal.map_err(io_error)?; child.kill().await.map_err(io_error)?; return Ok(());}
            result = tokio::time::timeout(Duration::from_secs(30), stdout.read_exact(&mut ready)) => {
                result.map_err(|_| Error::Invalid(format!("frontend did not signal readiness at {url} within 30 seconds")))?
                    .map_err(|error| Error::Invalid(format!("frontend exited before readiness at {url}: {error}")))?;
            }
        }
        if &ready != b"READY\n" || child.try_wait().map_err(io_error)?.is_some() {
            return Err(Error::Invalid(format!(
                "frontend did not confirm readiness at {url}"
            )));
        }
        tokio::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, self.port))
            .await
            .map_err(|error| {
                Error::Invalid(format!("frontend is not listening at {url}: {error}"))
            })?;
        eprintln!("Application: {url}\nCtrl-C stops this frontend and leaves the fleet running.");
        crate::view::open_external(&url);
        tokio::select! {
            signal = tokio::signal::ctrl_c() => {signal.map_err(io_error)?; child.kill().await.map_err(io_error)}
            result = child.wait() => {
                let status = result.map_err(io_error)?;
                if status.success() { Ok(()) } else { Err(Error::Invalid(format!("frontend exited with {status}"))) }
            }
        }
    }
}

fn io_error(error: std::io::Error) -> Error {
    Error::Supplier(Box::new(error))
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::{
        fs,
        net::{Ipv4Addr, TcpListener},
        os::unix::fs::PermissionsExt,
        process::Command,
    };

    #[tokio::test]
    async fn occupied_frontend_port_reports_running_fleet_and_retry() {
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = listener.local_addr().unwrap().port();
        let frontend = Frontend {
            port,
            directory: PathBuf::new(),
            program: "should-never-launch".into(),
        };
        let Err(Error::Blocked(message)) = frontend.serve(Path::new("connection.json")).await
        else {
            panic!("occupied port must refuse launch");
        };
        assert!(message.contains("fleet is running"));
        assert!(message.contains(&format!("port {port} is already in use")));
        assert!(message.contains("--open"));
    }

    // Re-enter the test binary so the opener environment and SIGINT are isolated.
    #[tokio::test]
    async fn foreground_browser_session() {
        let Some(config) = std::env::var_os("CANIC_TEST_FRONTEND_CONFIG") else {
            return;
        };
        let config = PathBuf::from(config);
        let port = std::env::var("CANIC_TEST_FRONTEND_PORT")
            .unwrap()
            .parse()
            .unwrap();
        resolve(
            &config,
            &LocalFrontend {
                program: "server".into(),
                port,
            },
        )
        .unwrap()
        .serve(&config)
        .await
        .unwrap();
    }

    #[test]
    fn foreground_opens_verified_origin_and_releases_it_on_interrupt() {
        let dir = tempfile::tempdir().unwrap();
        let file = |name: &str, body: &str| {
            let path = dir.path().join(name);
            fs::write(&path, body).unwrap();
            fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
        };
        file(
            "server",
            r#"#!/usr/bin/env python3
import socket, sys
from pathlib import Path
assert Path(sys.argv[1]).read_text() == 'verified connection'
with socket.socket() as server:
    server.bind(('127.0.0.1', int(sys.argv[2])))
    server.listen()
    print('READY', flush=True)
    while True:
        conn, _ = server.accept()
        conn.close()
"#,
        );
        let opener = if cfg!(target_os = "macos") {
            "open"
        } else {
            "xdg-open"
        };
        file(
            opener,
            "#!/bin/sh\n[ -z \"$BROWSER\" ] || exit 1\nprintf '%s' \"$1\" > \"$CANIC_TEST_FRONTEND_URL\"\n",
        );
        let config = dir.path().join("connection.json");
        let receipt = dir.path().join("opened");
        fs::write(&config, "verified connection").unwrap();
        let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
            .unwrap()
            .local_addr()
            .unwrap()
            .port();
        let mut paths = vec![dir.path().to_owned()];
        paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
        let mut child = Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "frontend::tests::foreground_browser_session",
                "--nocapture",
            ])
            .env("PATH", std::env::join_paths(paths).unwrap())
            .env("BROWSER", "editor-preview")
            .env("CANIC_TEST_FRONTEND_CONFIG", config)
            .env("CANIC_TEST_FRONTEND_PORT", port.to_string())
            .env("CANIC_TEST_FRONTEND_URL", &receipt)
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        let url = format!("http://localhost:{port}/");
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        while fs::read_to_string(&receipt).ok().as_ref() != Some(&url) {
            if child.try_wait().unwrap().is_some() || std::time::Instant::now() >= deadline {
                let _ = child.kill();
                panic!("browser handoff failed: {:?}", child.wait_with_output());
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(
            Command::new("kill")
                .arg("-INT")
                .arg(child.id().to_string())
                .status()
                .unwrap()
                .success()
        );
        let output = child.wait_with_output().unwrap();
        assert!(output.status.success());
        assert!(String::from_utf8_lossy(&output.stderr).contains(&url));
        assert!(std::net::TcpStream::connect((Ipv4Addr::LOCALHOST, port)).is_err());
    }
}