Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

perf(cua-mesh): an offline or unresponsive computer no longer holds up the others (#5907)

ddupont3a4b0aa68fb9
diff --git a/.github/workflows/ci-cua-sdk.yml b/.github/workflows/ci-cua-sdk.yml
index 386fefac28..4098ac167b 100644
--- a/.github/workflows/ci-cua-sdk.yml
+++ b/.github/workflows/ci-cua-sdk.yml
@@ -220,6 +220,12 @@ jobs:
shared-key: libs-cua-test
- name: Test Spaces discovery and post-create directory failures
run: cargo test --locked -p cua-spaces --test relay --test cloud_discovery -- --test-threads=4
+ - name: Test the mesh, and its scale budgets (offline or unresponsive computers never hold up the rest)
+ # The scale scenarios run one at a time: each starts 20 nodes and
+ # asserts wall-clock budgets.
+ run: |
+ cargo test --locked -p cua-mesh --lib --test mesh -- --test-threads=4
+ cargo test --locked -p cua-mesh --test scale -- --test-threads=1 --nocapture
- name: Test (embedded, daemon over UDS and loopback, CLI, cluster, Cua Spaces extensions)
run: >
cargo test --locked --no-fail-fast -p cua-sdk -p cua-daemon -p cua-cli -p cua-spacesd-client
diff --git a/libs/cua/crates/cua-mesh/examples/mesh-fanout.rs b/libs/cua/crates/cua-mesh/examples/mesh-fanout.rs
new file mode 100644
index 0000000000..85c49425f7
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/examples/mesh-fanout.rs
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Reaches many machines at once over a real relay's mesh, as the Spaces
+//! list does after a launch or a daemon restart, and prints how long each
+//! one took. With some of the machines switched off, it shows whether
+//! they hold up the rest.
+//!
+//! ```text
+//! # a machine (static-token relay), echoing every stream:
+//! mesh-fanout serve --relay URL --machine ID --relay-token T --env-token E --dir DIR
+//! # a client with a persistent identity, to every machine at once:
+//! mesh-fanout fanout --relay URL --machines ID,ID,... --env-token E --identity FILE
+//! ```
+//!
+//! `fanout` prints one JSON line per machine and a summary line.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cua_mesh::dialer::Dialer;
+use cua_mesh::{Mesh, MeshConfig, NodeKind};
+use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+fn flag(args: &[String], name: &str) -> String {
+ args.iter()
+ .position(|a| a == name)
+ .and_then(|i| args.get(i + 1))
+ .cloned()
+ .unwrap_or_else(|| panic!("{name} is required"))
+}
+
+#[tokio::main]
+async fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ match args.get(1).map(String::as_str) {
+ Some("serve") => serve(&args).await,
+ Some("fanout") => fanout(&args).await,
+ _ => {
+ eprintln!("usage: mesh-fanout serve|fanout ...");
+ std::process::exit(2);
+ }
+ }
+}
+
+async fn serve(args: &[String]) {
+ let relay = flag(args, "--relay");
+ let machine = flag(args, "--machine");
+ let token = flag(args, "--relay-token");
+ let env = flag(args, "--env-token");
+ let dir = std::path::PathBuf::from(flag(args, "--dir"));
+ std::fs::create_dir_all(&dir).unwrap();
+ let id = machine.clone();
+ let auth: cua_mesh::AuthProvider = Arc::new(move || {
+ let (token, id) = (token.clone(), id.clone());
+ Box::pin(async move {
+ Ok(vec![
+ ("authorization".to_owned(), format!("Bearer {token}")),
+ (cua_mesh::proto::MACHINE_ID_HEADER.to_owned(), id),
+ ])
+ })
+ });
+ let mut cfg = MeshConfig::new(
+ relay,
+ NodeKind::Machine,
+ Some(dir.join("identity.json")),
+ auth,
+ );
+ cfg.name = machine.clone();
+ cfg.media_udp_port = 0;
+ cfg.approved_path = Some(dir.join("approved.json"));
+ let id = machine.clone();
+ cfg.pair_verifier = Some(Arc::new(move |client, ts, proof| {
+ cua_mesh::proto::verify_pair_proof(
+ &env,
+ &id,
+ client,
+ ts,
+ proof,
+ cua_mesh::proto::now_secs(),
+ )
+ }));
+ let mesh = Mesh::start(cfg).await.expect("start");
+ mesh.wait_ready(Duration::from_secs(20))
+ .await
+ .expect("ready");
+ eprintln!("serving {machine}");
+ while let Some(incoming) = mesh.accept().await {
+ tokio::spawn(async move {
+ let (mut r, mut w) = tokio::io::split(incoming.stream);
+ let _ = tokio::io::copy(&mut r, &mut w).await;
+ let _ = w.shutdown().await;
+ });
+ }
+}
+
+async fn fanout(args: &[String]) {
+ let relay = flag(args, "--relay");
+ let machines: Vec<String> = flag(args, "--machines")
+ .split(',')
+ .map(str::to_owned)
+ .collect();
+ let env = flag(args, "--env-token");
+ let identity = std::path::PathBuf::from(flag(args, "--identity"));
+ let cap = Duration::from_secs(
+ args.iter()
+ .position(|a| a == "--cap")
+ .and_then(|i| args.get(i + 1))
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(90),
+ );
+ let started = Instant::now();
+ let dialer = Arc::new(
+ Dialer::start(
+ &relay,
+ cua_mesh::static_auth(vec![]),
+ Some(identity),
+ Duration::from_secs(20),
+ )
+ .await
+ .expect("client"),
+ );
+ let joined = started.elapsed();
+ let start = Instant::now();
+ let mut tasks = Vec::new();
+ for id in machines {
+ let (dialer, env) = (dialer.clone(), env.clone());
+ tasks.push(tokio::spawn(async move {
+ let r = tokio::time::timeout(cap, async {
+ let route = dialer
+ .route(&id, Some(&env), Duration::from_secs(3))
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut s = tokio::net::TcpStream::connect(route.local)
+ .await
+ .map_err(|e| e.to_string())?;
+ s.write_all(b"ping").await.map_err(|e| e.to_string())?;
+ let mut got = [0u8; 4];
+ s.read_exact(&mut got).await.map_err(|e| e.to_string())?;
+ Ok::<_, String>(())
+ })
+ .await
+ .unwrap_or_else(|_| Err(format!("no answer in {cap:?}")));
+ let ms = start.elapsed().as_millis();
+ let ok = r.is_ok();
+ println!(
+ "{}",
+ serde_json::json!({"machine": id, "ok": ok, "ms": ms, "error": r.err()})
+ );
+ (ok, ms)
+ }));
+ }
+ let (mut ok_max, mut fail_max, mut ok, mut failed) = (0, 0, 0, 0);
+ for t in tasks {
+ let (good, ms) = t.await.unwrap();
+ if good {
+ ok += 1;
+ ok_max = ok_max.max(ms);
+ } else {
+ failed += 1;
+ fail_max = fail_max.max(ms);
+ }
+ }
+ println!(
+ "{}",
+ serde_json::json!({"summary": true, "joined_ms": joined.as_millis(), "answered": ok,
+ "answered_max_ms": ok_max, "failed": failed, "failed_max_ms": fail_max})
+ );
+}
diff --git a/libs/cua/crates/cua-mesh/src/dialer.rs b/libs/cua/crates/cua-mesh/src/dialer.rs
index 1228003191..0165513f1f 100644
--- a/libs/cua/crates/cua-mesh/src/dialer.rs
+++ b/libs/cua/crates/cua-mesh/src/dialer.rs
@@ -110,11 +110,11 @@ impl Dialer {
env_token: Option<&str>,
wait: Duration,
) -> Result<Route> {
- let mut forwards = self.forwards.lock().await;
- if let Some(e) = forwards.get(machine_id)
- && self.mesh.machine(machine_id).map(|p| p.node_key) == Some(e.route.peer)
- {
- return Ok(e.route.clone());
+ // The lock is held only to read and write the table, never across
+ // a wait: one machine missing from the map, or slow to pair, must
+ // not hold up routes to the others.
+ if let Some(route) = self.cached(machine_id).await {
+ return Ok(route);
}
// A static relay's machine is in the map only once paired: pair
// right away instead of waiting for a map that will not have it.
@@ -140,6 +140,14 @@ impl Dialer {
crate::VERSION
)));
}
+ // The coordinator says it is not connected: say so now, so the
+ // caller moves on (or falls back) instead of waiting on a connect
+ // that cannot answer.
+ if !peer.online {
+ return Err(Error::Unreachable(format!(
+ "computer {machine_id} is offline"
+ )));
+ }
// Account relays: the machine vouches for this device only on
// requests carrying the forward's key. Static relays: the env token
// in each request is the credential.
@@ -156,6 +164,14 @@ impl Dialer {
session,
peer: peer.node_key,
};
+ let mut forwards = self.forwards.lock().await;
+ // Two callers raced to the same machine: the first forward stands
+ // (its session may already be in use); this one is dropped.
+ if let Some(e) = forwards.get(machine_id)
+ && e.route.peer == peer.node_key
+ {
+ return Ok(e.route.clone());
+ }
forwards.insert(
machine_id.to_owned(),
Entry {
@@ -166,6 +182,13 @@ impl Dialer {
Ok(route)
}
+ async fn cached(&self, machine_id: &str) -> Option<Route> {
+ let forwards = self.forwards.lock().await;
+ let e = forwards.get(machine_id)?;
+ (self.mesh.machine(machine_id).map(|p| p.node_key) == Some(e.route.peer))
+ .then(|| e.route.clone())
+ }
+
/// Drops the forward to `machine_id` (its path stopped answering).
pub async fn forget(&self, machine_id: &str) {
if let Some(e) = self.forwards.lock().await.remove(machine_id) {
diff --git a/libs/cua/crates/cua-mesh/src/engine.rs b/libs/cua/crates/cua-mesh/src/engine.rs
index 9b0e21d3e2..0dade8d682 100644
--- a/libs/cua/crates/cua-mesh/src/engine.rs
+++ b/libs/cua/crates/cua-mesh/src/engine.rs
@@ -268,7 +268,10 @@ impl Engine {
pub(crate) fn local_ports(&self) -> (u16, Option<u16>) {
let s = self.sockets.read().expect("sockets");
- let s = s.as_ref().expect("bound");
+ // Shut down (the discovery loop may run once more): no sockets.
+ let Some(s) = s.as_ref() else {
+ return (self.listen_port, None);
+ };
(
s.v4.local_addr()
.map(|a| a.port())
diff --git a/libs/cua/crates/cua-mesh/src/node.rs b/libs/cua/crates/cua-mesh/src/node.rs
index b0ed5fae30..ab92abbe3b 100644
--- a/libs/cua/crates/cua-mesh/src/node.rs
+++ b/libs/cua/crates/cua-mesh/src/node.rs
@@ -34,6 +34,11 @@ use crate::{Error, Result};
/// move it.
pub const MEDIA_UDP_PORT: u16 = 3212;
+/// How long a connection to a peer the map lists online may take.
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
+/// ... and to one it lists offline (only a direct path could carry it).
+const OFFLINE_CONNECT_TIMEOUT: Duration = Duration::from_millis(1500);
+
/// How a node is set up.
#[derive(Clone)]
pub struct MeshConfig {
@@ -251,6 +256,9 @@ struct Inner {
control: Arc<Control>,
endpoint: quinn::Endpoint,
conns: tokio::sync::Mutex<HashMap<PublicKey, quinn::Connection>>,
+ /// One connect at a time per peer (callers to the same peer share it);
+ /// peers never wait on each other's connects.
+ connecting: std::sync::Mutex<HashMap<PublicKey, Arc<tokio::sync::Mutex<()>>>>,
incoming: tokio::sync::Mutex<mpsc::Receiver<IncomingStream>>,
stun: Vec<String>,
shutdown: coord::tokio_util_cancel::Token,
@@ -309,6 +317,7 @@ impl Mesh {
control: control.clone(),
endpoint: endpoint.clone(),
conns: tokio::sync::Mutex::new(HashMap::new()),
+ connecting: std::sync::Mutex::new(HashMap::new()),
incoming: tokio::sync::Mutex::new(in_rx),
stun: cfg.stun.clone(),
shutdown: shutdown.clone(),
@@ -541,23 +550,72 @@ impl Mesh {
}
async fn connection(&self, peer: &PeerInfo) -> Result<quinn::Connection> {
- let mut conns = self.inner.conns.lock().await;
- if let Some(c) = conns.get(&peer.node_key)
- && c.close_reason().is_none()
- {
- return Ok(c.clone());
+ if let Some(c) = self.live_connection(&peer.node_key).await {
+ return Ok(c);
+ }
+ // Per peer: a peer that does not answer holds up only its own
+ // callers, never connections to the others (an offline computer
+ // used to stall every other one for the whole connect timeout).
+ let gate = self
+ .inner
+ .connecting
+ .lock()
+ .expect("connecting")
+ .entry(peer.node_key)
+ .or_default()
+ .clone();
+ let _turn = gate.lock().await;
+ if let Some(c) = self.live_connection(&peer.node_key).await {
+ return Ok(c);
}
self.inner.engine.want(&peer.node_key);
+ // A peer the map lists offline gets a short try (a direct path may
+ // still carry it), not the full wait.
+ let within = if peer.online {
+ CONNECT_TIMEOUT
+ } else {
+ OFFLINE_CONNECT_TIMEOUT
+ };
let c = tokio::time::timeout(
- Duration::from_secs(20),
+ within,
quic::connect(&self.inner.endpoint, peer.addr(), &peer.quic_pin),
)
.await
- .map_err(|_| Error::Unreachable(format!("{} did not answer on the mesh", peer.name)))??;
- conns.insert(peer.node_key, c.clone());
+ .map_err(|_| {
+ Error::Unreachable(if peer.online {
+ format!("{} did not answer on the mesh", peer.name)
+ } else {
+ format!("{} is offline", peer.name)
+ })
+ })??;
+ // Refused, or the peer left the map, while connecting: as if the
+ // connection had been open then (`denial_loop`, `prune_loop`).
+ if let Some(reason) = self.denied() {
+ c.close(3u32.into(), b"device refused");
+ return Err(Error::Refused(reason));
+ }
+ if self.inner.engine.peer(&peer.node_key).is_none() {
+ c.close(2u32.into(), b"peer removed");
+ return Err(Error::NotFound(format!("{} left the mesh", peer.name)));
+ }
+ self.inner
+ .conns
+ .lock()
+ .await
+ .insert(peer.node_key, c.clone());
Ok(c)
}
+ async fn live_connection(&self, peer: &PublicKey) -> Option<quinn::Connection> {
+ self.inner
+ .conns
+ .lock()
+ .await
+ .get(peer)
+ .filter(|c| c.close_reason().is_none())
+ .cloned()
+ }
+
/// Why this node can no longer use the mesh, while it holds: its
/// device was refused, or the relay turned its mesh off. Callers with
/// a fallback (the relay's HTTPS path) switch to it.
@@ -957,6 +1015,11 @@ async fn prune_loop(inner: std::sync::Weak<Inner>, mut rx: tokio::sync::watch::R
keep
});
drop(conns);
+ inner
+ .connecting
+ .lock()
+ .expect("connecting")
+ .retain(|k, _| current.contains(k));
// Connections removed peers opened to us end too (a share revoked,
// a device removed: cut at once, not at the idle timeout).
inner.inbound.lock().expect("inbound").retain(|(k, c)| {
diff --git a/libs/cua/crates/cua-mesh/tests/scale.rs b/libs/cua/crates/cua-mesh/tests/scale.rs
new file mode 100644
index 0000000000..00ded78800
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/tests/scale.rs
@@ -0,0 +1,370 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Many machines, some of them offline: one client reaches all of them at
+//! once (as the Spaces list does after an app launch or a daemon restart).
+//! An offline machine is in the network map, marked offline, as a computer
+//! that has been switched off for a while is. Machines that answer must
+//! answer within their budget, whatever the offline ones do, and the
+//! offline ones must fail fast instead of waiting out a connect timeout.
+//!
+//! Sizes: `CUA_MESH_SCALE_ONLINE` (default 15) and
+//! `CUA_MESH_SCALE_OFFLINE` (default 5). Each run prints one `SCALE` line
+//! per scenario with the slowest online and offline answers.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cua_mesh::dialer::Dialer;
+use cua_mesh::testing::FakeCoordinator;
+use cua_mesh::{Mesh, MeshConfig, Mode, NodeKind, static_auth};
+use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+/// Every machine that is online answers within this.
+const ONLINE_BUDGET: Duration = Duration::from_secs(2);
+/// Every offline machine is reported unreachable within this.
+const OFFLINE_BUDGET: Duration = Duration::from_secs(3);
+/// No single answer takes longer than this (it would only time out).
+const CAP: Duration = Duration::from_secs(60);
+
+fn size(var: &str, default: usize) -> usize {
+ std::env::var(var)
+ .ok()
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(default)
+}
+
+async fn machine(coord: &FakeCoordinator, dir: &std::path::Path, name: &str) -> Mesh {
+ let headers = vec![("x-cua-machine-id".to_owned(), format!("machine-{name}"))];
+ let mut cfg = MeshConfig::new(
+ coord.url.clone(),
+ NodeKind::Machine,
+ Some(dir.join(format!("{name}.json"))),
+ static_auth(headers),
+ );
+ cfg.name = name.to_owned();
+ cfg.stun = vec![coord.stun.to_string()];
+ // Port 0: many machines in one process.
+ cfg.media_udp_port = 0;
+ cfg.approved_path = Some(dir.join(format!("{name}-approved.json")));
+ let m = Mesh::start(cfg).await.expect("start");
+ m.wait_ready(Duration::from_secs(10)).await.expect("ready");
+ m
+}
+
+/// Echoes every stream, whatever its service.
+fn serve_echo(m: &Mesh) {
+ let m = m.clone();
+ tokio::spawn(async move {
+ while let Some(incoming) = m.accept().await {
+ tokio::spawn(async move {
+ let (mut r, mut w) = tokio::io::split(incoming.stream);
+ let _ = tokio::io::copy(&mut r, &mut w).await;
+ let _ = w.shutdown().await;
+ });
+ }
+ });
+}
+
+struct Fleet {
+ _dir: tempfile::TempDir,
+ coord: FakeCoordinator,
+ online: Vec<Mesh>,
+ offline: Vec<String>,
+}
+
+/// `online` machines serving echo, plus `offline` machines that joined
+/// once and were switched off (in the map, offline).
+async fn fleet(online: usize, offline: usize) -> Fleet {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let mut up = Vec::new();
+ for i in 0..online {
+ let m = machine(&coord, dir.path(), &format!("on{i}")).await;
+ serve_echo(&m);
+ up.push(m);
+ }
+ let mut down = Vec::new();
+ for i in 0..offline {
+ let name = format!("off{i}");
+ let m = machine(&coord, dir.path(), &name).await;
+ m.shutdown();
+ down.push(format!("machine-{name}"));
+ }
+ // The coordinator has noticed each one went away.
+ for _ in 0..200 {
+ if coord.connected() == online {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ assert_eq!(
+ coord.connected(),
+ online,
+ "offline machines still connected"
+ );
+ Fleet {
+ _dir: dir,
+ coord,
+ online: up,
+ offline: down,
+ }
+}
+
+async fn wait_map(client: &Mesh, machines: usize, offline: &[String]) {
+ for _ in 0..400 {
+ let peers = client.peers();
+ let all = peers.iter().filter(|p| p.kind == NodeKind::Machine).count() == machines;
+ let marked = offline
+ .iter()
+ .all(|id| client.machine(id).is_some_and(|p| !p.online));
+ if all && marked {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!("the client's map never listed every machine with its state");
+}
+
+async fn echo_once<S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin>(
+ s: &mut S,
+) -> std::io::Result<()> {
+ s.write_all(b"ping").await?;
+ s.flush().await?;
+ let mut got = [0u8; 4];
+ s.read_exact(&mut got).await?;
+ assert_eq!(&got, b"ping");
+ Ok(())
+}
+
+#[derive(Default)]
+struct Timings {
+ online: Vec<Duration>,
+ offline: Vec<Duration>,
+ online_failed: Vec<String>,
+ offline_answered: usize,
+}
+
+impl Timings {
+ fn report_and_check(&self, scenario: &str) {
+ let max = |v: &[Duration]| v.iter().max().copied().unwrap_or_default();
+ eprintln!(
+ "SCALE {scenario}: online n={} max={:?} offline n={} max={:?}",
+ self.online.len(),
+ max(&self.online),
+ self.offline.len(),
+ max(&self.offline)
+ );
+ assert!(
+ self.online_failed.is_empty(),
+ "{scenario}: online machines failed: {:?}",
+ self.online_failed
+ );
+ assert_eq!(
+ self.offline_answered, 0,
+ "{scenario}: an offline machine answered"
+ );
+ assert!(
+ max(&self.online) <= ONLINE_BUDGET,
+ "{scenario}: slowest online machine took {:?} (budget {ONLINE_BUDGET:?})",
+ max(&self.online)
+ );
+ assert!(
+ max(&self.offline) <= OFFLINE_BUDGET,
+ "{scenario}: slowest offline machine took {:?} (budget {OFFLINE_BUDGET:?})",
+ max(&self.offline)
+ );
+ }
+}
+
+/// Streams to every machine at once, straight on the node.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn offline_machines_do_not_hold_up_streams_to_the_rest() {
+ let f = fleet(
+ size("CUA_MESH_SCALE_ONLINE", 15),
+ size("CUA_MESH_SCALE_OFFLINE", 5),
+ )
+ .await;
+ let client = Dialer::start(
+ &f.coord.url,
+ static_auth(vec![]),
+ None,
+ Duration::from_secs(10),
+ )
+ .await
+ .unwrap();
+ let total = f.online.len() + f.offline.len();
+ wait_map(client.mesh(), total, &f.offline).await;
+
+ let mesh = client.mesh().clone();
+ let start = Instant::now();
+ let mut tasks = Vec::new();
+ // Offline ones first: the worst order for a shared connect lock.
+ for id in f.offline.iter() {
+ let key = mesh.machine(id).unwrap().node_key;
+ let mesh = mesh.clone();
+ tasks.push(tokio::spawn(async move {
+ let r = tokio::time::timeout(CAP, async {
+ let mut s = mesh.open_stream(&key, "echo", None).await?;
+ echo_once(&mut s)
+ .await
+ .map_err(|e| cua_mesh::Error::Io(e.to_string()))
+ })
+ .await;
+ (
+ false,
+ r.map(|r| r.is_ok()).unwrap_or(false),
+ start.elapsed(),
+ )
+ }));
+ }
+ for m in &f.online {
+ let key = m.node_key();
+ let mesh = mesh.clone();
+ tasks.push(tokio::spawn(async move {
+ let r = tokio::time::timeout(CAP, async {
+ let mut s = mesh.open_stream(&key, "echo", None).await?;
+ echo_once(&mut s)
+ .await
+ .map_err(|e| cua_mesh::Error::Io(e.to_string()))
+ })
+ .await;
+ (true, r.map(|r| r.is_ok()).unwrap_or(false), start.elapsed())
+ }));
+ }
+ let mut t = Timings::default();
+ for task in tasks {
+ let (online, ok, took) = task.await.unwrap();
+ match (online, ok) {
+ (true, true) => t.online.push(took),
+ (true, false) => t.online_failed.push(format!("{took:?}")),
+ (false, true) => t.offline_answered += 1,
+ (false, false) => t.offline.push(took),
+ }
+ }
+ t.report_and_check("open_stream");
+}
+
+/// The Spaces path: a route (a loopback forward) per machine, then a
+/// request through it, for every machine at once.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn offline_machines_do_not_hold_up_routes_to_the_rest() {
+ let f = fleet(
+ size("CUA_MESH_SCALE_ONLINE", 15),
+ size("CUA_MESH_SCALE_OFFLINE", 5),
+ )
+ .await;
+ let client = Arc::new(
+ Dialer::start(
+ &f.coord.url,
+ static_auth(vec![]),
+ None,
+ Duration::from_secs(10),
+ )
+ .await
+ .unwrap(),
+ );
+ let total = f.online.len() + f.offline.len();
+ wait_map(client.mesh(), total, &f.offline).await;
+
+ let start = Instant::now();
+ let mut tasks = Vec::new();
+ let ids = f.offline.iter().map(|id| (false, id.clone())).chain(
+ f.online
+ .iter()
+ .enumerate()
+ .map(|(i, _)| (true, format!("machine-on{i}"))),
+ );
+ for (online, id) in ids {
+ let client = client.clone();
+ tasks.push(tokio::spawn(async move {
+ let r = tokio::time::timeout(CAP, async {
+ let route = client
+ .route(&id, None, Duration::from_secs(3))
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut s = tokio::net::TcpStream::connect(route.local)
+ .await
+ .map_err(|e| e.to_string())?;
+ echo_once(&mut s).await.map_err(|e| e.to_string())
+ })
+ .await;
+ (online, matches!(r, Ok(Ok(()))), start.elapsed())
+ }));
+ }
+ let mut t = Timings::default();
+ for task in tasks {
+ let (online, ok, took) = task.await.unwrap();
+ match (online, ok) {
+ (true, true) => t.online.push(took),
+ (true, false) => t.online_failed.push(format!("{took:?}")),
+ (false, true) => t.offline_answered += 1,
+ (false, false) => t.offline.push(took),
+ }
+ }
+ t.report_and_check("route");
+}
+
+/// Computers that accept a connection and then never answer (a hung
+/// driver, a machine going to sleep mid-request): the rest answer within
+/// budget all the same, and each hung one is bounded by its caller.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn unresponsive_machines_do_not_hold_up_the_rest() {
+ let online = size("CUA_MESH_SCALE_ONLINE", 15);
+ let hung = size("CUA_MESH_SCALE_HUNG", 5);
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let mut up = Vec::new();
+ for i in 0..online {
+ let m = machine(&coord, dir.path(), &format!("on{i}")).await;
+ serve_echo(&m);
+ up.push(m);
+ }
+ // Their streams are never accepted, so never answered.
+ let mut dark = Vec::new();
+ for i in 0..hung {
+ dark.push(machine(&coord, dir.path(), &format!("hung{i}")).await);
+ }
+ let client = Dialer::start(
+ &coord.url,
+ static_auth(vec![]),
+ None,
+ Duration::from_secs(10),
+ )
+ .await
+ .unwrap();
+ wait_map(client.mesh(), online + hung, &[]).await;
+
+ let mesh = client.mesh().clone();
+ let start = Instant::now();
+ let mut tasks = Vec::new();
+ let targets = dark
+ .iter()
+ .map(|m| (false, m.node_key()))
+ .chain(up.iter().map(|m| (true, m.node_key())));
+ for (awake, key) in targets {
+ let mesh = mesh.clone();
+ tasks.push(tokio::spawn(async move {
+ // The caller's own deadline, as every Spaces call has one.
+ let r = tokio::time::timeout(OFFLINE_BUDGET - Duration::from_millis(500), async {
+ let mut s = mesh.open_stream(&key, "echo", None).await?;
+ echo_once(&mut s)
+ .await
+ .map_err(|e| cua_mesh::Error::Io(e.to_string()))
+ })
+ .await;
+ (awake, matches!(r, Ok(Ok(()))), start.elapsed())
+ }));
+ }
+ let mut t = Timings::default();
+ for task in tasks {
+ let (awake, ok, took) = task.await.unwrap();
+ match (awake, ok) {
+ (true, true) => t.online.push(took),
+ (true, false) => t.online_failed.push(format!("{took:?}")),
+ (false, true) => t.offline_answered += 1,
+ (false, false) => t.offline.push(took),
+ }
+ }
+ t.report_and_check("unresponsive");
+}