canic-cli 0.292.0

Canic command line deployment tool
//! Terminal progress and per-invocation diagnostics for local startup.
use crate::{
    Output,
    args::{CanisterConfigArgs, SignerArgs},
};
use canic_host::{Error, Result};
use std::{
    fs::File,
    io::{IsTerminal as _, Write as _},
    path::Path,
    sync::mpsc,
    time::{Duration, Instant},
};

struct Line {
    text: String,
    animate: bool,
}

impl From<canic_host::local_fleet::StartupProgress<'_>> for Line {
    fn from(progress: canic_host::local_fleet::StartupProgress<'_>) -> Self {
        use canic_host::local_fleet::StartupProgress::{Checks, Context, Stage, Working};
        match progress {
            Stage(label) | Working(label) => Self {
                text: ic_host_text::escape(label).into_owned(),
                animate: matches!(progress, Working(_)),
            },
            Context(label, detail) => Self {
                text: format!("{label}  {}", ic_host_text::escape(detail)),
                animate: false,
            },
            Checks {
                stage,
                completed,
                total,
                next,
            } => {
                let filled = (completed * 10).checked_div(total).unwrap_or(10);
                let bar = format!("{}{}", "#".repeat(filled), "-".repeat(10 - filled));
                let target =
                    next.map_or_else(String::new, |n| format!("  {}", ic_host_text::escape(n)));
                Self {
                    text: format!("{stage}  [{bar}] {completed}/{total}{target}"),
                    animate: next.is_some(),
                }
            }
        }
    }
}

fn report(log: &mut File, text: &str, terminal: bool) {
    if terminal {
        eprintln!("{text}");
    }
    let _ = writeln!(log, "{text}");
}

pub(crate) async fn run(
    selection: &CanisterConfigArgs,
    signer: &SignerArgs,
    json: bool,
    open: bool,
    verbose: bool,
) -> Result<Output> {
    let directory = Path::new("target/fleet");
    let log_error = |e| {
        Error::Invalid(format!(
            "Local fleet startup failed while opening a log in {}: {e}",
            directory.display()
        ))
    };
    std::fs::create_dir_all(directory).map_err(log_error)?;
    let (mut log, path) = tempfile::Builder::new()
        .prefix("startup-")
        .suffix(".log")
        .tempfile_in(directory)
        .map_err(log_error)?
        .keep()
        .map_err(|e| log_error(e.error))?;
    let (tx, rx) = mpsc::channel::<Line>();
    let (painted, ready) = mpsc::sync_channel(0);
    let reporter = std::thread::spawn(move || {
        let interactive = !json
            && std::io::stderr().is_terminal()
            && std::env::var_os("TERM").as_deref() != Some("dumb".as_ref());
        let mut stage = "Select local fleet".to_owned();
        let mut since = Instant::now();
        let mut animate = false;
        let mut frame = 0_usize;
        let mut heartbeat = 0;
        report(&mut log, &stage, !json);
        loop {
            let interval = if animate {
                Duration::from_millis(160)
            } else {
                Duration::from_secs(5)
            };
            let event = rx.recv_timeout(interval);
            if frame > 0 && !matches!(event, Err(mpsc::RecvTimeoutError::Timeout)) {
                eprint!("\r\x1b[2K");
                frame = 0;
            }
            match event {
                Ok(next) => {
                    stage = next.text;
                    since = Instant::now();
                    heartbeat = 0;
                    animate = interactive && next.animate;
                    report(&mut log, &stage, !json);
                    let _ = painted.send(());
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    let elapsed = since.elapsed().as_secs();
                    if animate {
                        let spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧"];
                        eprint!("\r  {} {elapsed}s", spinner[frame % spinner.len()]);
                        frame += 1;
                    }
                    if elapsed / 5 > heartbeat {
                        heartbeat = elapsed / 5;
                        report(&mut log, &format!("{stage} ({elapsed}s elapsed)"), false);
                    }
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => return (log, stage),
            }
        }
    });
    let result = async {
        let config = selection.config.path(selection.app.as_deref())?;
        let frontend = if open {
            let declarations = canic_host::load_config(&config)?;
            let (_, app) = declarations.select_app(selection.app.as_deref())?;
            let (name, fleet) = app.fleet_declaration(selection.fleet.as_deref())?;
            let frontend = fleet.local_frontend.as_ref().ok_or_else(|| Error::Invalid(format!(
                "fleet {name:?} has no local_frontend; declare its program and port in canic.toml"
            )))?;
            let frontend = crate::frontend::resolve(&config, frontend)?;
            let _ = tx.send(Line {
                text: "Check frontend port".into(),
                animate: false,
            });
            let _ = ready.recv();
            frontend.check_port()?;
            Some(frontend)
        } else {
            None
        };
        let connection = canic_host::local_fleet::start_with_progress(
            &config,
            selection.app.as_deref(),
            selection.fleet.as_deref(),
            &signer.icp_bin,
            verbose,
            |stage| {
                if tx.send(Line::from(stage)).is_ok() {
                    let _ = ready.recv();
                }
            },
        )
        .await?;
        Ok((connection, frontend))
    }
    .await;
    drop(tx);
    let (mut log, stage) = reporter.join().expect("startup progress thread");
    let (connection, frontend) = match result {
        Ok(connection) => connection,
        Err(error) => {
            report(
                &mut log,
                &format!("Local fleet startup failed during {stage}: {error}"),
                false,
            );
            let context = format!(
                "Local fleet startup failed during {stage}: {error}\nLog: {}",
                path.display()
            );
            return Err(match error {
                Error::Blocked(_) => Error::Blocked(context),
                Error::Invalid(_) => Error::Invalid(context),
                _ => Error::Supplier(context.into()),
            });
        }
    };
    report(&mut log, "Local fleet ready", false);
    if let Some(frontend) = frontend {
        eprintln!(
            "Local fleet ready\nConnection: {}",
            ic_host_text::escape(&connection.display().to_string())
        );
        if let Err(error) = frontend.serve(&connection).await {
            report(&mut log, &format!("Frontend: {error}"), false);
            return Err(error);
        }
        return Ok(Output::Text(String::new()));
    }
    if json {
        Ok(Output::Json(
            serde_json::json!({"state":"ready", "connection":connection}),
        ))
    } else {
        Ok(Output::Text(format!(
            "Local fleet ready\nConnection: {}\n",
            ic_host_text::escape(&connection.display().to_string())
        )))
    }
}