kayro-cli 0.1.0

Create, build, and run Kayro desktop apps for humans and agents
Documentation
use std::{
    net::{TcpStream, ToSocketAddrs as _},
    thread,
    time::{Duration, Instant},
};

use url::Url;

use crate::{
    args::DevArgs,
    cargo_command, cargo_progress,
    error::CliError,
    output::Reporter,
    process::{Cancellation, CommandSpec, ManagedChild, ProcessExit, run_cargo_command},
    project::Project,
};

pub fn run(
    project: &Project,
    arguments: &DevArgs,
    reporter: &Reporter,
    cancellation: &Cancellation,
    dry_run: bool,
) -> Result<(), CliError> {
    if arguments.ready_timeout == 0 {
        return Err(CliError::InvalidConfig {
            field: "ready_timeout",
            message: "must be at least one second".to_owned(),
        });
    }
    let dev_url = project.effective_dev_url(
        arguments.dev_url.as_deref(),
        arguments.host.as_deref(),
        arguments.port,
    )?;

    let native_packages = if dry_run {
        None
    } else {
        cargo_progress::estimate(project, &arguments.cargo, None)
    };

    if !arguments.skip_types {
        run_cargo_command(
            cargo_command::type_generation(project, &arguments.cargo),
            reporter,
            cancellation,
            dry_run,
            native_packages,
        )?;
    }

    let web_command = frontend_command(project, &dev_url)?;
    let native_command = cargo_command::native_dev(project, &arguments.cargo, dev_url.as_str());
    if dry_run {
        reporter.command_planned(&web_command);
        reporter.command_planned(&native_command);
        return Ok(());
    }

    let mut web = ManagedChild::spawn_plain(web_command, reporter)?;
    wait_for_server(
        &dev_url,
        Duration::from_secs(arguments.ready_timeout),
        &mut web,
        reporter,
        cancellation,
    )?;
    let mut native = ManagedChild::spawn_cargo(native_command, reporter, native_packages)?;

    loop {
        if cancellation.is_cancelled() {
            let _ = native.stop();
            let _ = web.stop();
            return Err(CliError::Interrupted);
        }
        if let Some(status) = native.try_wait()? {
            web.stop()?;
            return dev_exit("native", status, true);
        }
        if let Some(status) = web.try_wait()? {
            native.stop()?;
            return dev_exit("web", status, false);
        }
        thread::sleep(Duration::from_millis(25));
    }
}

fn frontend_command(project: &Project, dev_url: &Url) -> Result<CommandSpec, CliError> {
    let host = dev_url.host_str().ok_or_else(|| CliError::InvalidDevUrl {
        url: dev_url.to_string(),
        message: "URL has no host".to_owned(),
    })?;
    let port = dev_url
        .port_or_known_default()
        .ok_or_else(|| CliError::InvalidDevUrl {
            url: dev_url.to_string(),
            message: "URL has no port".to_owned(),
        })?;

    let mut command =
        CommandSpec::from_argv("web", project.frontend_dir.clone(), &project.dev_command);
    command
        .env("KAYRO_CONFIG", &project.config_path)
        .env("KAYRO_DEV_URL", dev_url.as_str())
        .env("KAYRO_DEV_HOST", host)
        .env("KAYRO_DEV_PORT", port.to_string());
    Ok(command)
}

fn wait_for_server(
    url: &Url,
    timeout: Duration,
    web: &mut ManagedChild,
    reporter: &Reporter,
    cancellation: &Cancellation,
) -> Result<(), CliError> {
    let host = url.host_str().ok_or_else(|| CliError::InvalidDevUrl {
        url: url.to_string(),
        message: "URL has no host".to_owned(),
    })?;
    let port = url
        .port_or_known_default()
        .ok_or_else(|| CliError::InvalidDevUrl {
            url: url.to_string(),
            message: "URL has no port".to_owned(),
        })?;
    let addresses = (host, port)
        .to_socket_addrs()
        .map_err(|error| CliError::InvalidDevUrl {
            url: url.to_string(),
            message: error.to_string(),
        })?
        .collect::<Vec<_>>();
    if addresses.is_empty() {
        return Err(CliError::InvalidDevUrl {
            url: url.to_string(),
            message: "host did not resolve to a socket address".to_owned(),
        });
    }

    let started = Instant::now();
    while started.elapsed() < timeout {
        if cancellation.is_cancelled() {
            web.stop()?;
            return Err(CliError::Interrupted);
        }
        if let Some(status) = web.try_wait()? {
            return Err(CliError::DevProcessExited {
                phase: "web".to_owned(),
                exit_code: status.code,
            });
        }
        if addresses
            .iter()
            .any(|address| TcpStream::connect_timeout(address, Duration::from_millis(100)).is_ok())
        {
            reporter.dev_server_ready(url.as_str(), started.elapsed());
            return Ok(());
        }
        thread::sleep(Duration::from_millis(50));
    }

    web.stop()?;
    Err(CliError::DevServerTimeout {
        url: url.to_string(),
        seconds: timeout.as_secs(),
    })
}

fn dev_exit(phase: &str, status: ProcessExit, allow_success: bool) -> Result<(), CliError> {
    if allow_success && status.success {
        Ok(())
    } else {
        Err(CliError::DevProcessExited {
            phase: phase.to_owned(),
            exit_code: status.code,
        })
    }
}