use std::collections::BTreeMap;
use std::ffi::OsString;
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use super::api::SandboxEntry;
use super::client::{self, Conn, Streamed};
use super::endpoint;
use super::machines::cli::{choose, found_of, machine_info, resolve_params};
use super::machines::{Where, parse_name};
use super::proto::{Notification, Response, Version};
use super::verbs::{GcParams, RebuildParams, RmParams, RunParams, ServicesRebuildParams, StartParams, StopParams, TtySize};
use crate::Command;
use crate::commands::run::cancel;
use crate::state::PhaseView;
pub(crate) mod identity;
use identity::{Ask, Scope};
const TICK: Duration = Duration::from_millis(100);
const CANCELLED_EXIT: i32 = 130;
const SETTLE_POLL: Duration = Duration::from_millis(500);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CliVerb {
Run {
sandbox: Option<String>,
name: Option<String>,
branch: Option<String>,
base: Option<String>,
profile: Option<String>,
json: bool,
reprobe: bool,
detach: bool,
place: bool,
},
Rebuild { target: Option<String>, force: bool, reprobe: bool, detach: bool },
Start { target: Option<String>, detach: bool },
Stop { target: Option<String> },
Rm { name: String, delete_branch: Option<bool>, force: bool },
ServicesRebuild { name: String },
Gc { force: bool },
}
impl CliVerb {
fn command(&self) -> &'static str {
match self {
CliVerb::Run { .. } => "run",
CliVerb::Rebuild { .. } => "rebuild",
CliVerb::Start { .. } => "start",
CliVerb::Stop { .. } => "stop",
CliVerb::Rm { .. } => "rm",
CliVerb::ServicesRebuild { .. } => "service rebuild",
CliVerb::Gc { .. } => "gc",
}
}
fn detach(&self) -> bool {
matches!(
self,
CliVerb::Run { detach: true, .. } | CliVerb::Rebuild { detach: true, .. } | CliVerb::Start { detach: true, .. }
)
}
fn builds(&self) -> bool {
matches!(self, CliVerb::Run { .. } | CliVerb::Rebuild { .. } | CliVerb::Start { .. })
}
}
pub(crate) fn from_command(command: &Command, machine: Option<&str>) -> Option<CliVerb> {
Some(match command {
Command::Gc { force } if machine.is_some() => CliVerb::Gc { force: *force },
Command::Run { env, dispatcher, .. } if !env.is_empty() || dispatcher.is_some() => return None,
Command::Run { sandbox, name, branch, base, profile, json, reprobe, detach, place, .. } => CliVerb::Run {
sandbox: sandbox.clone(),
name: name.clone(),
branch: branch.clone(),
base: base.clone(),
profile: profile.clone(),
json: *json,
reprobe: *reprobe,
detach: *detach,
place: *place,
},
Command::Rebuild { name, force, reprobe, detach, .. } => {
CliVerb::Rebuild { target: name.clone(), force: *force, reprobe: *reprobe, detach: *detach }
}
Command::Start { name, detach, .. } => CliVerb::Start { target: name.clone(), detach: *detach },
Command::Stop { name, .. } => CliVerb::Stop { target: name.clone() },
Command::Rm { fail_on_ask: true, .. } => return None,
Command::Rm { name, delete_branch, keep_branch, force, .. } => CliVerb::Rm {
name: name.clone(),
delete_branch: crate::rm_branch_flag(*delete_branch, *keep_branch),
force: *force,
},
Command::Service { cmd: crate::ServiceCommand::Rebuild { name } } => CliVerb::ServicesRebuild { name: name.clone() },
_ => return None,
})
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Fed {
pub machines: bool,
pub machine: Option<String>,
}
impl CliVerb {
fn name(&self) -> Option<&str> {
match self {
CliVerb::Run { sandbox: name, .. }
| CliVerb::Rebuild { target: name, .. }
| CliVerb::Start { target: name, .. }
| CliVerb::Stop { target: name } => name.as_deref(),
CliVerb::Rm { name, .. } => Some(name),
CliVerb::ServicesRebuild { .. } | CliVerb::Gc { .. } => None,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Done {
Exit(i32),
InProcess(String),
}
pub(crate) fn run(dir: &Path, verb: CliVerb, fed: &Fed) -> Result<Done> {
let root = dir.canonicalize().with_context(|| format!("no directory {}", dir.display()))?;
let env = caller_env(std::env::vars_os());
let tty = std::io::stdin().is_terminal();
let term = crate::build_log::terminal_size(1).filter(|_| std::io::stderr().is_terminal());
let mut ui = Ui {
tty,
term,
runs_here: crate::runtime::installed::installed(),
pick: &mut |prompt, options| {
let refs: Vec<&str> = options.iter().map(String::as_str).collect();
crate::commands::pick(prompt, &refs)
},
offer_example: &mut || crate::commands::run::offer_example_config(&root),
ask: &mut |question, choices, default| crate::ask::select(question, choices, default),
say: &mut |text| eprintln!("{text}"),
style: crate::ask::Style::detect(),
};
let mut conn = match endpoint::socket_dir().and_then(|socket| client::connect(&socket, "cli")) {
Ok(conn) => conn,
Err(e) => {
let done = in_process(&verb, fed, format!("{e:#}"))?;
if ui.tty {
let asks = identity::local_asks(&verb, &root, fed, &mut identity::local_call)?;
identity::prompt(asks, &mut identity::local_call, &mut ui)?;
}
return Ok(done);
}
};
let list = match prepare(&verb, &root, env, fed, &mut |method, params| conn.call(method, params), &mut ui)? {
Prep::Send(prepared) => vec![prepared],
Prep::Each(list) => list,
Prep::Exit(code) => return Ok(Done::Exit(code)),
Prep::Old(why) => return in_process(&verb, fed, why),
};
let mut code = 0;
for prepared in list {
if let Some(banner) = &prepared.banner {
eprintln!("{banner}");
}
let (done, go_on) = send(&mut conn, &verb, prepared)?;
match done {
Done::Exit(c) if code == 0 => code = c,
Done::Exit(_) => {}
Done::InProcess(why) => return in_process(&verb, fed, why),
}
if !go_on {
break;
}
}
Ok(Done::Exit(code))
}
fn send(conn: &mut Conn, verb: &CliVerb, prepared: Prepared) -> Result<(Done, bool)> {
let instance = prepared.instance.clone();
let machine = prepared.machine.clone();
let mut last = Streaming::new(instance.clone(), false, None);
let answer = with_answers(
prepared.params,
&mut |params| {
let (answer, streaming) = stream(conn, verb, prepared.method, params, instance.clone(), machine.clone())?;
last = streaming;
Ok(answer)
},
&mut |question| crate::commands::confirm(question),
&mut approve_here,
)?;
if let Answer::Ok(v) = &answer
&& last.instance.is_none()
{
last.instance = v["instance"].as_str().map(str::to_string);
}
let placed = match &answer {
Answer::Ok(v) => v["machine"].as_str().map(str::to_string),
_ => None,
};
let machine = machine.or(last.placed.clone()).or(placed);
last.finish_stdout();
let ending = ending(answer, last.cancelled);
if !matches!(ending, Ok(Ending::Detached(_))) {
last.replay();
}
Ok(match ending? {
Ending::Exit(code) => (Done::Exit(code), code != CANCELLED_EXIT),
Ending::Detached(result) => {
for line in held_notes(last.held.as_deref().unwrap_or_default()) {
eprintln!("{line}");
}
print_detached(verb, &result, machine.as_deref())?;
(Done::Exit(0), true)
}
Ending::Lost => (Done::Exit(lost(verb, last.instance.as_deref(), machine.as_deref())?), false),
Ending::Old(why) => (Done::InProcess(why), false),
})
}
fn in_process(verb: &CliVerb, fed: &Fed, why: String) -> Result<Done> {
if let Some(m) = &fed.machine {
bail!("--machine {m} needs devsandbox serve: {why}");
}
if fed.machines
&& let Some(name) = verb.name()
&& let Ok((Where::Machine(m), _)) = parse_name(name)
{
bail!("`{name}` is on machine `{m}`, which needs devsandbox serve: {why}");
}
if !verb.detach() {
eprintln!("warning: devsandbox serve: {why}; running in-process");
}
Ok(Done::InProcess(why))
}
pub(crate) fn caller_env(vars: impl IntoIterator<Item = (OsString, OsString)>) -> BTreeMap<String, String> {
vars.into_iter().filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))).collect()
}
type AskFn<'a> = dyn FnMut(&str, &[crate::ask::Choice], usize) -> Result<crate::ask::Answer> + 'a;
struct Ui<'a> {
tty: bool,
term: Option<TtySize>,
pick: &'a mut dyn FnMut(&str, &[String]) -> Result<usize>,
offer_example: &'a mut dyn FnMut() -> Result<()>,
ask: &'a mut AskFn<'a>,
say: &'a mut dyn FnMut(&str),
style: crate::ask::Style,
runs_here: bool,
}
#[derive(Debug)]
enum Prep {
Send(Prepared),
Each(Vec<Prepared>),
Exit(i32),
Old(String),
}
#[derive(Debug)]
struct Prepared {
method: &'static str,
params: Value,
instance: Option<String>,
machine: Option<String>,
banner: Option<String>,
}
enum Reply {
Ok(Value),
Old(String),
Err(super::proto::ErrorBody),
}
fn reply(r: Response) -> Reply {
match r.error {
Some(e) if e.code == "unknown-method" => Reply::Old(format!("{} ({})", e.message, e.code)),
Some(e) => Reply::Err(e),
None => Reply::Ok(r.result.unwrap_or(Value::Null)),
}
}
type Call<'a> = dyn FnMut(&str, Value) -> Result<Response> + 'a;
fn prepare(
verb: &CliVerb,
root: &Path,
env: BTreeMap<String, String>,
fed: &Fed,
call: &mut Call,
ui: &mut Ui,
) -> Result<Prep> {
let root: PathBuf = root.to_path_buf();
macro_rules! resolved {
($name:expr) => {
match target_of($name, &root, fed, call, ui)? {
Ok(target) => target,
Err(old) => return Ok(Prep::Old(old)),
}
};
}
let machine_roots = |call: &mut Call| -> Result<Option<(String, Vec<PathBuf>)>> {
let Some(m) = &fed.machine else { return Ok(None) };
let roots = machine_info(call, m)?.entry.roots;
if roots.is_empty() {
bail!("machine `{m}` has no config roots (devsandbox machine ls)");
}
Ok(Some((m.clone(), roots)))
};
let one = |method, params: Value, target: Option<&Target>| Prepared {
method,
params: routed(params, target.and_then(|t| t.machine.as_deref())),
instance: target.map(|t| t.name.clone()),
machine: target.and_then(|t| t.machine.clone()),
banner: None,
};
let prepared = match verb.clone() {
CliVerb::Run { sandbox, name, branch, base, profile, json, reprobe, detach, place } => {
let Some(target) = run_target(sandbox, place, &root, fed, call, ui, json)? else {
return Ok(Prep::Exit(0));
};
let target = match target {
Ok(target) => target,
Err(old) => return Ok(Prep::Old(old)),
};
if !json {
identity::prompt(target.ask().into_iter().collect(), call, ui)?;
}
let tty = if json { None } else { ui.term };
let ask = ui.tty && !json && !detach && !place && target.machine.is_none();
let p = RunParams {
root: target.root.clone(),
env,
sandbox: target.name.clone(),
name,
branch,
base,
profile,
json,
reprobe,
detach,
tty,
place,
ask,
};
Prepared { instance: None, ..one("run", serde_json::to_value(p)?, Some(&target)) }
}
CliVerb::Rebuild { target, force, reprobe, detach } => match target {
Some(name) => {
let t = resolved!(&name);
identity::prompt(t.ask().into_iter().collect(), call, ui)?;
let p = RebuildParams {
root: t.root.clone(),
env,
instance: Some(t.name.clone()),
all: false,
force,
reprobe,
detach,
tty: ui.term,
};
one("rebuild", serde_json::to_value(p)?, Some(&t))
}
None => match machine_roots(call)? {
None => {
identity::prompt(vec![every(&root, None)], call, ui)?;
let p = RebuildParams { root, env, instance: None, all: true, force, reprobe, detach, tty: ui.term };
one("rebuild", serde_json::to_value(p)?, None)
}
Some((m, roots)) => {
identity::prompt(roots.iter().map(|r| every(r, Some(&m))).collect(), call, ui)?;
let mut each = Vec::new();
for root in roots {
let banner = super::machines::cli::banner(&m, &root);
let p =
RebuildParams { root, env: env.clone(), instance: None, all: true, force, reprobe, detach, tty: ui.term };
each.push(on_machine("rebuild", serde_json::to_value(p)?, &m, banner));
}
return Ok(Prep::Each(each));
}
},
},
CliVerb::Start { target, detach } => match target {
Some(name) => {
let t = resolved!(&name);
identity::prompt(t.ask().into_iter().collect(), call, ui)?;
let p = StartParams { root: t.root.clone(), env, instance: Some(t.name.clone()), all: false, detach, tty: ui.term };
one("start", serde_json::to_value(p)?, Some(&t))
}
None => {
let (root, m) = match machine_roots(call)? {
None => {
identity::prompt(vec![every(&root, None)], call, ui)?;
(root, None)
}
Some((m, roots)) => {
identity::prompt(roots.iter().map(|r| every(r, Some(&m))).collect(), call, ui)?;
(roots[0].clone(), Some(m))
}
};
let p = StartParams { root, env, instance: None, all: true, detach, tty: ui.term };
Prepared { machine: m.clone(), ..one("start", routed(serde_json::to_value(p)?, m.as_deref()), None) }
}
},
CliVerb::Stop { target } => match target {
Some(name) => {
let t = resolved!(&name);
let p = StopParams { root: t.root.clone(), env, instance: Some(t.name.clone()), all: false, detach: false };
one("stop", serde_json::to_value(p)?, Some(&t))
}
None => {
let (root, m) = match machine_roots(call)? {
None => (root, None),
Some((m, roots)) => (roots[0].clone(), Some(m)),
};
let p = StopParams { root, env, instance: None, all: true, detach: false };
Prepared { machine: m.clone(), ..one("stop", routed(serde_json::to_value(p)?, m.as_deref()), None) }
}
},
CliVerb::Rm { name, delete_branch, force } => {
let t = resolved!(&name);
let ask = ui.tty && delete_branch.is_none();
let p = RmParams { root: t.root.clone(), env, instance: t.name.clone(), delete_branch, force, ask, detach: false };
one("rm", serde_json::to_value(p)?, Some(&t))
}
CliVerb::ServicesRebuild { name } => match machine_roots(call)? {
None => {
let p = ServicesRebuildParams { root, env, name, detach: false };
one("services.rebuild", serde_json::to_value(p)?, None)
}
Some((m, roots)) => {
let mut each = Vec::new();
for root in &roots {
match reply(call("services.get", json!({ "root": root, "name": name, "machine": m }))?) {
Reply::Ok(_) => {}
Reply::Err(e) if e.code == "not-found" => continue,
Reply::Old(why) => return Ok(Prep::Old(why)),
Reply::Err(e) => bail!("{}", e.message),
}
let banner = super::machines::cli::banner(&m, root);
let p = ServicesRebuildParams { root: root.clone(), env: env.clone(), name: name.clone(), detach: false };
each.push(on_machine("services.rebuild", serde_json::to_value(p)?, &m, banner));
}
if each.is_empty() {
let list: Vec<String> = roots.iter().map(|r| r.display().to_string()).collect();
bail!("no service `{name}` on machine `{m}` (roots: {})", list.join(", "));
}
return Ok(Prep::Each(each));
}
},
CliVerb::Gc { force } => match machine_roots(call)? {
None => one("gc", serde_json::to_value(GcParams { root, env, force, detach: false })?, None),
Some((m, roots)) => {
let mut config = Vec::new();
for at in &roots {
let list = match reply(call("instances.list", json!({ "dir": at, "depth": "disk", "machine": m }))?) {
Reply::Ok(v) => serde_json::from_value(v).context("bad instances.list result from devsandbox serve")?,
Reply::Old(why) => return Ok(Prep::Old(why)),
Reply::Err(e) => bail!("{}", e.message),
};
config.extend(super::machines::cli::config_roots(at, &list));
}
config.sort();
config.dedup();
let mut each = Vec::new();
for root in config {
let banner = super::machines::cli::banner(&m, &root);
let p = GcParams { root, env: env.clone(), force, detach: false };
each.push(on_machine("gc", serde_json::to_value(p)?, &m, banner));
}
return Ok(Prep::Each(each));
}
},
};
Ok(Prep::Send(prepared))
}
fn routed(mut params: Value, machine: Option<&str>) -> Value {
if let Some(m) = machine {
params["machine"] = json!(m);
}
params
}
fn every(root: &Path, machine: Option<&str>) -> Ask {
Ask { root: root.to_path_buf(), machine: machine.map(str::to_string), scope: Scope::Used }
}
fn on_machine(method: &'static str, params: Value, m: &str, banner: String) -> Prepared {
Prepared { method, params: routed(params, Some(m)), instance: None, machine: Some(m.to_string()), banner: Some(banner) }
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Target {
name: String,
machine: Option<String>,
root: PathBuf,
sandbox: Option<String>,
}
impl Target {
fn ask(&self) -> Option<Ask> {
let sandbox = self.sandbox.clone()?;
Some(Ask { root: self.root.clone(), machine: self.machine.clone(), scope: Scope::Sandboxes(vec![sandbox]) })
}
}
fn target_of(name: &str, root: &Path, fed: &Fed, call: &mut Call, ui: &mut Ui) -> Result<Result<Target, String>> {
let (wherever, name) = if fed.machines { parse_name(name)? } else { (Where::Local, name.to_string()) };
let params = match wherever {
Where::Local => json!({ "name": name }),
_ => resolve_params(&wherever, &name),
};
let found = match reply(call("instances.resolve", params)?) {
Reply::Ok(v) => found_of(v, &wherever)?,
Reply::Old(why) => return Ok(Err(why)),
Reply::Err(e) => bail!("{}", e.message),
};
let Some(found) = choose(&name, found, ui.tty, &mut *ui.pick)? else {
bail!("{}", crate::commands::no_instance_matches(&name));
};
let Some(m) = found.machine else {
return Ok(Ok(Target { name: found.name, machine: None, root: root.to_path_buf(), sandbox: found.sandbox }));
};
let root = match found.root {
Some(root) => root,
None => machine_info(call, &m)?.root_or_default(None)?,
};
Ok(Ok(Target { name: found.name, machine: Some(m), root, sandbox: found.sandbox }))
}
fn run_target(
sandbox: Option<String>,
place: bool,
root: &Path,
fed: &Fed,
call: &mut Call,
ui: &mut Ui,
json: bool,
) -> Result<Option<Result<Target, String>>> {
let params = if fed.machines { json!({ "root": root, "machines": true }) } else { json!({ "root": root }) };
let rows: Vec<SandboxEntry> = match reply(call("sandboxes.list", params)?) {
Reply::Ok(rows) => serde_json::from_value(rows).context("bad sandboxes.list result from devsandbox serve")?,
Reply::Old(why) => return Ok(Some(Err(why))),
Reply::Err(e) => bail!("{}", e.message),
};
let wanted = match sandbox {
Some(s) if fed.machines => Some(parse_name(&s)?),
Some(s) => Some((Where::Any, s)),
None => None,
};
let wanted = match (wanted, place) {
(Some((Where::Machine(m), name)), true) => {
bail!("--place asks the control plane where to run this host's sandbox; `{m}/{name}` is on machine `{m}`")
}
(Some((_, name)), true) => Some((Where::Local, name)),
(wanted, _) => wanted,
};
let rows = if place { rows.into_iter().filter(|r| r.machine.is_none()).collect() } else { rows };
let local = |name: String| Target { sandbox: Some(name.clone()), name, machine: None, root: root.to_path_buf() };
let there = |row: SandboxEntry| -> Result<Target> {
let root = row.root.context("bad sandboxes.list entry from devsandbox serve: no root")?;
Ok(Target { sandbox: Some(row.name.clone()), name: row.name, machine: row.machine, root })
};
let target = match choose_sandbox(rows, wanted, ui.runs_here) {
SandboxChoice::Example { unmatched } => {
if let Some(name) = unmatched.filter(|_| fed.machines && !place) {
note_unreachable(&name, call);
}
(ui.offer_example)()?;
if json {
bail!("no instance created");
}
return Ok(None);
}
SandboxChoice::Here { sandbox, matched } => {
if !matched && fed.machines && !place {
note_unreachable(&sandbox, call);
}
local(sandbox)
}
SandboxChoice::There(row) => there(row)?,
SandboxChoice::Missing { machine, sandbox } => {
bail!("no sandbox `{sandbox}` on machine `{machine}`{}", unreachable_suffix(&unreachable(call), Some(&machine)))
}
SandboxChoice::Pick { prompt, error, mut options } => {
if !ui.tty {
bail!("{error}");
}
let labels: Vec<String> = options.iter().map(|(label, _)| label.clone()).collect();
let at = (ui.pick)(&prompt, &labels)?;
if at >= options.len() {
bail!("selection out of range");
}
match options.swap_remove(at).1 {
row if row.machine.is_none() => local(row.name),
row => there(row)?,
}
}
};
Ok(Some(Ok(target)))
}
#[derive(Debug, PartialEq)]
enum SandboxChoice {
Example { unmatched: Option<String> },
Here { sandbox: String, matched: bool },
There(SandboxEntry),
Missing { machine: String, sandbox: String },
Pick { prompt: String, error: String, options: Vec<(String, SandboxEntry)> },
}
fn choose_sandbox(rows: Vec<SandboxEntry>, wanted: Option<(Where, String)>, runs_here: bool) -> SandboxChoice {
let local_empty = !rows.iter().any(|r| r.machine.is_none());
let drop_local = |rows: Vec<SandboxEntry>| -> Vec<SandboxEntry> {
if runs_here || rows.iter().all(|r| r.machine.is_none()) {
return rows;
}
rows.into_iter().filter(|r| r.machine.is_some()).collect()
};
let Some((wherever, name)) = wanted else {
let rows = drop_local(rows);
if rows.is_empty() {
return SandboxChoice::Example { unmatched: None };
}
let labels: Vec<String> = rows.iter().map(|r| sandbox_label(r, &rows, false)).collect();
let error = format!("no sandbox specified; available: {}", labels.join(", "));
let options = labels.into_iter().zip(rows).collect();
return SandboxChoice::Pick { prompt: "Select a sandbox".into(), error, options };
};
let fits = |r: &SandboxEntry| {
r.name == name
&& match &wherever {
Where::Any => true,
Where::Local => r.machine.is_none(),
Where::Machine(m) => r.machine.as_ref() == Some(m),
}
};
let mut candidates: Vec<SandboxEntry> = drop_local(rows.iter().filter(|r| fits(r)).cloned().collect());
match candidates.len() {
0 => match wherever {
Where::Machine(machine) => SandboxChoice::Missing { machine, sandbox: name },
_ if local_empty => SandboxChoice::Example { unmatched: Some(name) },
_ => SandboxChoice::Here { sandbox: name, matched: false },
},
1 => match candidates.pop().expect("one") {
row if row.machine.is_none() => SandboxChoice::Here { sandbox: row.name, matched: true },
row => SandboxChoice::There(row),
},
_ => {
let labels: Vec<String> = candidates.iter().map(|r| sandbox_label(r, &candidates, true)).collect();
let (prompt, hint) = match &candidates[0].machine {
one if candidates.iter().all(|r| &r.machine == one) => {
(format!("`{name}` is defined in several roots of `{}`", one.as_deref().unwrap_or("@")), "")
}
_ => (format!("`{name}` is defined on several machines"), "; qualify it"),
};
let error = format!("{prompt}: {}{hint}", labels.join(", "));
SandboxChoice::Pick { prompt, error, options: labels.into_iter().zip(candidates).collect() }
}
}
}
fn sandbox_label(row: &SandboxEntry, rows: &[SandboxEntry], local_qualified: bool) -> String {
let base = match &row.machine {
Some(m) => format!("{m}/{}", row.name),
None if local_qualified => format!("@/{}", row.name),
None => row.name.clone(),
};
let twice = rows.iter().filter(|r| r.machine == row.machine && r.name == row.name).count() > 1;
match (&row.root, twice) {
(Some(root), true) => format!("{base} ({})", root.display()),
_ => base,
}
}
fn unreachable(call: &mut Call) -> Vec<String> {
let Ok(Reply::Ok(rows)) = call("machines.list", json!({})).map(reply) else { return Vec::new() };
let rows = rows.as_array().cloned().unwrap_or_default();
rows.iter()
.filter(|r| r["state"] == "unreachable")
.filter_map(|r| {
let name = r["name"].as_str()?;
Some(match r["error"].as_str() {
Some(why) => format!("{name} ({why})"),
None => name.to_string(),
})
})
.collect()
}
fn unreachable_suffix(items: &[String], machine: Option<&str>) -> String {
let items: Vec<&String> =
items.iter().filter(|i| machine.is_none_or(|m| i.as_str() == m || i.starts_with(&format!("{m} (")))).collect();
match items.is_empty() {
true => String::new(),
false => format!("; unreachable: {}", items.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")),
}
}
fn note_unreachable(sandbox: &str, call: &mut Call) {
let suffix = unreachable_suffix(&unreachable(call), None);
if let Some(list) = suffix.strip_prefix("; ") {
eprintln!("note: no machine reached defines `{sandbox}`; {list}");
}
}
#[derive(Debug, PartialEq)]
enum Answer {
Ok(Value),
Failed(i32),
Confirm(String),
Approve(Unapproved),
Error(String),
Old(String),
HungUp,
Lost,
}
impl Answer {
fn of(streamed: Streamed) -> Answer {
let r = match streamed {
Streamed::Answer(r) => r,
Streamed::HungUp => return Answer::HungUp,
Streamed::Lost => return Answer::Lost,
};
match reply(r) {
Reply::Ok(v) => Answer::Ok(v),
Reply::Old(why) => Answer::Old(why),
Reply::Err(e) if e.code == "failed" => {
let exit = e.data.as_ref().and_then(|d| d["exit"].as_i64()).and_then(|n| i32::try_from(n).ok());
Answer::Failed(exit.filter(|&n| n != 0).unwrap_or(1))
}
Reply::Err(e) if e.code == "confirm" => Answer::Confirm(e.message),
Reply::Err(e) if e.code == "approve" => {
let field = |k: &str| e.data.as_ref().and_then(|d| d[k].as_str()).map(str::to_string);
match (field("credential"), field("version")) {
(Some(credential), Some(version)) => {
Answer::Approve(Unapproved { credential, version, message: e.message })
}
_ => Answer::Error(e.message),
}
}
Reply::Err(e) => Answer::Error(e.message),
}
}
}
#[derive(Debug, Clone, PartialEq)]
struct Unapproved {
credential: String,
version: String,
message: String,
}
impl Unapproved {
fn refusal(&self) -> String {
crate::commands::run::refusal(&self.message, &self.credential, None)
}
}
fn with_answers(
params: Value,
send: &mut dyn FnMut(Value) -> Result<Answer>,
confirm: &mut dyn FnMut(&str) -> Result<bool>,
approve: &mut dyn FnMut(&str, &str) -> Result<bool>,
) -> Result<Answer> {
let mut params = params;
let mut confirmed = false;
let mut approved: Vec<String> = Vec::new();
loop {
match send(params.clone())? {
Answer::Confirm(question) if !confirmed => {
params["deleteBranch"] = confirm(&question)?.into();
params["ask"] = false.into();
confirmed = true;
}
Answer::Confirm(question) => bail!("devsandbox serve asked again: {question}"),
Answer::Approve(u) if !approved.contains(&u.credential) => {
if !approve(&u.credential, &u.version)? {
bail!("{}", u.refusal());
}
approved.push(u.credential);
}
Answer::Approve(u) => bail!("devsandbox serve asked again: {}", u.message),
answer => return Ok(answer),
}
}
}
fn approve_here(credential: &str, version: &str) -> Result<bool> {
let path = crate::credentials::home::path(&crate::commands::login::data_dir()?);
crate::commands::access::ask_approve(&path, credential, Some(version), &mut crate::commands::login::Stdio)
}
#[derive(Debug, Clone)]
struct Streaming {
instance: Option<String>,
cancelled: bool,
track_progress: bool,
held: Option<Vec<(bool, String)>>,
qualify: Option<String>,
partial: String,
pending: Option<String>,
placed: Option<String>,
qualify_placed: bool,
}
impl Streaming {
fn new(instance: Option<String>, track_progress: bool, held: Option<Vec<(bool, String)>>) -> Self {
Self {
instance,
cancelled: false,
track_progress,
held,
qualify: None,
partial: String::new(),
pending: None,
placed: None,
qualify_placed: false,
}
}
}
fn stream(
conn: &mut Conn,
verb: &CliVerb,
method: &str,
params: Value,
instance: Option<String>,
machine: Option<String>,
) -> Result<(Answer, Streaming)> {
let track_progress = matches!(verb, CliVerb::Run { .. });
let held = (verb.detach() || matches!(verb, CliVerb::Rm { .. }) && params["ask"] == true).then(Vec::new);
let mut s = Streaming::new(instance, track_progress, held);
s.qualify_placed = matches!(verb, CliVerb::Run { json: false, .. });
s.qualify = machine.clone().filter(|_| s.qualify_placed);
let _guard = cancel::catch();
let streamed = conn.call_streaming(method, params, TICK, &mut |note| {
if let Some(note) = note {
s.observe(note);
}
if cancel::requested() && !s.cancelled {
s.cancelled = true;
return match &s.instance {
Some(instance) => cancel_by_name(instance, machine.as_deref().or(s.placed.as_deref())),
None => false,
};
}
true
})?;
Ok((Answer::of(streamed), s))
}
impl Streaming {
fn observe(&mut self, note: &Notification) {
match note.method.as_str() {
"output" => {
let data = note.params["data"].as_str().unwrap_or_default();
let stdout = note.params["stream"] == "stdout";
match &mut self.held {
Some(held) => held.push((stdout, data.to_string())),
None if stdout && self.qualify.is_some() => self.stdout_lines(data),
None => print_output(stdout, data),
}
}
"progress" if self.track_progress && self.instance.is_none() => {
self.instance = note.params["instance"].as_str().map(str::to_string);
if let Some(m) = note.params["machine"].as_str() {
self.placed = Some(m.to_string());
if self.qualify_placed && self.qualify.is_none() {
self.qualify = Some(m.to_string());
}
}
}
_ => {}
}
}
}
impl Streaming {
fn stdout_lines(&mut self, data: &str) {
self.partial.push_str(data);
while let Some(at) = self.partial.find('\n') {
let line: String = self.partial.drain(..=at).collect();
if let Some(before) = self.pending.replace(line) {
print_output(true, &before);
}
}
}
fn finish_stdout(&mut self) {
let last = self.pending.take().map(|line| self.qualified(line));
let rest = std::mem::take(&mut self.partial);
print_output(true, &(last.unwrap_or_default() + &rest));
}
fn qualified(&self, line: String) -> String {
match (&self.qualify, &self.instance) {
(Some(m), Some(instance)) if line.trim_end_matches(['\n', '\r']) == instance => format!("{m}/{line}"),
_ => line,
}
}
fn replay(&mut self) {
for (stdout, data) in self.held.take().unwrap_or_default() {
print_output(stdout, &data);
}
}
}
fn held_notes(held: &[(bool, String)]) -> Vec<String> {
let stderr: String = held.iter().filter(|(stdout, _)| !stdout).map(|(_, d)| d.as_str()).collect();
stderr.lines().filter(|l| l.starts_with("note: ")).map(str::to_string).collect()
}
fn print_output(stdout: bool, data: &str) {
if stdout {
let mut out = std::io::stdout().lock();
let _ = out.write_all(data.as_bytes()).and_then(|()| out.flush());
} else {
let mut err = std::io::stderr().lock();
let _ = err.write_all(data.as_bytes()).and_then(|()| err.flush());
}
}
fn cancel_by_name(instance: &str, machine: Option<&str>) -> bool {
let Ok(socket) = endpoint::socket_dir() else { return false };
let conn = client::connect_running(&socket, "cli", &Version::current(), client::START_TIMEOUT);
let Ok(Some(mut conn)) = conn else { return false };
match conn.call("instances.cancel", routed(json!({ "instance": instance }), machine)) {
Ok(Response { error: None, .. }) => {
eprintln!("cancelling {instance}…");
true
}
_ => false,
}
}
#[derive(Debug, PartialEq)]
enum Ending {
Exit(i32),
Detached(Value),
Lost,
Old(String),
}
fn ending(answer: Answer, cancelled: bool) -> Result<Ending> {
Ok(match answer {
Answer::Old(why) => Ending::Old(why),
Answer::HungUp => Ending::Exit(CANCELLED_EXIT),
Answer::Error(message) => bail!("{message}"),
Answer::Confirm(question) => bail!("devsandbox serve asked, unasked: {question}"),
Answer::Approve(u) => bail!("{}", u.refusal()),
_ if cancelled => Ending::Exit(CANCELLED_EXIT),
Answer::Lost => Ending::Lost,
Answer::Failed(exit) => Ending::Exit(exit),
Answer::Ok(v) if v["detached"] == true => Ending::Detached(v),
Answer::Ok(_) => Ending::Exit(0),
})
}
fn print_detached(verb: &CliVerb, result: &Value, machine: Option<&str>) -> Result<()> {
let instance = result["instance"].as_str();
if let CliVerb::Run { json: true, .. } = verb {
let doc = match (result.get("record"), instance, machine) {
(Some(record), _, _) => serde_json::to_string_pretty(&crate::commands::Envelope::new(record))?,
(None, Some(key), None) => crate::commands::run::run_record_json(key)?,
(None, Some(_), Some(m)) => bail!("{m} sent no run record (its devsandbox is older)"),
(None, None, _) => bail!("no instance created"),
};
println!("{doc}");
} else if let Some(instance) = instance {
match machine {
Some(m) => println!("{m}/{instance}"),
None => println!("{instance}"),
}
}
Ok(())
}
fn lost(verb: &CliVerb, instance: Option<&str>, machine: Option<&str>) -> Result<i32> {
if let Some(m) = machine {
eprintln!(
"the connection to devsandbox serve was lost; `devsandbox {}` may still be running on {m}",
verb.command()
);
return Ok(1);
}
eprintln!("devsandbox serve went away; `devsandbox {}` keeps running in the background", verb.command());
let Some(instance) = instance.filter(|_| verb.builds()) else { return Ok(1) };
if !matches!(verb, CliVerb::Run { json: true, .. })
&& let Err(e) = crate::commands::logs::build_log(instance, true)
{
eprintln!("warning: {e:#}");
}
loop {
let state = crate::state::State::load()?;
if let Some(code) = settled(state.instances.get(instance).map(|i| i.phase_view())) {
return Ok(code);
}
std::thread::sleep(SETTLE_POLL);
}
}
fn settled(view: Option<Option<PhaseView>>) -> Option<i32> {
match view {
Some(None) => Some(0),
Some(Some(PhaseView::InFlight(_))) => None,
Some(Some(PhaseView::Failed { .. })) | None => Some(1),
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use clap::Parser;
use super::*;
use crate::Cli;
use crate::serve::proto::ErrorBody;
fn verb(args: &[&str]) -> Option<CliVerb> {
let cli = Cli::try_parse_from(std::iter::once("devsandbox").chain(args.iter().copied()))
.unwrap_or_else(|e| panic!("{e}"));
from_command(&cli.command.unwrap(), None)
}
#[test]
fn verbs_from_the_parsed_cli() {
assert_eq!(
verb(&["run", "web", "--name", "w2", "--branch", "b", "--base", "origin/x", "--profile", "work", "--json", "--reprobe", "-d"]),
Some(CliVerb::Run {
sandbox: Some("web".into()),
name: Some("w2".into()),
branch: Some("b".into()),
base: Some("origin/x".into()),
profile: Some("work".into()),
json: true,
reprobe: true,
detach: true,
place: false,
})
);
assert_eq!(
verb(&["run"]),
Some(CliVerb::Run { sandbox: None, name: None, branch: None, base: None, profile: None, json: false, reprobe: false, detach: false, place: false })
);
assert!(matches!(verb(&["run", "web", "--place"]), Some(CliVerb::Run { place: true, .. })));
assert_eq!(verb(&["rebuild", "w", "--force"]), Some(CliVerb::Rebuild { target: Some("w".into()), force: true, reprobe: false, detach: false }));
assert_eq!(verb(&["recreate", "--all", "--detach"]), Some(CliVerb::Rebuild { target: None, force: false, reprobe: false, detach: true }));
assert_eq!(verb(&["rebuild", "w", "--reprobe"]), Some(CliVerb::Rebuild { target: Some("w".into()), force: false, reprobe: true, detach: false }));
assert_eq!(verb(&["start", "-d", "w"]), Some(CliVerb::Start { target: Some("w".into()), detach: true }));
assert_eq!(verb(&["stop", "--all"]), Some(CliVerb::Stop { target: None }));
assert_eq!(verb(&["rm", "w"]), Some(CliVerb::Rm { name: "w".into(), delete_branch: None, force: false }));
assert_eq!(
verb(&["rm", "-f", "--keep-branch", "w"]),
Some(CliVerb::Rm { name: "w".into(), delete_branch: Some(false), force: true })
);
assert_eq!(verb(&["service", "rebuild", "db"]), Some(CliVerb::ServicesRebuild { name: "db".into() }));
assert!(Cli::try_parse_from(["devsandbox", "service", "rebuild", "-d", "db"]).is_err());
assert!(Cli::try_parse_from(["devsandbox", "stop", "-d", "w"]).is_err());
assert!(Cli::try_parse_from(["devsandbox", "rm", "-d", "w"]).is_err());
}
#[test]
fn in_process_verbs() {
assert_eq!(verb(&["run", "web", "--env", "A=1"]), None);
assert_eq!(verb(&["run", "web", "--dispatcher", "id"]), None);
assert_eq!(verb(&["rm", "--fail-on-ask", "w"]), None);
assert_eq!(verb(&["ps"]), None);
assert_eq!(verb(&["logs", "w"]), None);
assert_eq!(verb(&["service", "ls"]), None);
assert_eq!(verb(&["gc"]), None);
let gc = Cli::try_parse_from(["devsandbox", "--machine", "lap", "gc", "--force"]).unwrap();
assert_eq!(from_command(&gc.command.unwrap(), gc.machine.as_deref()), Some(CliVerb::Gc { force: true }));
let cli = Cli::try_parse_from(["devsandbox", "--in-process", "stop", "w"]).unwrap();
assert!(cli.in_process);
}
#[test]
fn caller_env_skips_non_utf8() {
use std::os::unix::ffi::OsStringExt;
let bad = OsString::from_vec(vec![0xff]);
let env = caller_env([
("PATH".into(), "/bin".into()),
(bad.clone(), "x".into()),
("HOME".into(), bad),
]);
assert_eq!(env, BTreeMap::from([("PATH".to_string(), "/bin".to_string())]));
}
fn ok(v: Value) -> Response {
Response::ok(Some(1), v)
}
fn err(code: &str, message: &str, data: Option<Value>) -> Response {
Response { id: Some(1), result: None, error: Some(ErrorBody { code: code.into(), message: message.into(), data }) }
}
#[test]
fn answers_map_to_exit_codes() {
let end = |r: Response, cancelled| ending(Answer::of(Streamed::Answer(r)), cancelled);
assert_eq!(end(ok(json!({"instance": "w", "exit": 0})), false).unwrap(), Ending::Exit(0));
let detached = json!({"instance": "w", "detached": true});
assert_eq!(end(ok(detached.clone()), false).unwrap(), Ending::Detached(detached));
let failed = err("failed", "boom", Some(json!({"exit": 7, "instance": "w"})));
assert_eq!(end(failed, false).unwrap(), Ending::Exit(7));
assert_eq!(end(err("failed", "boom", None), false).unwrap(), Ending::Exit(1));
let e = end(err("not-found", "no sandbox instance matches `x`", None), false).unwrap_err();
assert_eq!(e.to_string(), "no sandbox instance matches `x`");
assert!(matches!(end(err("unknown-method", "no method `rm`", None), false).unwrap(), Ending::Old(_)));
let failed = err("failed", "cancelled", Some(json!({"exit": 1, "instance": "w"})));
assert_eq!(end(failed, true).unwrap(), Ending::Exit(CANCELLED_EXIT));
assert_eq!(ending(Answer::HungUp, true).unwrap(), Ending::Exit(CANCELLED_EXIT));
assert_eq!(ending(Answer::Lost, false).unwrap(), Ending::Lost);
assert_eq!(ending(Answer::Lost, true).unwrap(), Ending::Exit(CANCELLED_EXIT));
}
#[test]
fn rm_asks_once_on_confirm_and_resends_with_the_answer() {
let sent = RefCell::new(Vec::new());
let mut send = |p: Value| {
sent.borrow_mut().push(p.clone());
Ok(if p["ask"] == true { Answer::Confirm("Delete branch `b`?".into()) } else { Answer::Ok(json!({"exit": 0})) })
};
let asked = RefCell::new(Vec::new());
let mut confirm = |q: &str| {
asked.borrow_mut().push(q.to_string());
Ok(true)
};
let params = json!({"instance": "w", "ask": true});
assert_eq!(with_answers(params, &mut send, &mut confirm, &mut never_approve).unwrap(), Answer::Ok(json!({"exit": 0})));
assert_eq!(*asked.borrow(), ["Delete branch `b`?"]);
let sent = sent.into_inner();
assert_eq!(sent.len(), 2);
assert_eq!((&sent[1]["deleteBranch"], &sent[1]["ask"]), (&json!(true), &json!(false)));
let mut once = |_: Value| Ok(Answer::Failed(2));
let mut never = |_: &str| -> Result<bool> { panic!("asked") };
assert_eq!(with_answers(json!({}), &mut once, &mut never, &mut never_approve).unwrap(), Answer::Failed(2));
let mut again = |_: Value| Ok(Answer::Confirm("q".into()));
let mut no = |_: &str| Ok(false);
assert!(with_answers(json!({"ask": true}), &mut again, &mut no, &mut never_approve).is_err());
}
fn never_approve(_: &str, _: &str) -> Result<bool> {
panic!("asked to approve")
}
fn unapproved(credential: &str) -> Answer {
Answer::Approve(Unapproved {
credential: credential.into(),
version: "0123456789ab".into(),
message: format!("credential `{credential}` hasn't approved this version of feature `f`'s `sentry` claim (0123456789ab)"),
})
}
#[test]
fn run_asks_per_credential_on_approve_and_resends() {
let sent = RefCell::new(0);
let mut send = |p: Value| {
assert_eq!(p, json!({"sandbox": "web", "ask": true}));
*sent.borrow_mut() += 1;
Ok(match *sent.borrow() {
1 => unapproved("a"),
2 => unapproved("b"),
_ => Answer::Ok(json!({"exit": 0})),
})
};
let asked = RefCell::new(Vec::new());
let mut approve = |c: &str, v: &str| {
asked.borrow_mut().push((c.to_string(), v.to_string()));
Ok(true)
};
let mut never = |_: &str| -> Result<bool> { panic!("confirm") };
let params = json!({"sandbox": "web", "ask": true});
assert_eq!(with_answers(params.clone(), &mut send, &mut never, &mut approve).unwrap(), Answer::Ok(json!({"exit": 0})));
assert_eq!(*asked.borrow(), [("a".into(), "0123456789ab".into()), ("b".into(), "0123456789ab".to_string())]);
assert_eq!(sent.into_inner(), 3);
let mut once = |_: Value| Ok(unapproved("a"));
let mut no = |_: &str, _: &str| Ok(false);
let err = with_answers(params.clone(), &mut once, &mut never, &mut no).unwrap_err().to_string();
assert!(err.ends_with("(0123456789ab): run `devsandbox access approve a`, then try again"), "{err}");
let mut yes = |_: &str, _: &str| Ok(true);
let err = with_answers(params, &mut once, &mut never, &mut yes).unwrap_err().to_string();
assert!(err.starts_with("devsandbox serve asked again"), "{err}");
}
#[test]
fn approve_answers_carry_the_credential_or_read_as_errors() {
let r = |data: Value| Response::err_with(None, "approve", "m", Some(data));
let got = Answer::of(Streamed::Answer(r(json!({"credential": "c", "version": "v"}))));
assert_eq!(got, Answer::Approve(Unapproved { credential: "c".into(), version: "v".into(), message: "m".into() }));
assert_eq!(Answer::of(Streamed::Answer(r(json!({})))), Answer::Error("m".into()));
}
fn prep(verb: &CliVerb, tty: bool, answers: &[(&str, Response)], pick: usize) -> (Result<Prep>, Vec<String>, bool) {
prep_on(verb, tty, Some(TERM), answers, pick)
}
const TERM: TtySize = TtySize { cols: 100, rows: 30 };
fn prep_on(
verb: &CliVerb,
tty: bool,
term: Option<TtySize>,
answers: &[(&str, Response)],
pick: usize,
) -> (Result<Prep>, Vec<String>, bool) {
let (out, calls, offered, _) = prep_fed(verb, &Fed::default(), tty, term, answers, pick);
(out, calls, offered)
}
fn prep_fed(
verb: &CliVerb,
fed: &Fed,
tty: bool,
term: Option<TtySize>,
answers: &[(&str, Response)],
pick: usize,
) -> (Result<Prep>, Vec<String>, bool, Vec<Vec<String>>) {
let out = prep_all(verb, fed, tty, term, answers, pick, None);
(out.prep, out.calls, out.offered, out.picks)
}
struct Out {
prep: Result<Prep>,
calls: Vec<String>,
offered: bool,
picks: Vec<Vec<String>>,
said: Vec<String>,
}
fn prep_all(
verb: &CliVerb,
fed: &Fed,
tty: bool,
term: Option<TtySize>,
answers: &[(&str, Response)],
pick: usize,
reply: Option<&str>,
) -> Out {
let calls = RefCell::new(Vec::new());
let picks = RefCell::new(Vec::new());
let said = RefCell::new(Vec::new());
let mut call = |method: &str, params: Value| {
if method == "config.findings" && !answers.iter().any(|(m, _)| m.split(' ').next() == Some(method)) {
return Ok(ok(json!({"file": "/cfg/devsandboxes.toml", "format": "toml", "fileHash": "h", "findings": []})));
}
calls.borrow_mut().push(format!("{method} {params}"));
let fits = |key: &str| match key.split_once(' ') {
Some((m, text)) => m == method && params.to_string().contains(text),
None => key == method,
};
let r = answers.iter().find(|(m, _)| fits(m)).map(|(_, r)| r).unwrap_or_else(|| panic!("unexpected {method} {params}"));
Ok(Response { id: r.id, result: r.result.clone(), error: r.error.clone() })
};
let offered = RefCell::new(false);
let mut ui = Ui {
tty,
term,
runs_here: true,
pick: &mut |_, options| {
assert!(options.len() > 1);
picks.borrow_mut().push(options.to_vec());
Ok(pick)
},
offer_example: &mut || {
*offered.borrow_mut() = true;
Ok(())
},
ask: &mut |question, choices, default| {
said.borrow_mut().push(format!("? {question}"));
let reply = reply.unwrap_or_else(|| panic!("asked: {question}")).trim().to_ascii_lowercase();
let at = match reply.chars().next() {
None => default,
Some(c) => choices.iter().position(|ch| ch.key == Some(c)).unwrap_or_else(|| panic!("no choice `{c}`")),
};
Ok(crate::ask::Answer::Picked(at))
},
say: &mut |text| said.borrow_mut().push(text.to_string()),
style: crate::ask::Style::plain(),
};
let env = BTreeMap::from([("A".to_string(), "1".to_string())]);
let prep = prepare(verb, Path::new("/cfg"), env, fed, &mut call, &mut ui);
Out { prep, calls: calls.into_inner(), offered: offered.into_inner(), picks: picks.into_inner(), said: said.into_inner() }
}
fn sent(p: Result<Prep>) -> Prepared {
match p.unwrap() {
Prep::Send(p) => p,
other => panic!("{other:?}"),
}
}
#[test]
fn names_resolve_and_pick_before_sending() {
let stop = CliVerb::Stop { target: Some("web".into()) };
let one = [("instances.resolve", ok(json!({"matches": ["web-2"]})))];
let (p, calls, _) = prep(&stop, false, &one, 0);
let p = sent(p);
assert_eq!(calls, [r#"instances.resolve {"name":"web"}"#]);
assert_eq!((p.method, p.instance.as_deref()), ("stop", Some("web-2")));
assert_eq!(p.params, json!({"root": "/cfg", "env": {"A": "1"}, "instance": "web-2", "all": false, "detach": false}));
let two = [("instances.resolve", ok(json!({"matches": ["web", "web-2"]})))];
let e = prep(&stop, false, &two, 0).0.unwrap_err();
assert_eq!(e.to_string(), "`web` is ambiguous: web, web-2");
assert_eq!(sent(prep(&stop, true, &two, 1).0).instance.as_deref(), Some("web-2"));
let none = [("instances.resolve", err("not-found", "no sandbox instance matches `web` (see `devsandbox ps -a`)", None))];
let e = prep(&stop, true, &none, 0).0.unwrap_err();
assert_eq!(e.to_string(), crate::commands::no_instance_matches("web"));
let old = [("instances.resolve", err("unknown-method", "unknown method", None))];
assert!(matches!(prep(&stop, true, &old, 0).0.unwrap(), Prep::Old(_)));
let (p, calls, _) = prep(&CliVerb::Rebuild { target: None, force: true, reprobe: false, detach: true }, true, &[], 0);
assert!(calls.is_empty());
let p = sent(p);
assert_eq!(p.instance, None);
assert_eq!((&p.params["all"], &p.params["force"], &p.params["detach"]), (&json!(true), &json!(true), &json!(true)));
}
#[test]
fn service_rebuild_sends_the_name_unresolved() {
let (p, calls, _) = prep(&CliVerb::ServicesRebuild { name: "db".into() }, true, &[], 0);
assert!(calls.is_empty(), "no prompt, no resolve");
let p = sent(p);
assert_eq!((p.method, p.instance), ("services.rebuild", None));
assert_eq!(p.params, json!({"root": "/cfg", "env": {"A": "1"}, "name": "db", "detach": false}));
}
#[test]
fn rm_asks_only_on_a_tty_without_a_branch_flag() {
let one = [("instances.resolve", ok(json!({"matches": ["w"]})))];
let rm = |delete_branch| CliVerb::Rm { name: "w".into(), delete_branch, force: false };
let params = |verb, tty| sent(prep(&verb, tty, &one, 0).0).params;
assert_eq!(params(rm(None), true)["ask"], true);
assert_eq!(params(rm(None), false)["ask"], false);
assert_eq!(params(rm(None), false).get("deleteBranch"), Some(&Value::Null));
let keep = params(rm(Some(false)), true);
assert_eq!((&keep["ask"], &keep["deleteBranch"]), (&json!(false), &json!(false)));
}
#[test]
fn run_lists_sandboxes_picks_and_offers_the_example() {
let run = |sandbox: Option<&str>, json| CliVerb::Run {
sandbox: sandbox.map(str::to_string),
name: None,
branch: None,
base: None,
profile: None,
json,
reprobe: false,
detach: false,
place: false,
};
let two = [("sandboxes.list", ok(json!([{"name": "api"}, {"name": "web"}])))];
let p = sent(prep(&run(None, false), true, &two, 1).0);
assert_eq!((p.method, &p.params["sandbox"]), ("run", &json!("web")));
let e = prep(&run(None, false), false, &two, 0).0.unwrap_err();
assert_eq!(e.to_string(), "no sandbox specified; available: api, web");
assert_eq!(sent(prep(&run(Some("api"), false), false, &two, 0).0).params["sandbox"], "api");
let empty = [("sandboxes.list", ok(json!([])))];
let (p, _, offered) = prep(&run(Some("web"), false), true, &empty, 0);
assert!(offered);
assert!(matches!(p.unwrap(), Prep::Exit(0)));
let (p, _, offered) = prep(&run(None, true), true, &empty, 0);
assert!(offered);
assert_eq!(p.unwrap_err().to_string(), "no instance created");
let bad = [("sandboxes.list", err("invalid", "bad config: x", None))];
assert_eq!(prep(&run(None, false), true, &bad, 0).0.unwrap_err().to_string(), "bad config: x");
}
#[test]
fn build_verbs_send_the_terminal_size() {
let run = |json| CliVerb::Run { sandbox: Some("web".into()), name: None, branch: None, base: None, profile: None, json, reprobe: false, detach: false, place: false };
let rebuild = CliVerb::Rebuild { target: None, force: false, reprobe: false, detach: false };
let start = CliVerb::Start { target: None, detach: true };
let list = [("sandboxes.list", ok(json!([{"name": "web"}])))];
let size = json!({"cols": 100, "rows": 30});
for (verb, tty) in [(run(false), &size), (run(true), &Value::Null), (rebuild.clone(), &size), (start.clone(), &size)] {
let p = sent(prep(&verb, true, &list, 0).0);
assert_eq!(&p.params["tty"], tty, "{verb:?}");
let p = sent(prep_on(&verb, true, None, &list, 0).0);
assert_eq!(p.params["tty"], Value::Null, "{verb:?} off a terminal");
}
}
#[test]
fn progress_names_a_runs_instance_once() {
let note = |instance: &str| Notification {
method: "progress".into(),
params: json!({"request": 1, "instance": instance, "phase": "building"}),
};
let mut s = Streaming::new(None, true, None);
s.observe(¬e("web-2"));
s.observe(¬e("other"));
assert_eq!(s.instance.as_deref(), Some("web-2"));
let mut s = Streaming::new(None, false, None);
s.observe(¬e("web-2"));
assert_eq!(s.instance, None);
}
#[test]
fn detach_holds_output_back() {
let out = |stream: &str, data: &str| Notification {
method: "output".into(),
params: json!({"request": 1, "stream": stream, "data": data}),
};
let mut s = Streaming::new(None, true, Some(Vec::new()));
s.observe(&out("stdout", "3c66ab93\n"));
s.observe(&out("stderr", "Preparing worktree\n"));
assert_eq!(
s.held.as_deref(),
Some(&[(true, "3c66ab93\n".to_string()), (false, "Preparing worktree\n".to_string())][..])
);
}
#[test]
fn detach_prints_held_notes() {
let held = |v: &[(bool, &str)]| v.iter().map(|(o, d)| (*o, d.to_string())).collect::<Vec<_>>();
let h = held(&[
(false, "note: signed config `cfg` v3\n"),
(true, "note: not this\n"),
(false, "Preparing worktree\nnote: not placed on b"),
(false, ": full; running here\n"),
]);
assert_eq!(held_notes(&h), ["note: signed config `cfg` v3", "note: not placed on b: full; running here"]);
assert_eq!(held_notes(&[]), Vec::<String>::new());
}
#[test]
fn a_lost_verb_settles_by_phase() {
assert_eq!(settled(Some(None)), Some(0));
assert_eq!(settled(Some(Some(PhaseView::InFlight("building".into())))), None);
assert_eq!(settled(Some(Some(PhaseView::Failed { at: "building".into(), error: "x".into() }))), Some(1));
assert_eq!(settled(None), Some(1));
}
const FED: Fed = Fed { machines: true, machine: None };
fn on(m: &str) -> Fed {
Fed { machines: true, machine: Some(m.into()) }
}
fn run_of(sandbox: Option<&str>) -> CliVerb {
CliVerb::Run { sandbox: sandbox.map(str::to_string), name: None, branch: None, base: None, profile: None, json: false, reprobe: false, detach: false, place: false }
}
fn row(name: &str, machine: Option<&str>, root: &str) -> SandboxEntry {
SandboxEntry { name: name.into(), machine: machine.map(Into::into), root: Some(root.into()) }
}
#[test]
fn run_chooses_where_the_sandbox_is() {
let rows = || vec![row("api", None, "/cfg"), row("web", None, "/cfg"), row("web", Some("a"), "/r"), row("db", Some("a"), "/r")];
let pick = |w: Where, n: &str| choose_sandbox(rows(), Some((w, n.into())), true);
assert_eq!(pick(Where::Any, "api"), SandboxChoice::Here { sandbox: "api".into(), matched: true });
assert_eq!(pick(Where::Any, "db"), SandboxChoice::There(row("db", Some("a"), "/r")));
assert_eq!(pick(Where::Machine("a".into()), "web"), SandboxChoice::There(row("web", Some("a"), "/r")));
assert_eq!(pick(Where::Local, "web"), SandboxChoice::Here { sandbox: "web".into(), matched: true });
let SandboxChoice::Pick { prompt, error, options } = pick(Where::Any, "web") else { panic!() };
assert_eq!(prompt, "`web` is defined on several machines");
assert_eq!(error, "`web` is defined on several machines: @/web, a/web; qualify it");
assert_eq!(options.iter().map(|o| o.0.as_str()).collect::<Vec<_>>(), ["@/web", "a/web"]);
assert_eq!(pick(Where::Any, "zzz"), SandboxChoice::Here { sandbox: "zzz".into(), matched: false });
assert_eq!(pick(Where::Local, "db"), SandboxChoice::Here { sandbox: "db".into(), matched: false });
assert_eq!(pick(Where::Machine("a".into()), "api"), SandboxChoice::Missing { machine: "a".into(), sandbox: "api".into() });
let SandboxChoice::Pick { error, .. } = choose_sandbox(rows(), None, true) else { panic!() };
assert_eq!(error, "no sandbox specified; available: api, web, a/web, a/db");
let two = vec![row("web", Some("a"), "/r1"), row("web", Some("a"), "/r2")];
let SandboxChoice::Pick { prompt, error, options } = choose_sandbox(two, Some((Where::Machine("a".into()), "web".into())), true) else { panic!() };
assert_eq!(options.iter().map(|o| o.0.as_str()).collect::<Vec<_>>(), ["a/web (/r1)", "a/web (/r2)"]);
assert_eq!(prompt, "`web` is defined in several roots of `a`");
assert_eq!(error, "`web` is defined in several roots of `a`: a/web (/r1), a/web (/r2)");
let remote_only = || vec![row("web", Some("a"), "/r")];
assert_eq!(choose_sandbox(remote_only(), Some((Where::Any, "web".into())), true), SandboxChoice::There(row("web", Some("a"), "/r")));
assert_eq!(choose_sandbox(remote_only(), Some((Where::Any, "x".into())), true), SandboxChoice::Example { unmatched: Some("x".into()) });
assert_eq!(choose_sandbox(vec![], None, true), SandboxChoice::Example { unmatched: None });
}
#[test]
fn a_driver_offers_the_machines_sandboxes() {
let rows = || vec![row("api", None, "/cfg"), row("web", None, "/cfg"), row("web", Some("a"), "/r"), row("db", Some("a"), "/r")];
let pick = |w: Where, n: &str| choose_sandbox(rows(), Some((w, n.into())), false);
assert_eq!(pick(Where::Any, "web"), SandboxChoice::There(row("web", Some("a"), "/r")), "not ambiguous");
assert_eq!(pick(Where::Any, "api"), SandboxChoice::Here { sandbox: "api".into(), matched: true });
assert_eq!(pick(Where::Local, "web"), SandboxChoice::Here { sandbox: "web".into(), matched: true });
assert_eq!(pick(Where::Any, "zzz"), SandboxChoice::Here { sandbox: "zzz".into(), matched: false });
let SandboxChoice::Pick { error, .. } = choose_sandbox(rows(), None, false) else { panic!() };
assert_eq!(error, "no sandbox specified; available: a/web, a/db");
let local_only = vec![row("api", None, "/cfg")];
let SandboxChoice::Pick { error, .. } = choose_sandbox(local_only, None, false) else { panic!() };
assert_eq!(error, "no sandbox specified; available: api");
}
#[test]
fn run_on_a_machine_sends_its_root_and_machine() {
let list = [("sandboxes.list", ok(json!([{"name": "loc", "root": "/cfg"}, {"name": "web", "machine": "a", "root": "/r"}])))];
let (p, calls, _, _) = prep_fed(&run_of(Some("web")), &FED, false, None, &list, 0);
assert_eq!(calls, [r#"sandboxes.list {"machines":true,"root":"/cfg"}"#]);
let p = sent(p);
assert_eq!((p.method, p.machine.as_deref(), p.instance.as_deref()), ("run", Some("a"), None));
assert_eq!((&p.params["root"], &p.params["sandbox"], &p.params["machine"]), (&json!("/r"), &json!("web"), &json!("a")));
let p = sent(prep_fed(&run_of(Some("@/loc")), &FED, false, None, &list, 0).0);
assert_eq!((p.params.get("machine"), &p.params["root"], p.machine), (None, &json!("/cfg"), None));
let (p, _, _, picks) = prep_fed(&run_of(None), &FED, true, None, &list, 1);
assert_eq!(picks, [vec!["loc".to_string(), "a/web".to_string()]]);
assert_eq!(sent(p).params["machine"], "a");
let down = [
("sandboxes.list", ok(json!([{"name": "loc", "root": "/cfg"}]))),
("machines.list", ok(json!([{"name": "a", "state": "unreachable", "error": "ssh: no route"}, {"name": "b", "state": "connected"}]))),
];
let e = prep_fed(&run_of(Some("a/loc")), &FED, false, None, &down, 0).0.unwrap_err();
assert_eq!(e.to_string(), "no sandbox `loc` on machine `a`; unreachable: a (ssh: no route)");
let (_, calls, _, _) = prep_fed(&run_of(Some("loc")), &Fed::default(), false, None, &list, 0);
assert_eq!(calls, [r#"sandboxes.list {"root":"/cfg"}"#]);
}
#[test]
fn run_place_starts_from_this_host() {
let here = |sandbox: Option<&str>| CliVerb::Run {
sandbox: sandbox.map(str::to_string),
name: None,
branch: None,
base: None,
profile: None,
json: false,
reprobe: false,
detach: false,
place: true,
};
let list = [("sandboxes.list", ok(json!([{"name": "web", "root": "/cfg"}, {"name": "web", "machine": "a", "root": "/r"}, {"name": "db", "machine": "a", "root": "/r"}])))];
let p = sent(prep_fed(&here(Some("web")), &FED, false, None, &list, 0).0);
assert_eq!((p.params.get("machine"), &p.params["root"], &p.params["place"], p.machine), (None, &json!("/cfg"), &json!(true), None));
let p = sent(prep_fed(&here(Some("db")), &FED, false, None, &list, 0).0);
assert_eq!((p.params.get("machine"), &p.params["sandbox"]), (None, &json!("db")));
let two = [("sandboxes.list", ok(json!([{"name": "api", "root": "/cfg"}, {"name": "web", "root": "/cfg"}, {"name": "db", "machine": "a", "root": "/r"}])))];
let (p, _, _, picks) = prep_fed(&here(None), &FED, true, None, &two, 1);
assert_eq!(picks, [vec!["api".to_string(), "web".to_string()]]);
assert_eq!(sent(p).params["sandbox"], "web");
let e = prep_fed(&here(Some("a/web")), &FED, false, None, &list, 0).0.unwrap_err();
assert_eq!(e.to_string(), "--place asks the control plane where to run this host's sandbox; `a/web` is on machine `a`");
assert_eq!(sent(prep_fed(&run_of(Some("@/web")), &FED, false, None, &list, 0).0).params["place"], false);
}
#[test]
fn a_placed_runs_progress_names_its_worker() {
let note = json!({"request": 1, "instance": "web-2", "phase": "building", "machine": "lap"});
let mut s = Streaming::new(None, true, None);
s.qualify_placed = true;
s.observe(&Notification { method: "progress".into(), params: note.clone() });
assert_eq!((s.instance.as_deref(), s.placed.as_deref(), s.qualify.as_deref()), (Some("web-2"), Some("lap"), Some("lap")));
assert_eq!(s.qualified("web-2\n".into()), "lap/web-2\n");
let mut s = Streaming::new(None, true, None);
s.observe(&Notification { method: "progress".into(), params: note });
assert_eq!((s.placed.as_deref(), s.qualify), (Some("lap"), None));
}
#[test]
fn instance_verbs_resolve_across_machines() {
let stop = |name: &str| CliVerb::Stop { target: Some(name.into()) };
let both = [(
"instances.resolve",
ok(json!({"matches": ["a/web-2", "web-1"], "found": [
{"name": "web-2", "machine": "a", "root": "/r"}, {"name": "web-1", "machine": null, "root": "/cfg"}]})),
)];
let e = prep_fed(&stop("web"), &FED, false, None, &both, 0).0.unwrap_err();
assert_eq!(e.to_string(), "`web` is ambiguous: a/web-2, @/web-1");
let (p, calls, _, picks) = prep_fed(&stop("web"), &FED, true, None, &both, 0);
assert_eq!(calls, [r#"instances.resolve {"machines":true,"name":"web"}"#]);
assert_eq!(picks, [vec!["a/web-2".to_string(), "@/web-1".to_string()]]);
let p = sent(p);
assert_eq!((p.instance.as_deref(), p.machine.as_deref()), (Some("web-2"), Some("a")));
assert_eq!(p.params, json!({"root": "/r", "env": {"A": "1"}, "instance": "web-2", "all": false, "detach": false, "machine": "a"}));
let p = sent(prep_fed(&stop("web"), &FED, true, None, &both, 1).0);
assert_eq!(p.params, json!({"root": "/cfg", "env": {"A": "1"}, "instance": "web-1", "all": false, "detach": false}));
let resolved = || ("instances.resolve", ok(json!({"matches": ["w"], "found": [{"name": "w", "machine": null, "root": null}]})));
let info = |default: Value| {
let info = json!({"name": "a", "kind": "ssh", "target": "me@a", "command": null, "roots": ["/r1", "/r2"], "default_root": default, "listed": true, "agent": false});
("machines.get", ok(info))
};
let rm = CliVerb::Rm { name: "a/w".into(), delete_branch: None, force: true };
let (p, calls, _, _) = prep_fed(&rm, &FED, false, None, &[resolved(), info(json!("/r2"))], 0);
assert_eq!(calls, [r#"instances.resolve {"machine":"a","name":"w"}"#, r#"machines.get {"name":"a"}"#]);
let p = sent(p);
assert_eq!((&p.params["root"], &p.params["machine"], &p.params["instance"]), (&json!("/r2"), &json!("a"), &json!("w")));
let e = prep_fed(&rm, &FED, false, None, &[resolved(), info(Value::Null)], 0).0.unwrap_err();
assert_eq!(e.to_string(), "machine `a` has 2 config roots and none is its default: a:/r1, a:/r2");
let here = [("instances.resolve", ok(json!({"matches": ["w"], "found": [{"name": "w", "machine": null, "root": "/x"}]})))];
let (p, calls, _, _) = prep_fed(&stop("@/w"), &FED, false, None, &here, 0);
assert_eq!(calls, [r#"instances.resolve {"name":"w"}"#]);
assert_eq!(sent(p).params["root"], "/cfg");
}
#[test]
fn all_verbs_with_a_machine_go_by_its_roots() {
let machine = || ("machines.get", ok(json!({"name": "a", "kind": "ssh", "target": "a", "command": null, "roots": ["/r1", "/r2"], "agent": false})));
let get = [machine()];
for verb in [CliVerb::Stop { target: None }, CliVerb::Start { target: None, detach: false }] {
let p = sent(prep_fed(&verb, &on("a"), false, None, &get, 0).0);
assert_eq!((&p.params["root"], &p.params["machine"], &p.params["all"]), (&json!("/r1"), &json!("a"), &json!(true)));
assert_eq!((p.machine.as_deref(), p.banner), (Some("a"), None));
}
let Prep::Each(each) = prep_fed(&CliVerb::Rebuild { target: None, force: false, reprobe: false, detach: false }, &on("a"), false, None, &get, 0).0.unwrap()
else {
panic!()
};
let roots: Vec<_> = each.iter().map(|p| (p.params["root"].clone(), p.banner.clone().unwrap())).collect();
assert_eq!(roots, [(json!("/r1"), "==> a:/r1".to_string()), (json!("/r2"), "==> a:/r2".to_string())]);
assert!(each.iter().all(|p| p.params["machine"] == "a"));
let svc = [
machine(),
("services.get /r1", err("not-found", "no service `db` in /r1", None)),
("services.get /r2", ok(json!({"original": "image = \"x\""}))),
];
let Prep::Each(each) = prep_fed(&CliVerb::ServicesRebuild { name: "db".into() }, &on("a"), false, None, &svc, 0).0.unwrap() else {
panic!()
};
assert_eq!(each.len(), 1);
assert_eq!(each[0].params, json!({"root": "/r2", "env": {"A": "1"}, "name": "db", "detach": false, "machine": "a"}));
let none = [machine(), ("services.get", err("not-found", "no service", None))];
let e = prep_fed(&CliVerb::ServicesRebuild { name: "db".into() }, &on("a"), false, None, &none, 0).0.unwrap_err();
assert_eq!(e.to_string(), "no service `db` on machine `a` (roots: /r1, /r2)");
let row = |name: &str, root: &str| {
json!({"name": name, "sandbox": "web", "container": "c", "status": {"state": "running", "text": "Up"}, "uptime_secs": 0,
"cpu": null, "mem": null, "folder": "", "worktree": false, "services": [], "workspace": "",
"remote_user": null, "remote_env_len": 0, "base_folder": "", "drift": false, "instance_id": "id",
"done": false, "root": root})
};
let listing = |rows: Vec<Value>, error: Option<&str>| {
ok(json!({"instances": rows, "sandboxes": [], "services": [], "sandbox_count": 0, "runtime_name": "docker",
"runtime_version": null, "error": error}))
};
let gc = [
machine(),
("instances.list /r1", listing(vec![row("x", "/r1/b"), row("y", "/r1/a"), row("z", "/r1/a")], Some("config: no devsandboxes.toml"))),
("instances.list /r2", listing(vec![row("x", "/r1/b"), row("w", "/r2")], None)),
];
let out = prep_fed(&CliVerb::Gc { force: true }, &on("a"), false, None, &gc, 0);
let Prep::Each(each) = out.0.unwrap() else { panic!() };
let roots: Vec<_> = each.iter().map(|p| (p.params["root"].clone(), p.banner.clone().unwrap())).collect();
assert_eq!(
roots,
[(json!("/r1/a"), "==> a:/r1/a".to_string()), (json!("/r1/b"), "==> a:/r1/b".to_string()), (json!("/r2"), "==> a:/r2".to_string())]
);
assert_eq!(each[0].params, json!({"root": "/r1/a", "env": {"A": "1"}, "force": true, "detach": false, "machine": "a"}));
assert!(each.iter().all(|p| p.method == "gc" && p.instance.is_none() && p.machine.as_deref() == Some("a")));
assert!(out.1[1].contains(r#""depth":"disk""#) && out.1[1].contains(r#""machine":"a""#), "{:?}", out.1);
let missing = [("machines.get", err("not-found", "no machine named `z`", None))];
let e = prep_fed(&CliVerb::Stop { target: None }, &on("z"), false, None, &missing, 0).0.unwrap_err();
assert_eq!(e.to_string(), "no machine named `z` (devsandbox machine ls)");
}
#[test]
fn a_machine_verb_has_no_in_process_fallback() {
let stop = |name: &str| CliVerb::Stop { target: Some(name.into()) };
assert!(in_process(&stop("a/w"), &FED, "down".into()).unwrap_err().to_string().contains("needs devsandbox serve: down"));
assert!(in_process(&CliVerb::Stop { target: None }, &on("a"), "down".into()).is_err());
assert_eq!(in_process(&stop("w"), &FED, "down".into()).unwrap(), Done::InProcess("down".into()));
assert_eq!(in_process(&stop("@/w"), &FED, "down".into()).unwrap(), Done::InProcess("down".into()));
}
#[test]
fn a_remote_runs_name_is_printed_qualified() {
let mut s = Streaming::new(None, true, None);
s.qualify = Some("a".into());
s.stdout_lines("first\nweb");
assert_eq!(s.pending.as_deref(), Some("first\n"));
s.stdout_lines("-2\n");
assert_eq!(s.pending.as_deref(), Some("web-2\n"), "the last line waits");
s.instance = Some("web-2".into());
assert_eq!(s.qualified("web-2\n".into()), "a/web-2\n");
assert_eq!(s.qualified("web-2\r\n".into()), "a/web-2\r\n");
assert_eq!(s.qualified("other\n".into()), "other\n");
s.qualify = None;
assert_eq!(s.qualified("web-2\n".into()), "web-2\n");
}
fn finding(id: &str, kind: &str, edit: Option<&str>, sandboxes: &[&str], acked: bool) -> Value {
json!({"id": id, "table": "sandbox.web", "kind": kind, "key": "workspaceFolder", "value": "/root/app",
"edit": edit, "sandboxes": sandboxes, "acked": acked})
}
fn findings_answer(format: &str) -> Response {
ok(json!({"file": "/cfg/devsandboxes.toml", "format": format, "fileHash": "h1", "findings": [
finding("m1", "root-target", Some("sandbox.web: mounts entry \"a\" -> \"b\""), &["web"], false),
finding("u1", "root-user", Some("sandbox.web: remove remoteUser = \"root\""), &["web"], false),
finding("p1", "root-path", None, &["web"], false),
finding("old", "root-target", Some("acked"), &["web"], true),
finding("a1", "root-env", Some("api's"), &["api"], false),
]}))
}
fn run_web(json: bool) -> CliVerb {
CliVerb::Run { sandbox: Some("web".into()), name: None, branch: None, base: None, profile: None, json, reprobe: false, detach: false, place: false }
}
fn list() -> (&'static str, Response) {
("sandboxes.list", ok(json!([{"name": "web"}, {"name": "api"}])))
}
#[test]
fn identity_prompt_lists_un_acked_findings_and_updates() {
let answers = [
list(),
("config.findings", findings_answer("toml")),
("config.migrate", ok(json!({"edits": 2, "drifted": ["web-1", "web-2"]}))),
];
let out = prep_all(&run_web(false), &Fed::default(), true, None, &answers, 0, Some("u\n"));
assert_eq!(sent(out.prep).params["sandbox"], "web", "the verb goes on");
assert_eq!(
out.calls[1..],
[
r#"config.findings {"root":"/cfg"}"#.to_string(),
r#"config.migrate {"fileHash":"h1","ids":["m1","u1"],"root":"/cfg"}"#.to_string(),
]
);
assert_eq!(
out.said,
[
"/cfg/devsandboxes.toml assumes root in the container, which breaks under identity = \"host\":\n \
sandbox.web: mounts entry \"a\" -> \"b\"\n sandbox.web: remove remoteUser = \"root\"\n \
sandbox.web: workspaceFolder = \"/root/app\" is under /root (fix by hand)"
.to_string(),
format!("? {}", identity::QUESTION),
"updated devsandboxes.toml (2 edits); now drifted: web-1, web-2 → devsandbox rebuild <name>".to_string(),
]
);
}
#[test]
fn identity_prompt_continue_acks_and_keeps_the_root_user() {
let answers = [
list(),
("config.findings", findings_answer("toml")),
("config.ack", ok(json!({"acked": ["m1", "old", "p1"]}))),
("config.migrate", ok(json!({"edits": 1, "drifted": []}))),
];
let out = prep_all(&run_web(false), &Fed::default(), true, None, &answers, 0, Some("C"));
assert!(matches!(out.prep.unwrap(), Prep::Send(_)));
assert_eq!(
out.calls[2..],
[
r#"config.ack {"ids":["m1","p1"],"root":"/cfg"}"#.to_string(),
r#"config.migrate {"fileHash":"h1","ids":[],"keep":["u1"],"root":"/cfg"}"#.to_string(),
]
);
assert_eq!(out.said[2..], ["/cfg/devsandboxes.toml: 2 entries kept as is, not asked about again", "updated devsandboxes.toml (1 edit)"]);
let yaml = [list(), ("config.findings", findings_answer("yaml")), ("config.ack", ok(json!({"acked": []})))];
let out = prep_all(&run_web(false), &Fed::default(), true, None, &yaml, 0, Some("c"));
assert_eq!(out.calls[2..], [r#"config.ack {"ids":["m1","u1","p1"],"root":"/cfg"}"#.to_string()]);
}
#[test]
fn identity_prompt_skips_and_stays_quiet_off_a_tty() {
let answers = [list(), ("config.findings", findings_answer("toml"))];
let out = prep_all(&run_web(false), &Fed::default(), true, None, &answers, 0, Some(""));
assert!(matches!(out.prep.unwrap(), Prep::Send(_)));
assert_eq!(out.calls.len(), 2, "findings read, nothing written: {:?}", out.calls);
for (verb, tty) in [(run_web(false), false), (run_web(true), true)] {
let out = prep_all(&verb, &Fed::default(), tty, None, &answers, 0, None);
assert!(matches!(out.prep.unwrap(), Prep::Send(_)));
assert_eq!(out.calls.len(), 1, "{verb:?}: {:?}", out.calls);
}
let api_only = [list(), ("config.findings", ok(json!({"file": "/cfg/x.toml", "format": "toml", "fileHash": "h",
"findings": [finding("a1", "root-env", Some("e"), &["api"], false), finding("w", "root-env", Some("e"), &["web"], true)]})))];
let out = prep_all(&run_web(false), &Fed::default(), true, None, &api_only, 0, None);
assert!(out.said.is_empty());
let old = [list(), ("config.findings", err("unknown-method", "no", None))];
assert!(matches!(prep_all(&run_web(false), &Fed::default(), true, None, &old, 0, None).prep.unwrap(), Prep::Send(_)));
}
#[test]
fn identity_prompt_errors_conflict_stops_others_warn() {
let with = |migrate: Response| {
let answers = [list(), ("config.findings", findings_answer("toml")), ("config.migrate", migrate)];
prep_all(&run_web(false), &Fed::default(), true, None, &answers, 0, Some("u"))
};
let e = with(err("conflict", "changed", None)).prep.unwrap_err();
assert_eq!(e.to_string(), "/cfg/devsandboxes.toml changed while you were asked; nothing written, run the command again");
let out = with(err("unsupported", "YAML configs aren't rewritten; make these edits by hand:\nx", None));
assert!(matches!(out.prep.unwrap(), Prep::Send(_)));
assert_eq!(out.said.last().unwrap(), "/cfg/devsandboxes.toml: YAML configs aren't rewritten; make these edits by hand:\nx");
let out = with(err("internal", "disk full; left devsandboxes.toml.bak", None));
assert!(matches!(out.prep.unwrap(), Prep::Send(_)));
assert_eq!(out.said.last().unwrap(), "warning: could not update /cfg/devsandboxes.toml: disk full; left devsandboxes.toml.bak");
}
#[test]
fn identity_prompt_for_instances_and_all() {
let answers = [
("instances.resolve", ok(json!({"matches": ["web-2"], "found": [{"name": "web-2", "machine": null, "root": "/cfg", "sandbox": "web"}]}))),
("config.findings", findings_answer("toml")),
];
let rebuild = CliVerb::Rebuild { target: Some("web-2".into()), force: false, reprobe: false, detach: false };
let out = prep_all(&rebuild, &Fed::default(), true, None, &answers, 0, Some("s"));
assert_eq!(sent(out.prep).instance.as_deref(), Some("web-2"));
assert!(out.said[0].contains("remove remoteUser"), "{:?}", out.said);
let machine = ("machines.get", ok(json!({"name": "a", "kind": "ssh", "target": "a", "command": null, "roots": ["/r1", "/r2"], "agent": false})));
let answers = [
machine,
("config.findings /r1", findings_answer("toml")),
("config.findings /r2", ok(json!({"file": "/r2/devsandboxes.toml", "format": "toml", "fileHash": "h2",
"findings": [finding("x", "root-env", Some("r2's"), &["db"], false), finding("t", "root-env", Some("unused"), &[], false)]}))),
("config.migrate /r1", ok(json!({"edits": 3, "drifted": ["web-1"]}))),
("config.migrate /r2", ok(json!({"edits": 1, "drifted": []}))),
];
let all = CliVerb::Rebuild { target: None, force: false, reprobe: false, detach: false };
let out = prep_all(&all, &on("a"), true, None, &answers, 0, Some("u"));
assert!(matches!(out.prep.unwrap(), Prep::Each(_)));
let asked: Vec<&String> = out.said.iter().filter(|s| s.starts_with("? ")).collect();
assert_eq!(asked.len(), 1, "one prompt");
assert!(out.said[0].starts_with("a:/cfg/devsandboxes.toml assumes root"), "{}", out.said[0]);
assert!(out.said[0].contains("a:/r2/devsandboxes.toml assumes root"), "{}", out.said[0]);
assert!(!out.said[0].contains("unused"), "an unused template isn't the verb's: {}", out.said[0]);
assert!(out.calls.contains(&r#"config.migrate {"fileHash":"h1","ids":["m1","u1","a1"],"machine":"a","root":"/r1"}"#.to_string()), "{:?}", out.calls);
assert!(out.calls.contains(&r#"config.migrate {"fileHash":"h2","ids":["x"],"machine":"a","root":"/r2"}"#.to_string()), "{:?}", out.calls);
assert!(out.said.contains(&"updated devsandboxes.toml (3 edits); now drifted: a/web-1 → devsandbox rebuild <name>".to_string()));
}
#[test]
fn with_no_daemon_the_asks_come_from_what_is_known() {
let mut call = |method: &str, params: Value| {
assert_eq!(method, "instances.resolve");
Ok(match params["name"].as_str() {
Some("w") => ok(json!({"matches": ["w-1", "w-2", "x"], "found": [
{"name": "w-1", "machine": null, "root": null, "sandbox": "web"},
{"name": "w-2", "machine": null, "root": null, "sandbox": "web"},
{"name": "x", "machine": null, "root": null, "sandbox": "api"}]})),
_ => err("not-found", "no", None),
})
};
let asks = |verb: CliVerb, call: &mut Call| identity::local_asks(&verb, Path::new("/cfg"), &FED, call).unwrap();
let ask = |scope| vec![Ask { root: "/cfg".into(), machine: None, scope }];
let names = |n: &[&str]| Scope::Sandboxes(n.iter().map(|s| s.to_string()).collect());
assert_eq!(asks(run_of(Some("@/web")), &mut call), ask(names(&["web"])));
assert_eq!(asks(run_web(true), &mut call), Vec::<Ask>::new(), "--json");
assert_eq!(asks(run_of(None), &mut call), Vec::<Ask>::new(), "the pick comes later");
assert_eq!(asks(CliVerb::Start { target: Some("w".into()), detach: false }, &mut call), ask(names(&["api", "web"])));
assert_eq!(asks(CliVerb::Rebuild { target: Some("zz".into()), force: false, reprobe: false, detach: false }, &mut call), Vec::<Ask>::new());
assert_eq!(asks(CliVerb::Rebuild { target: None, force: false, reprobe: false, detach: false }, &mut call), ask(Scope::Used));
assert_eq!(asks(CliVerb::Stop { target: Some("w".into()) }, &mut call), Vec::<Ask>::new());
}
#[test]
fn the_local_call_answers_only_the_prompts_methods() {
assert!(identity::local_call("inbox.threads.list", json!({})).is_err());
let r = identity::local_call("config.findings", json!({"root": "rel"})).unwrap();
assert_eq!(r.error.unwrap().code, "invalid");
}
}