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
relay: retry plan lookups after a transport error, log the cause (CUA-2276) (#5928)
cua-agents[bot]685f81c8753e
diff --git a/libs/cua-spacesd/crates/cua-relay/src/org_access.rs b/libs/cua-spacesd/crates/cua-relay/src/org_access.rsindex 1e1ec42469..e8d6f88f36 100644--- a/libs/cua-spacesd/crates/cua-relay/src/org_access.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/org_access.rs@@ -385,7 +385,7 @@ impl OrgAccess {]).send().await- .map_err(|e| format!("service token: {e}"))?;+ .map_err(|e| format!("service token: {}", error_chain(&e)))?;if !reply.status().is_success() {return Err(format!("service token: HTTP {}", reply.status()));}@@ -421,7 +421,7 @@ impl OrgAccess {self.counters.api_calls.fetch_add(1, Ordering::Relaxed);let r = req.send().await.map_err(|e| {self.counters.api_errors.fetch_add(1, Ordering::Relaxed);- format!("Spaces API: {e}")+ format!("Spaces API: {}", error_chain(&e))})?;if r.status().is_server_error() || r.status() == reqwest::StatusCode::UNAUTHORIZED {self.counters.api_errors.fetch_add(1, Ordering::Relaxed);@@ -1046,6 +1046,19 @@ fn machine_ids(v: &serde_json::Value) -> Vec<String> {.unwrap_or_default()}+/// An error with its causes ("error sending request: operation timed out"),+/// so the log says whether a lookup timed out, was refused or was reset.+fn error_chain(e: &dyn std::error::Error) -> String {+ let mut out = e.to_string();+ let mut src = e.source();+ while let Some(s) = src {+ out.push_str(": ");+ out.push_str(&s.to_string());+ src = s.source();+ }+ out+}+#[cfg(test)]mod tests {use super::*;diff --git a/libs/cua-spacesd/crates/cua-relay/src/plan_source.rs b/libs/cua-spacesd/crates/cua-relay/src/plan_source.rsindex cdc12b48c8..57d050029f 100644--- a/libs/cua-spacesd/crates/cua-relay/src/plan_source.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/plan_source.rs@@ -41,6 +41,14 @@ const MAX_ENTRIES: usize = 50_000;const MAX_CONCURRENT_LOOKUPS: usize = 4;/// Wait before the first retry for a user never answered for.const RETRY_UNKNOWN_AFTER: Duration = Duration::from_secs(3);+/// Tries per lookup. A transport blip (a connection reset or a 5 s stall on+/// one pod) usually clears within a second, so ask again before counting the+/// lookup as failed and waiting for the next refresh.+const FETCH_ATTEMPTS: usize = 3;+/// Wait before the second try; doubled before the third.+const FETCH_BACKOFF: Duration = Duration::from_millis(250);+/// Start of the errors for an answer the API did give (4xx, unreadable body).+const ANSWERED: &str = "Spaces API entitlements";/// Least time between writes of the plan snapshot.const PERSIST_EVERY: Duration = Duration::from_secs(10);@@ -365,10 +373,7 @@ impl Inner {}let _done = Done(&self, &user);self.counters.lookups.fetch_add(1, Ordering::Relaxed);- let answer = {- let _permit = self.permits.acquire().await;- self.fetch(&user).await- };+ let answer = self.fetch_with_retry(&user).await;let now = Instant::now();let changed = {let mut cache = self.cache.lock().expect("plan cache");@@ -456,6 +461,29 @@ impl Inner {.and_then(|()| std::fs::rename(&tmp, path).map_err(|e| e.to_string()))}+ /// [`Self::fetch`], asked again with a short backoff after a transport+ /// error, a 5xx or a refused service token. The permit is held per try,+ /// never while waiting, so a retry cannot starve other users' lookups.+ async fn fetch_with_retry(&self, user: &str) -> Result<Assignment, String> {+ let mut wait = FETCH_BACKOFF;+ let mut last = Err("no lookup made".to_owned());+ for attempt in 1..=FETCH_ATTEMPTS {+ last = {+ let _permit = self.permits.acquire().await;+ self.fetch(user).await+ };+ // Only a transport error, a 5xx or a refused token is worth asking+ // again; a 4xx (429, 403) or an unreadable answer is final.+ let final_answer = matches!(&last, Err(e) if e.starts_with(ANSWERED));+ if last.is_ok() || final_answer || attempt == FETCH_ATTEMPTS || !self.org.has_api() {+ break;+ }+ tokio::time::sleep(wait).await;+ wait *= 2;+ }+ last+ }+async fn fetch(&self, user: &str) -> Result<Assignment, String> {let path = format!("/internal/v1/entitlements/{}",@@ -466,12 +494,12 @@ impl Inner {return Ok(Assignment::default());}if !r.status().is_success() {- return Err(format!("Spaces API entitlements: HTTP {}", r.status()));+ return Err(format!("{ANSWERED}: HTTP {}", r.status()));}let reply: EntitlementsReply = r.json().await- .map_err(|e| format!("Spaces API entitlements answer: {e}"))?;+ .map_err(|e| format!("{ANSWERED} answer: {e}"))?;Ok(assignment_from(&reply))}}@@ -586,6 +614,69 @@ mod tests {);}+ #[tokio::test]+ async fn a_lookup_is_asked_again_after_a_transport_error() {+ // A server that drops the first connection, then answers.+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let (first, _) = listener.accept().await.unwrap();+ drop(first);+ loop {+ let (mut c, _) = listener.accept().await.unwrap();+ let mut buf = [0u8; 2048];+ let _ = c.read(&mut buf).await;+ let body = r#"{"orgs":[]}"#;+ let _ = c+ .write_all(+ format!(+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",+ body.len()+ )+ .as_bytes(),+ )+ .await;+ }+ });+ let org = OrgAccess::new(crate::org_access::OrgAccessConfig {+ api_url: Some(format!("http://{addr}")),+ ..Default::default()+ });+ let plans = EntitlementPlans::new(Arc::new(org), None);+ let got = plans.inner.fetch_with_retry("ada").await;+ assert!(got.is_ok(), "{got:?}");+ }++ #[tokio::test]+ async fn a_refused_lookup_is_not_asked_again() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let hits = Arc::new(AtomicU64::new(0));+ let seen = hits.clone();+ tokio::spawn(async move {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ loop {+ let (mut c, _) = listener.accept().await.unwrap();+ seen.fetch_add(1, Ordering::Relaxed);+ let mut buf = [0u8; 2048];+ let _ = c.read(&mut buf).await;+ let _ = c+ .write_all(+ b"HTTP/1.1 429 Too Many Requests\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",+ )+ .await;+ }+ });+ let org = OrgAccess::new(crate::org_access::OrgAccessConfig {+ api_url: Some(format!("http://{addr}")),+ ..Default::default()+ });+ let plans = EntitlementPlans::new(Arc::new(org), None);+ assert!(plans.inner.fetch_with_retry("ada").await.is_err());+ assert_eq!(hits.load(Ordering::Relaxed), 1);+ }+#[tokio::test]async fn snapshot_restores_a_payer_when_the_api_is_down() {let dir = std::env::temp_dir().join(format!("plans-snap-{}", std::process::id()));