use crate::{
Output,
args::{DeploymentStage, FleetCommand},
progress, status,
};
use canic_host::{ApplyOutcome, Error, FleetPlanning, Result, deployment};
use std::io::{IsTerminal, Write};
use std::time::Duration;
fn confirm(stage: &str) -> Result<bool> {
eprint!("Approve {stage}? [y/N] ");
std::io::stderr()
.flush()
.map_err(|e| Error::Invalid(e.to_string()))?;
let mut answer = String::new();
std::io::stdin()
.read_line(&mut answer)
.map_err(|e| Error::Invalid(e.to_string()))?;
Ok(matches!(
answer.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
}
pub(crate) async fn run(command: &FleetCommand, json: bool) -> Result<Output> {
let (operator, guided) = match command {
FleetCommand::Deploy(op) => (op, true),
FleetCommand::Bootstrap(s) | FleetCommand::Placement(s) => (s.operator(), false),
_ => unreachable!(),
};
if guided && (json || !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal()) {
return Err(Error::Invalid("guided deploy requires an interactive terminal; use fleet bootstrap review/apply and fleet placement review/apply for automation".into()));
}
let (path, fleet, journal) = operator.scope.resolve()?;
let identity = &operator.identity;
let icp = &operator.signer.icp_bin;
let controller = canic_host::signing_principal(identity, icp)?;
let output = |value: serde_json::Value, text: String| {
if json {
Output::Json(value)
} else {
Output::Text(text)
}
};
if !matches!(command, FleetCommand::Placement(_)) {
let digest = if let FleetCommand::Bootstrap(DeploymentStage::Apply { digest, .. }) = command
{
Some(digest.clone())
} else {
let review = deployment::bootstrap(&journal, &path, &fleet, &controller)?;
let (operation, text) = status::plan_preview(&review, &journal)?;
if !guided {
let next = operation.map_or_else(String::new, |id| {
progress::next(command, id, "apply", Some(identity))
});
return Ok(output(serde_json::json!(review), format!("{text}{next}")));
}
match &review {
FleetPlanning::Create { operation, .. } => {
eprintln!("Bootstrap\n{text}");
if !deployment::bootstrap_started(&journal, operation)?
&& !confirm("bootstrap")?
{
return Ok(Output::Text("Bootstrap awaiting approval.\n".into()));
}
Some(operation.clone())
}
FleetPlanning::Unchanged { operation } => {
eprintln!("Bootstrap complete ({operation}).");
None
}
_ => {
return Err(Error::Blocked(
"bootstrap requires installation or retained completion".into(),
));
}
}
};
if let Some(digest) = digest {
let until = std::time::Instant::now() + Duration::from_secs(180);
loop {
let result =
deployment::apply_bootstrap(&journal, &fleet, &digest, identity, icp).await?;
let complete = matches!(&result,ApplyOutcome::Fleet{store:Some(_),children,..} if children.iter().all(|c|matches!(c.outcome,ApplyOutcome::Complete(_))));
if complete {
if !guided {
return Ok(output(
serde_json::json!(result),
format!("Bootstrap complete ({digest}).\n"),
));
}
eprintln!("Bootstrap complete ({digest}).");
break;
}
if std::time::Instant::now() >= until {
return Err(Error::Blocked(format!(
"bootstrap {digest} is pending; resume the same deployment"
)));
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
}
let digest = if let FleetCommand::Placement(DeploymentStage::Apply { digest, .. }) = command {
digest.clone()
} else {
let Some(review) = deployment::placement(&journal, &path, &fleet, &controller)? else {
return Ok(output(
serde_json::json!({"placement":"not_configured"}),
"No placement pools declared.\n".into(),
));
};
let (_, text) = status::plan_preview(&review.terms, &journal)?;
let text = format!(
"{}Placement digest: {}\nSetup signing deadline (Unix ns): {}\n",
text.trim_end_matches("\nOffline review only. No operation submitted.\n"),
review.operation,
review.expires_at_ns
);
if !guided {
let next = progress::next(command, &review.operation, "apply", Some(identity));
return Ok(output(serde_json::json!(review), format!("{text}{next}")));
}
if review.complete {
return Ok(Output::Text(format!(
"Placement complete ({}).\n",
review.operation
)));
}
eprintln!("{text}");
if !review.started && !confirm("placement")? {
return Ok(Output::Text("Placement awaiting approval.\n".into()));
}
review.operation
};
deployment::apply_placement(&journal, &fleet, &digest, identity, icp).await?;
Ok(output(
serde_json::json!({"operation":digest,"stage":"placement","complete":true}),
format!("Placement complete ({digest}).\n"),
))
}