Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua): Spaces created on a host use its runtime; clear runtime errors; the daemon stops on SIGTERM (#6013)
ddupont3dea77a7a58b
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex c1eeee2dad..6782428fc7 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -2408,6 +2408,20 @@ async fn daemon_start("the daemon did not start within 10 s".into(),));}+ // One daemon per home: one still winding down (stopped, or an app+ // restarting it) is waited for, never run next to.+ let lock_path = discovery+ .parent()+ .map(|d| d.join("daemon.lock"))+ .unwrap_or_else(cua_daemon::InstanceLock::path);+ let _instance = {+ let path = lock_path.clone();+ let wait = cua_daemon::server::SHUTDOWN_GRACE + Duration::from_secs(5);+ tokio::task::spawn_blocking(move || cua_daemon::InstanceLock::acquire(&path, wait))+ .await+ .map_err(util::internal)?+ .map_err(|held| CuaError::InvalidArgument(held.to_string()))?+ };// A daemon holds a descriptor per Space, client and stream: dozens of// concurrent creates exhausted macOS's default soft limit of 256.if let Some((before, after)) = util::raise_open_file_limit() {@@ -2516,12 +2530,15 @@ async fn daemon_start(.unwrap_or_default(),h.loopback_url.clone().unwrap_or_default());+ // SIGTERM and Ctrl-C stop it cleanly, within a bounded time.let trigger = h.shutdown_trigger();tokio::spawn(async move {- let _ = tokio::signal::ctrl_c().await;+ cua_daemon::server::stop_signal().await;let _ = trigger.send(true);});- h.wait().await;+ if !h.wait_bounded(cua_daemon::server::SHUTDOWN_GRACE).await {+ eprintln!("cua daemon: shutdown took too long; exiting");+ }Ok(0)}diff --git a/libs/cua/crates/cua-cli/tests/daemon_sigterm.rs b/libs/cua/crates/cua-cli/tests/daemon_sigterm.rsnew file mode 100644index 0000000000..47ee9b435a--- /dev/null+++ b/libs/cua/crates/cua-cli/tests/daemon_sigterm.rs@@ -0,0 +1,73 @@+//! `cua daemon start --foreground` stops cleanly on SIGTERM (what `kill`,+//! launchd and an app quitting send), and never runs next to another+//! daemon for the same home: a second one waits for the first to exit,+//! then takes over. Everything runs in a temp home; the only daemons are+//! this test's own.+#![cfg(unix)]++mod common;++use common::Home;+use std::time::Duration;++fn discovery_pid(h: &Home) -> Option<u32> {+ let text = std::fs::read_to_string(h.cua_home().join("daemon.json")).ok()?;+ let v: serde_json::Value = serde_json::from_str(&text).ok()?;+ v["pid"].as_u64().map(|p| p as u32)+}++async fn wait_for_discovery(h: &Home, pid: u32) {+ for _ in 0..300 {+ if discovery_pid(h) == Some(pid) {+ return;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("daemon {pid} did not start");+}++fn sigterm(pid: u32) {+ // SAFETY: kill(2) on this test's own child.+ assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) }, 0);+}++#[tokio::test]+async fn sigterm_stops_the_daemon_and_a_second_one_waits_for_it() {+ let mut h = Home::new();+ h.set("CUA_DAEMON_NO_RELAY", "1");+ let args = ["daemon", "start", "--foreground", "--loopback", "off"];+ let mut first = h.spawn(&args);+ let first_pid = first.id().unwrap();+ wait_for_discovery(&h, first_pid).await;++ // A second daemon for the same home does not start while the first runs.+ let mut second = h.spawn(&args);+ let second_pid = second.id().unwrap();+ tokio::time::sleep(Duration::from_secs(2)).await;+ assert_eq!(+ discovery_pid(&h),+ Some(first_pid),+ "two daemons ran at once"+ );+ assert!(+ second.try_wait().unwrap().is_none(),+ "the second gave up early"+ );++ // SIGTERM: the first exits cleanly and promptly...+ sigterm(first_pid);+ let status = tokio::time::timeout(Duration::from_secs(45), first.wait())+ .await+ .expect("the daemon ignored SIGTERM")+ .unwrap();+ assert!(status.success(), "{status:?}");+ // ...and the second takes over.+ wait_for_discovery(&h, second_pid).await;+ sigterm(second_pid);+ let status = tokio::time::timeout(Duration::from_secs(45), second.wait())+ .await+ .expect("the daemon ignored SIGTERM")+ .unwrap();+ assert!(status.success(), "{status:?}");+ assert_eq!(discovery_pid(&h), None, "the discovery file outlived it");+}diff --git a/libs/cua/crates/cua-daemon/src/lib.rs b/libs/cua/crates/cua-daemon/src/lib.rsindex 6cf0ef4f65..9f22829672 100644--- a/libs/cua/crates/cua-daemon/src/lib.rs+++ b/libs/cua/crates/cua-daemon/src/lib.rs@@ -524,6 +524,98 @@ pub fn default_discovery_path() -> PathBuf {cua_home().join("daemon.json")}+/// One daemon per home: an exclusive lock on `daemon.lock` next to the+/// discovery file, held for the life of the process (the OS drops it when+/// the process ends, however it ends). A daemon started while another still+/// runs for the same home (an app restarting its daemon while the old one+/// winds down) waits for it, then refuses: two daemons would serve the same+/// Spaces, state and Keyvault socket.+#[derive(Debug)]+pub struct InstanceLock {+ _file: Option<std::fs::File>,+}++/// The daemon holding an [`InstanceLock`] (its pid, when it wrote one).+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct InstanceHeld {+ /// The lock file.+ pub path: PathBuf,+ /// The pid written in it.+ pub pid: Option<u32>,+}++impl std::fmt::Display for InstanceHeld {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self.pid {+ Some(pid) => write!(f, "another cua daemon (pid {pid}) runs for this home"),+ None => write!(f, "another cua daemon runs for this home"),+ }?;+ write!(+ f,+ " (it holds {}); stop it with `cua daemon stop` first",+ self.path.display()+ )+ }+}++impl InstanceLock {+ /// The lock of the default home.+ pub fn path() -> PathBuf {+ cua_home().join("daemon.lock")+ }++ /// Takes the lock at `path`, waiting up to `wait` for a daemon that+ /// holds it to exit.+ pub fn acquire(+ path: &std::path::Path,+ wait: std::time::Duration,+ ) -> std::result::Result<Self, InstanceHeld> {+ use std::io::{Seek, Write};+ if let Some(dir) = path.parent() {+ let _ = std::fs::create_dir_all(dir);+ }+ let held = || InstanceHeld {+ path: path.to_path_buf(),+ pid: std::fs::read_to_string(path)+ .ok()+ .and_then(|s| s.trim().parse().ok()),+ };+ let mut file = match std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(path)+ {+ Ok(f) => f,+ // A home it cannot write: no guard rather than no daemon.+ Err(e) => {+ tracing::warn!(path = %path.display(), error = %e, "no single-instance lock");+ return Ok(Self { _file: None });+ }+ };+ let deadline = std::time::Instant::now() + wait;+ loop {+ match file.try_lock() {+ Ok(()) => break,+ Err(std::fs::TryLockError::WouldBlock) if std::time::Instant::now() < deadline => {+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+ Err(std::fs::TryLockError::WouldBlock) => return Err(held()),+ Err(std::fs::TryLockError::Error(e)) => {+ tracing::warn!(path = %path.display(), error = %e, "no single-instance lock");+ return Ok(Self { _file: Some(file) });+ }+ }+ }+ let _ = file.set_len(0);+ let _ = file.rewind();+ let _ = write!(file, "{}", std::process::id());+ let _ = file.flush();+ Ok(Self { _file: Some(file) })+ }+}+/// What every caller shows when no daemon listens: [`Error::DaemonNotRunning`].pub const DAEMON_NOT_RUNNING: &str ="The Cua daemon isn't running. Start Cua, or run `cua daemon start`.";@@ -983,3 +1075,40 @@ mod tests {assert!(a.len() >= 43);}}++#[cfg(test)]+mod instance_lock_tests {+ use super::*;+ use std::time::Duration;++ /// One daemon per home: a second one waits for the first, then+ /// refuses naming its pid; once the first is gone the lock is free.+ #[test]+ fn a_second_daemon_for_the_same_home_is_refused() {+ let d = tempfile::tempdir().unwrap();+ let path = d.path().join("daemon.lock");+ let first = InstanceLock::acquire(&path, Duration::ZERO).unwrap();+ let started = std::time::Instant::now();+ let held = InstanceLock::acquire(&path, Duration::from_millis(300)).unwrap_err();+ assert!(started.elapsed() >= Duration::from_millis(300));+ assert_eq!(held.pid, Some(std::process::id()));+ assert!(held.to_string().contains("cua daemon stop"), "{held}");+ drop(first);+ InstanceLock::acquire(&path, Duration::ZERO).unwrap();+ }++ /// A daemon waiting for the lock gets it when the old one exits within+ /// the wait (an app restarting its daemon).+ #[test]+ fn the_lock_is_taken_once_the_old_daemon_exits() {+ let d = tempfile::tempdir().unwrap();+ let path = d.path().join("daemon.lock");+ let first = InstanceLock::acquire(&path, Duration::ZERO).unwrap();+ let t = std::thread::spawn(move || {+ std::thread::sleep(Duration::from_millis(200));+ drop(first);+ });+ InstanceLock::acquire(&path, Duration::from_secs(5)).unwrap();+ t.join().unwrap();+ }+}diff --git a/libs/cua/crates/cua-daemon/src/server.rs b/libs/cua/crates/cua-daemon/src/server.rsindex 2f3246e752..6f2f64811c 100644--- a/libs/cua/crates/cua-daemon/src/server.rs+++ b/libs/cua/crates/cua-daemon/src/server.rs@@ -331,16 +331,79 @@ impl DaemonHandle {self.cleanup();}- fn cleanup(&self) {- if let Some(p) = &self.socket_path {- let _ = std::fs::remove_file(p);+ /// [`wait`](Self::wait), with the shutdown bounded: once shutdown is+ /// requested, the daemon's own wind-down (extensions, the warm pool, the+ /// built-in Linux runtime) gets `grace`; past it the socket and discovery+ /// file go and this returns `false`, so a stop signal always ends the+ /// process (a supervisor that sees the daemon gone never waits on one+ /// still winding down for minutes).+ pub async fn wait_bounded(self, grace: Duration) -> bool {+ let mut rx = self.shared.shutdown.subscribe();+ while !*rx.borrow() {+ if rx.changed().await.is_err() {+ break;+ }}- if let Some(p) = &self.discovery_path- && Discovery::read(p).is_some_and(|d| d.pid == std::process::id())- {- let _ = std::fs::remove_file(p);+ let socket = self.socket_path.clone();+ let discovery = self.discovery_path.clone();+ if tokio::time::timeout(grace, self.wait()).await.is_ok() {+ return true;+ }+ tracing::warn!(+ ?grace,+ "the daemon's shutdown took too long; exiting without it"+ );+ cleanup_paths(socket.as_deref(), discovery.as_deref());+ false+ }++ fn cleanup(&self) {+ cleanup_paths(self.socket_path.as_deref(), self.discovery_path.as_deref());+ }+}++/// Removes the daemon's socket, and its discovery file while it names this+/// process.+fn cleanup_paths(socket: Option<&std::path::Path>, discovery: Option<&std::path::Path>) {+ if let Some(p) = socket {+ let _ = std::fs::remove_file(p);+ }+ if let Some(p) = discovery+ && Discovery::read(p).is_some_and(|d| d.pid == std::process::id())+ {+ let _ = std::fs::remove_file(p);+ }+}++/// How long a stopped daemon may take to wind down before it exits anyway+/// ([`DaemonHandle::wait_bounded`]).+pub const SHUTDOWN_GRACE: Duration = Duration::from_secs(30);++/// Resolves on the first stop signal: SIGTERM (`kill`, launchd, systemd, an+/// app quitting) or SIGINT (Ctrl-C) on Unix, Ctrl-C elsewhere.+pub async fn stop_signal() {+ #[cfg(unix)]+ {+ use tokio::signal::unix::{SignalKind, signal};+ match (+ signal(SignalKind::terminate()),+ signal(SignalKind::interrupt()),+ ) {+ (Ok(mut term), Ok(mut int)) => {+ tokio::select! {+ _ = term.recv() => tracing::info!("SIGTERM: stopping the daemon"),+ _ = int.recv() => tracing::info!("SIGINT: stopping the daemon"),+ }+ }+ _ => {+ let _ = tokio::signal::ctrl_c().await;+ }}}+ #[cfg(not(unix))]+ {+ let _ = tokio::signal::ctrl_c().await;+ }}impl Drop for DaemonHandle {diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rsindex 40dbca220d..eb24dc2807 100644--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs@@ -1494,6 +1494,18 @@ impl HostSpacesServer {};let kind = Kind::parse(&req.kind).map_err(place)?;let runtime = Runtime::parse(&req.runtime).map_err(place)?;+ // This host's runtime, not the caller's: an explicit one it cannot+ // run is refused naming what it can; `auto` takes its own+ // `default.runtime`.+ let settings = cua_sandbox_core::settings::Settings::load().ok();+ let (mut kind, mut runtime) = host_placement(+ kind,+ runtime,+ macos,+ settings.as_ref(),+ &cua_sandbox_core::placement::HostFacts::current(),+ )+ .map_err(|e| self.refuse(caller, &label, place(e)))?;let provided_now = provided::load_provided(&self.host_dir())?;let slot = self.reserve(&policy, &provided_now, macos, &host_name)@@ -1589,41 +1601,77 @@ impl HostSpacesServer {}),}} else {- self.spaces- .create(SpaceCreate {- progress: following.as_ref().map(Following::sink),- image: Some(image.clone()),- on: Some(On::Local),- kind,- runtime: runtime.clone(),- name: Some(req.name.clone()).filter(|n| !n.trim().is_empty()),- cpus: Some(req.cpus).filter(|c| *c > 0),- memory_mb: Some(req.memory_mb).filter(|m| *m > 0),- disk_gb: Some(req.disk_gb).filter(|d| *d > 0),- wait: Some(true),- // A provided Space joins the relay through its own driver- // (a direct one is reached through the host's forward).- spacesd: Some(true),- // The caller cancels it by the machine it registered.- create_id: (!direct).then(|| attach.machine_id.clone()),- network,- // Its driver's mesh node, so the caller reaches it directly- // when it can (a direct Space has no relay to coordinate one).- env: {- let mut env: std::collections::BTreeMap<String, String> =- req.env.clone().into_iter().collect();- if !direct {- env.extend(crate::mesh::provided_space_env());- }- env- },- gpu: Some(req.gpu.trim().to_string()).filter(|g| !g.is_empty()),- headless: req.headless,- // Enforced by this host, from the guest's first instruction.- egress: egress_from_pb(req.egress.clone()),- ..Default::default()- })- .await+ let create = SpaceCreate {+ progress: following.as_ref().map(Following::sink),+ image: Some(image.clone()),+ on: Some(On::Local),+ kind,+ runtime: runtime.clone(),+ name: Some(req.name.clone()).filter(|n| !n.trim().is_empty()),+ cpus: Some(req.cpus).filter(|c| *c > 0),+ memory_mb: Some(req.memory_mb).filter(|m| *m > 0),+ disk_gb: Some(req.disk_gb).filter(|d| *d > 0),+ wait: Some(true),+ // A provided Space joins the relay through its own driver+ // (a direct one is reached through the host's forward).+ spacesd: Some(true),+ // The caller cancels it by the machine it registered.+ create_id: (!direct).then(|| attach.machine_id.clone()),+ network,+ // Its driver's mesh node, so the caller reaches it directly+ // when it can (a direct Space has no relay to coordinate one).+ env: {+ let mut env: std::collections::BTreeMap<String, String> =+ req.env.clone().into_iter().collect();+ if !direct {+ env.extend(crate::mesh::provided_space_env());+ }+ env+ },+ gpu: Some(req.gpu.trim().to_string()).filter(|g| !g.is_empty()),+ headless: req.headless,+ // Enforced by this host, from the guest's first instruction.+ egress: egress_from_pb(req.egress.clone()),+ ..Default::default()+ };+ match self.spaces.create(create.clone()).await {+ // `auto` on a broken container engine (Docker failing its+ // own writes, a stopped engine): the next working runtime+ // here rather than the engine's error.+ Err(e)+ if let Some(next) = engine_fallback(+ kind,+ &runtime,+ macos,+ &e,+ &cua_sandbox_core::placement::HostFacts::current(),+ ) =>+ {+ tracing::warn!(+ error = %e,+ runtime = %next,+ "the container engine failed; creating the Space on the next runtime"+ );+ (kind, runtime) = (next.builtin_kind().unwrap_or(Kind::Auto), next);+ self.spaces+ .create(SpaceCreate {+ kind,+ runtime: runtime.clone(),+ ..create+ })+ .await+ .map_err(|e2| {+ Error::host(+ "host spaces",+ format!(+ "the container engine on {host_name} failed ({e}), and so did \+ {runtime} ({e2})"+ ),+ )+ })+ }+ r => r,+ }};let info = match created {Ok(c) => match c.ready() {@@ -2630,11 +2678,104 @@ pub(crate) fn from_host(e: cua_spacesd_client::Error) -> Error {Error::host("host spaces", msg)}(Some("not_found"), _) => Error::NotFound(msg),- (Some("invalid_argument"), _) => Error::invalid(msg),+ (Some("invalid_argument" | "invalid_placement"), _) => Error::invalid(msg),_ => Error::Env(e),}}+/// The kind and runtime a Space created on this host runs with, from what+/// the caller asked (`kind`, `runtime`) and this host's own configuration.+///+/// - An explicit built-in runtime must run here ([`placement::select`] on+/// this host's facts); otherwise the refusal names the runtimes it has.+/// - `auto` takes this host's `default.runtime` (`cua config set+/// default.runtime`) when it fits the kind and runs here: the caller's+/// machine knows nothing about which engine works on this one. A macOS+/// guest keeps its own rule (Lume).+///+/// [`placement::select`]: cua_sandbox_core::placement::select+pub(crate) fn host_placement(+ kind: Kind,+ runtime: Runtime,+ macos_guest: bool,+ settings: Option<&cua_sandbox_core::settings::Settings>,+ host: &cua_sandbox_core::placement::HostFacts,+) -> std::result::Result<(Kind, Runtime), cua_sandbox_core::placement::PlacementError> {+ use cua_sandbox_core::placement::{ImageFacts, select};+ let image = ImageFacts {+ os: macos_guest.then(|| "macos".to_string()),+ variants: vec![],+ };+ if runtime != Runtime::Auto {+ if runtime.builtin_kind().is_some() {+ select(&On::Local, kind, &runtime, &image, host).map_err(|mut e| {+ e.message = format!("this host cannot run {runtime}: {}", e.message);+ e+ })?;+ }+ return Ok((kind, runtime));+ }+ if macos_guest {+ return Ok((kind, runtime));+ }+ let Some(resolved) = settings.and_then(|s| {+ s.resolve(Some(On::Local), (kind != Kind::Auto).then_some(kind), None)+ .ok()+ }) else {+ return Ok((kind, runtime));+ };+ if resolved.runtime == Runtime::Auto+ || select(&On::Local, kind, &resolved.runtime, &image, host).is_err()+ {+ return Ok((kind, runtime));+ }+ Ok((kind, resolved.runtime))+}++/// The runtime to try when an `auto` create failed on a broken container+/// engine, or `None` to keep the error: a microVM runtime this host has+/// (cua's own monitor, Apple's Containerization, Firecracker). Only for+/// `auto` (an explicit kind or runtime is kept), never for a macOS guest,+/// and never for an image fault (no such image, a refused pull).+pub(crate) fn engine_fallback(+ kind: Kind,+ runtime: &Runtime,+ macos_guest: bool,+ err: &Error,+ host: &cua_sandbox_core::placement::HostFacts,+) -> Option<Runtime> {+ if kind != Kind::Auto || *runtime != Runtime::Auto || macos_guest || !engine_broken(err) {+ return None;+ }+ Kind::parse("microvm").ok()?;+ [+ (host.vz, Runtime::Vz),+ (host.apple_containers, Runtime::Containerization),+ (host.kvm, Runtime::Firecracker),+ ]+ .into_iter()+ .find_map(|(has, r)| has.then_some(r))+}++/// Whether `err` says the container engine itself failed (an I/O error in+/// its store, a 5xx, a stopped daemon), not the image.+fn engine_broken(err: &Error) -> bool {+ let m = err.to_string().to_ascii_lowercase();+ let engine = m.contains("container engine") || m.contains("docker");+ let image_fault = [+ "manifest unknown",+ "pull access denied",+ "toomanyrequests",+ "unauthorized",+ "no such image",+ "invalid reference",+ "not found: manifest",+ ]+ .iter()+ .any(|f| m.contains(f));+ engine && !image_fault+}+/// A machine that provides Spaces, as [`Spaces::resolve_host`] found it.#[derive(Clone, Debug, PartialEq, Eq)]#[allow(clippy::large_enum_variant)] // resolved once per call, never stored in bulk@@ -4834,3 +4975,170 @@ mod tests {}}}++#[cfg(test)]+mod host_runtime_tests {+ use super::*;+ use cua_sandbox_core::placement::HostFacts;+ use cua_sandbox_core::settings::Settings;++ const MAC_26: HostFacts = HostFacts {+ gvisor: None,+ apple_silicon: true,+ kvm: false,+ apple_containers: true,+ vz: false,+ };+ const MAC_15: HostFacts = HostFacts {+ gvisor: None,+ apple_silicon: true,+ kvm: false,+ apple_containers: false,+ vz: false,+ };++ fn settings(toml: &str) -> (tempfile::TempDir, Settings) {+ let d = tempfile::tempdir().unwrap();+ std::fs::write(d.path().join("config.toml"), toml).unwrap();+ let s = Settings::load_with(d.path().join("config.toml"), |_| None).unwrap();+ (d, s)+ }++ /// A Space created on this host from another device with `auto` runs+ /// on this host's `default.runtime`, not the engine `auto` would pick.+ #[test]+ fn auto_takes_the_hosts_default_runtime() {+ let (_d, s) = settings("[default]\nruntime = \"containerization\"\n");+ let got = host_placement(Kind::Auto, Runtime::Auto, false, Some(&s), &MAC_26).unwrap();+ assert_eq!(got, (Kind::Auto, Runtime::Containerization));+ // Without a default, `auto` stays `auto` (this host picks at start).+ let (_d, none) = settings("");+ let got = host_placement(Kind::Auto, Runtime::Auto, false, Some(&none), &MAC_26).unwrap();+ assert_eq!(got, (Kind::Auto, Runtime::Auto));+ let got = host_placement(Kind::Auto, Runtime::Auto, false, None, &MAC_26).unwrap();+ assert_eq!(got, (Kind::Auto, Runtime::Auto));+ }++ /// The host's default is skipped where it cannot apply: a macOS guest+ /// (Lume), a kind it does not run, a host that cannot run it.+ #[test]+ fn the_hosts_default_is_skipped_where_it_does_not_fit() {+ let (_d, s) = settings("[default]\nruntime = \"containerization\"\n");+ assert_eq!(+ host_placement(Kind::Auto, Runtime::Auto, true, Some(&s), &MAC_26).unwrap(),+ (Kind::Auto, Runtime::Auto)+ );+ assert_eq!(+ host_placement(Kind::Container, Runtime::Auto, false, Some(&s), &MAC_26).unwrap(),+ (Kind::Container, Runtime::Auto)+ );+ assert_eq!(+ host_placement(Kind::Auto, Runtime::Auto, false, Some(&s), &MAC_15).unwrap(),+ (Kind::Auto, Runtime::Auto)+ );+ }++ /// An explicit runtime this host runs is kept; one it cannot run is+ /// refused naming the runtimes it has (never a transport error).+ #[test]+ fn an_explicit_runtime_is_kept_or_refused_with_the_valid_ones() {+ let got = host_placement(Kind::Auto, Runtime::Containerization, false, None, &MAC_26);+ assert_eq!(got.unwrap(), (Kind::Auto, Runtime::Containerization));+ let e = host_placement(Kind::Auto, Runtime::Containerization, false, None, &MAC_15)+ .unwrap_err();+ assert!(+ e.message+ .starts_with("this host cannot run containerization: "),+ "{}",+ e.message+ );+ assert!(e.valid.iter().any(|v| v == "auto"), "{:?}", e.valid);+ assert!(+ !e.valid.iter().any(|v| v == "containerization"),+ "{:?}",+ e.valid+ );+ assert!(e.message.contains("valid runtime: auto"), "{}", e.message);+ // Through the RPC and back it stays a clear invalid-argument error.+ let status = to_status(&Error::Sandbox(cua_sandbox_core::Error::InvalidPlacement(+ e.clone(),+ )));+ assert_eq!(status.code(), tonic::Code::InvalidArgument);+ let back = from_host(cua_spacesd_client::Error::from(status));+ assert!(matches!(back, Error::InvalidArgument(_)), "{back:?}");+ assert!(+ back.to_string()+ .contains("this host cannot run containerization")+ );+ // A third-party runtime is the provider's to check.+ let other = Runtime::Other("acme".into());+ assert_eq!(+ host_placement(Kind::Auto, other.clone(), false, None, &MAC_15).unwrap(),+ (Kind::Auto, other)+ );+ }++ /// `auto` on a broken container engine moves to a microVM runtime this+ /// host has; an image fault, an explicit choice and a macOS guest keep+ /// the error.+ #[test]+ fn a_broken_engine_falls_back_for_auto_only() {+ let broken = Error::Sandbox(cua_sandbox_core::Error::Runtime(+ cua_sandbox_core::RuntimeError::Other(+ "container engine: pull ghcr.io/trycua/linux@sha256:9a: Docker responded with \+ status code 500: write /var/lib/containerd/io.containerd.metadata.v1.bolt/meta.db: \+ input/output error"+ .into(),+ ),+ ));+ let fb = |k, r: &Runtime, mac, e: &Error, h: &HostFacts| engine_fallback(k, r, mac, e, h);+ assert_eq!(+ fb(Kind::Auto, &Runtime::Auto, false, &broken, &MAC_26),+ Some(Runtime::Containerization)+ );+ assert_eq!(+ fb(Kind::Auto, &Runtime::Auto, false, &broken, &MAC_15),+ None+ );+ assert_eq!(+ fb(Kind::Container, &Runtime::Auto, false, &broken, &MAC_26),+ None+ );+ assert_eq!(+ fb(Kind::Auto, &Runtime::Gvisor, false, &broken, &MAC_26),+ None+ );+ assert_eq!(fb(Kind::Auto, &Runtime::Auto, true, &broken, &MAC_26), None);+ let image = Error::Sandbox(cua_sandbox_core::Error::Runtime(+ cua_sandbox_core::RuntimeError::Other(+ "container engine: pull ghcr.io/x/y:1: manifest unknown".into(),+ ),+ ));+ assert_eq!(fb(Kind::Auto, &Runtime::Auto, false, &image, &MAC_26), None);+ let vz = HostFacts { vz: true, ..MAC_26 };+ assert_eq!(+ fb(Kind::Auto, &Runtime::Auto, false, &broken, &vz),+ Some(Runtime::Vz)+ );+ }++ /// Drift guard: a create on this host goes through [`host_placement`]+ /// (its runtime, not the caller's) and keeps [`engine_fallback`].+ #[test]+ fn host_creates_resolve_the_runtime_here() {+ let src = include_str!("host_spaces.rs");+ let body = src+ .split("async fn create_provided(")+ .nth(1)+ .and_then(|b| b.split("\n fn with_egress(").next())+ .expect("create_provided");+ assert!(+ body.contains("host_placement("),+ "create_provided skips host_placement"+ );+ assert!(+ body.contains("engine_fallback("),+ "create_provided skips engine_fallback"+ );+ }+}diff --git a/libs/cua/crates/cua-spacesd-client/src/transport.rs b/libs/cua/crates/cua-spacesd-client/src/transport.rsindex 62586e72ec..66b153f9ad 100644--- a/libs/cua/crates/cua-spacesd-client/src/transport.rs+++ b/libs/cua/crates/cua-spacesd-client/src/transport.rs@@ -553,11 +553,193 @@ impl Service<Request<Body>> for Prefixed {let headers = Arc::clone(&self.headers);Box::pin(async move {headers.apply(&mut req).await.map_err(ChannelError)?;- inner.oneshot(req).await.map_err(ChannelError)+ let res = inner.oneshot(req).await.map_err(ChannelError)?;+ Ok(non_grpc_as_status(res).await)})}}+/// A response that is not gRPC (a proxy's or load balancer's HTTP error+/// page, an HTML 500) as the gRPC error it stands for.+///+/// Without this, tonic reads the page's first byte as a gRPC frame header+/// and fails with "protocol error: received message with invalid+/// compression flag: 73 (valid flags are 0 and 1) while receiving response+/// with status: 500", which hides what the server said. A gRPC server+/// always answers HTTP 200 with a `application/grpc*` content type, or+/// carries `grpc-status` in its headers (trailers-only); anything else is+/// turned into a trailers-only response whose status names the HTTP status+/// and the start of the body, with the code the gRPC HTTP mapping gives.+pub(crate) async fn non_grpc_as_status(res: Response<Body>) -> Response<Body> {+ if !is_non_grpc(&res) {+ return res;+ }+ let (parts, body) = res.into_parts();+ let text = http_body_util::Limited::new(body, NON_GRPC_BODY_MAX);+ let text = tokio::time::timeout(+ Duration::from_secs(5),+ http_body_util::BodyExt::collect(text),+ )+ .await+ .ok()+ .and_then(|r| r.ok())+ .map(|c| body_summary(&c.to_bytes()))+ .unwrap_or_default();+ let status = parts.status;+ let reason = status.canonical_reason().unwrap_or("");+ let mut message = format!("HTTP {} {reason}", status.as_u16())+ .trim_end()+ .to_string();+ if status == http::StatusCode::OK {+ let ct = parts+ .headers+ .get(http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .unwrap_or("none");+ message.push_str(&format!(" with content type {ct}, not gRPC"));+ }+ if !text.is_empty() {+ message.push_str(": ");+ message.push_str(&text);+ }+ tonic::Status::new(http_status_code(status), message).into_http::<Body>()+}++/// How much of a non-gRPC body is read for its message.+const NON_GRPC_BODY_MAX: usize = 16 * 1024;++fn is_non_grpc<B>(res: &Response<B>) -> bool {+ if res.headers().contains_key("grpc-status") {+ return false;+ }+ let grpc_type = res+ .headers()+ .get(http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .is_some_and(|ct| ct.starts_with("application/grpc"));+ res.status() != http::StatusCode::OK || !grpc_type+}++/// The gRPC code for an HTTP status without one+/// (<https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md>).+fn http_status_code(status: http::StatusCode) -> tonic::Code {+ match status.as_u16() {+ 400 => tonic::Code::Internal,+ 401 => tonic::Code::Unauthenticated,+ 403 => tonic::Code::PermissionDenied,+ 404 => tonic::Code::Unimplemented,+ 429 | 502 | 503 | 504 => tonic::Code::Unavailable,+ _ => tonic::Code::Unknown,+ }+}++/// The readable start of an error body: the text of an HTML page (tags+/// dropped), whitespace collapsed, at most 300 characters.+fn body_summary(bytes: &[u8]) -> String {+ let raw = String::from_utf8_lossy(bytes);+ let mut text = String::with_capacity(raw.len().min(4096));+ let mut in_tag = false;+ for c in raw.chars() {+ match c {+ '<' => in_tag = true,+ '>' if in_tag => {+ in_tag = false;+ text.push(' ');+ }+ _ if in_tag => {}+ c if c.is_control() => text.push(' '),+ c => text.push(c),+ }+ }+ let words: Vec<&str> = text.split_whitespace().collect();+ let mut out = words.join(" ");+ if out.chars().count() > 300 {+ out = out.chars().take(300).collect::<String>() + "...";+ }+ out+}++#[cfg(test)]+mod non_grpc_tests {+ use super::*;++ fn response(status: u16, ct: Option<&str>, body: &'static str) -> Response<Body> {+ let mut b = Response::builder().status(status);+ if let Some(ct) = ct {+ b = b.header(http::header::CONTENT_TYPE, ct);+ }+ b.body(Body::new(http_body_util::Full::new(+ bytes::Bytes::from_static(body.as_bytes()),+ )))+ .unwrap()+ }++ fn status_of(res: &Response<Body>) -> tonic::Status {+ tonic::Status::from_header_map(res.headers()).expect("a grpc-status header")+ }++ /// An HTML 500 from a proxy becomes a readable gRPC error, never a+ /// frame-parsing "invalid compression flag".+ #[tokio::test]+ async fn an_html_500_is_a_readable_error() {+ let res = non_grpc_as_status(response(+ 500,+ Some("text/html"),+ "<html><body><h1>Internal Server Error</h1>\n<p>upstream failed</p></body></html>",+ ))+ .await;+ let s = status_of(&res);+ assert_eq!(s.code(), tonic::Code::Unknown);+ assert_eq!(+ s.message(),+ "HTTP 500 Internal Server Error: Internal Server Error upstream failed"+ );+ }++ /// A gateway's 502 keeps its status words (callers retry on them) and+ /// maps to `Unavailable`.+ #[tokio::test]+ async fn a_502_is_unavailable() {+ let res =+ non_grpc_as_status(response(502, Some("text/plain"), "failed to reach host")).await;+ let s = status_of(&res);+ assert_eq!(s.code(), tonic::Code::Unavailable);+ assert_eq!(s.message(), "HTTP 502 Bad Gateway: failed to reach host");+ }++ /// A 200 that is not gRPC (a captive portal, a web page) is an error too.+ #[tokio::test]+ async fn a_200_web_page_is_an_error() {+ let res = non_grpc_as_status(response(200, Some("text/html"), "<p>hello</p>")).await;+ let s = status_of(&res);+ assert_eq!(+ s.message(),+ "HTTP 200 OK with content type text/html, not gRPC: hello"+ );+ }++ /// gRPC answers pass through untouched: a normal one and a+ /// trailers-only error (whatever its HTTP status).+ #[tokio::test]+ async fn grpc_responses_pass_through() {+ let ok = non_grpc_as_status(response(200, Some("application/grpc"), "\0\0\0\0\0")).await;+ assert!(!ok.headers().contains_key("grpc-status"));+ let web = non_grpc_as_status(response(200, Some("application/grpc-web+proto"), "")).await;+ assert!(!web.headers().contains_key("grpc-status"));+ let mut err = tonic::Status::not_found("no such space").into_http::<Body>();+ *err.status_mut() = http::StatusCode::OK;+ let err = non_grpc_as_status(err).await;+ assert_eq!(status_of(&err).message(), "no such space");+ }++ /// Long bodies are cut to a readable length.+ #[test]+ fn long_bodies_are_cut() {+ let long = "x".repeat(1000);+ assert_eq!(body_summary(long.as_bytes()).chars().count(), 303);+ }+}+#[cfg(test)]mod extra_header_tests {use super::*;