canic-cli 0.283.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::Write as _,
    path::Path,
    sync::mpsc,
    time::{Duration, Instant},
};

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,
) -> 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();
    let reporter = std::thread::spawn(move || {
        let mut stage = "Select local fleet";
        let mut since = Instant::now();
        report(&mut log, stage, !json);
        loop {
            match rx.recv_timeout(Duration::from_secs(5)) {
                Ok(next) => {
                    stage = next;
                    since = Instant::now();
                    report(&mut log, stage, !json);
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    report(
                        &mut log,
                        &format!("{stage} ({}s elapsed)", since.elapsed().as_secs()),
                        !json,
                    );
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => return (log, stage),
            }
        }
    });
    let result = async {
        let config = selection.config.path(selection.app.as_deref())?;
        canic_host::local_fleet::start(
            &config,
            selection.app.as_deref(),
            selection.fleet.as_deref(),
            &signer.icp_bin,
            |stage| {
                let _ = tx.send(stage);
            },
        )
        .await
    }
    .await;
    drop(tx);
    let (mut log, stage) = reporter.join().expect("startup progress thread");
    let connection = 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 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())
        )))
    }
}