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.

fix(spaces): one owner for relay machine state

injaneity9994fc2e41a8
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
index a5ae06fc38..be00211047 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
@@ -1649,6 +1649,7 @@ impl Spaces {
fn has_share_consent(&self) -> bool;
fn set_relay(&self, relay: Option<RelayAccount>);
async fn relay_machines(&self) -> Result<Vec<RelayMachine>>;
+ async fn find(&self, space: &str) -> Result<SpaceInfo>;
fn resolve(&self, space: &str) -> Result<SpaceId>;
async fn add(&self, url: &str, token: Option<String>, name: Option<String>) -> Result<SpaceInfo>;
async fn add_with_service(&self, url: &str, token: Option<String>, name: Option<String>, service: Option<String>) -> Result<SpaceInfo>;
diff --git a/docs/content/docs/spaces/index.mdx b/docs/content/docs/spaces/index.mdx
index 349fefac43..a664d4e618 100644
--- a/docs/content/docs/spaces/index.mdx
+++ b/docs/content/docs/spaces/index.mdx
@@ -28,7 +28,7 @@ run agents in them from Python, TypeScript, Swift or Rust.
| Direct | `direct:<host:port>` | `spaces.add(url, token)`: an existing machine |
| Relay | `relay:<machine-id>` | Your machines set up with `cua host setup`, listed automatically |
-The app, the `cua` CLI, the SDKs and `cua daemon` share one registry (`~/.cua/spaces.json`).
+The app, the `cua` CLI, the SDKs and `cua daemon` share one registry (`~/.cua/spaces.json`). Relay machines come from the account's directory and are never written to `spaces.json`.
## What you can do with a Space
diff --git a/libs/cua/crates/cua-cli/src/sandbox.rs b/libs/cua/crates/cua-cli/src/sandbox.rs
index 22229e402c..aaeb177c94 100644
--- a/libs/cua/crates/cua-cli/src/sandbox.rs
+++ b/libs/cua/crates/cua-cli/src/sandbox.rs
@@ -2081,13 +2081,8 @@ pub async fn env_of(cua: &Cua, name: &str) -> Result<Arc<cua_sdk::SpacesdClient>
crate::host::daemon_relay_account(&crate::util::cua_home())
});
let spaces = cua.spaces();
- // `Spaces::space` looks the machine up in the relay directory cache.
- // An embedded runtime fills that cache on list, not on connect. A
- // qualified id that is not in the directory is not a Space yet.
- let listed = spaces.list().await?;
- if !listed.iter().any(|s| s.id == id) {
- return Err(CuaError::NotFound(format!("Space {id}")));
- }
+ // NotFound before dial, and the snapshot has the name space() dials with.
+ spaces.resolve(id.clone()).await?;
return spaces.space(id).await?.spacesd();
}
let sbx = cua.sandboxes();
diff --git a/libs/cua/crates/cua-daemon/src/spaces_svc.rs b/libs/cua/crates/cua-daemon/src/spaces_svc.rs
index 2965314941..9adc4303f6 100644
--- a/libs/cua/crates/cua-daemon/src/spaces_svc.rs
+++ b/libs/cua/crates/cua-daemon/src/spaces_svc.rs
@@ -18,19 +18,11 @@ mod imp {
use cua_sandbox_core::placement::{Kind, On, Runtime};
use prost::Message;
- fn record(spaces: &cua_spaces::Spaces, id: &str) -> Result<pb::Space, Error> {
+ async fn record(spaces: &cua_spaces::Spaces, id: &str) -> Result<pb::Space, Error> {
if let Some(r) = spaces.registry().get(id).map_err(Error::from)? {
return Ok(r);
}
- // Relay machines are not registered; they come from the account's
- // directory listing.
- spaces
- .list()
- .map_err(Error::from)?
- .iter()
- .find(|i| i.id == id)
- .map(info_record)
- .ok_or_else(|| Error::NotFound(format!("Space {id}")))
+ Ok(info_record(&spaces.find(id).await.map_err(Error::from)?))
}
/// A relay machine (or any listed Space) as a SpaceService record.
@@ -116,13 +108,13 @@ mod imp {
}
/// What a create returned, as the wire response.
- fn create_response(
+ async fn create_response(
spaces: &cua_spaces::Spaces,
created: cua_spaces::SpaceCreated,
) -> Result<pb::CreateSpaceResponse, tonic::Status> {
Ok(match created {
cua_spaces::SpaceCreated::Ready { info, reused } => pb::CreateSpaceResponse {
- space: Some(record(spaces, &info.id).map_err(st)?),
+ space: Some(record(spaces, &info.id).await.map_err(st)?),
phase: "ready".into(),
reused,
},
@@ -181,7 +173,7 @@ mod imp {
.await
.map_err(|e| st(e.into()))?;
ok(pb::AddSpaceResponse {
- space: Some(record(self.spaces(), &info.id).map_err(st)?),
+ space: Some(record(self.spaces(), &info.id).await.map_err(st)?),
})
}
@@ -224,7 +216,7 @@ mod imp {
.resolve(&req.into_inner().space)
.map_err(|e| st(e.into()))?;
ok(pb::ResolveSpaceResponse {
- space: Some(record(self.spaces(), &id.to_string()).map_err(st)?),
+ space: Some(record(self.spaces(), &id.to_string()).await.map_err(st)?),
})
}
@@ -262,7 +254,7 @@ mod imp {
match created {
cua_spaces::SpaceCreated::Ready { info, reused } => {
ok(pb::ClaimFleetSpaceResponse {
- space: Some(record(self.spaces(), &info.id).map_err(st)?),
+ space: Some(record(self.spaces(), &info.id).await.map_err(st)?),
pending_json: String::new(),
reused,
})
@@ -301,7 +293,7 @@ mod imp {
.ready()
.map_err(|p| st(Error::Internal(format!("{} is still starting", p.id))))?;
ok(pb::ProvisionLocalSpaceResponse {
- space: Some(record(self.spaces(), &info.id).map_err(st)?),
+ space: Some(record(self.spaces(), &info.id).await.map_err(st)?),
})
}
@@ -327,7 +319,7 @@ mod imp {
.create(create)
.await
.map_err(|e| st(e.into()))?;
- ok(create_response(self.spaces(), created)?)
+ ok(create_response(self.spaces(), created).await?)
}
type CreateSpaceStreamStream = std::pin::Pin<
@@ -367,11 +359,11 @@ mod imp {
let spaces = self.spaces().clone();
tokio::spawn(async move {
let result = match spaces.create(create).await {
- Ok(created) => {
- create_response(&spaces, created).map(|r| pb::CreateSpaceStreamResponse {
+ Ok(created) => create_response(&spaces, created).await.map(|r| {
+ pb::CreateSpaceStreamResponse {
event: Some(Event::Result(r)),
- })
- }
+ }
+ }),
Err(e) => Err(st(e.into())),
};
let _ = tx.send(result).await;
@@ -460,7 +452,7 @@ mod imp {
})
.collect();
ok(pb::ConnectSpaceResponse {
- space: Some(record(self.spaces(), &id).map_err(st)?),
+ space: Some(record(self.spaces(), &id).await.map_err(st)?),
env_url: if space.has_spacesd() {
format!("{base}/v1/spaces/{key}/env")
} else {
diff --git a/libs/cua/crates/cua-sdk/src/native/spaces.rs b/libs/cua/crates/cua-sdk/src/native/spaces.rs
index 31b72125b3..16802790b3 100644
--- a/libs/cua/crates/cua-sdk/src/native/spaces.rs
+++ b/libs/cua/crates/cua-sdk/src/native/spaces.rs
@@ -2080,14 +2080,7 @@ impl Host {
async fn record(&self, space: &str) -> Result<SpaceInfo> {
match self {
- Host::Embedded(s) => {
- let id = s.resolve(space)?;
- s.list()?
- .into_iter()
- .find(|i| i.id == id.to_string())
- .map(Into::into)
- .ok_or_else(|| CuaError::NotFound(format!("Space {id}")))
- }
+ Host::Embedded(s) => Ok(s.find(space).await?.into()),
Host::Daemon(d) => d
.spaces()
.resolve_space(dpb::ResolveSpaceRequest {
diff --git a/libs/cua/crates/cua-sdk/tests/space_os.rs b/libs/cua/crates/cua-sdk/tests/space_os.rs
index e2cc41bb83..1dae6daba6 100644
--- a/libs/cua/crates/cua-sdk/tests/space_os.rs
+++ b/libs/cua/crates/cua-sdk/tests/space_os.rs
@@ -185,3 +185,87 @@ async fn discovered_relay_os_survives_embedded_and_daemon_connections() {
}
}
}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn relay_id_resolves_before_any_list_including_a_late_join() {
+ for daemon in [false, true] {
+ let relay = FakeRelay::start().await;
+ relay.legacy_enrollment(true);
+ relay.add_account("owner-token", "owner", None);
+ let id = "00112233445566778899aabbccddeeff";
+ let joined = "ffeeddccbbaa99887766554433221100";
+ let register = async |machine: &str, name: &str| {
+ cua_host::RelayClient::new(&relay.url)
+ .unwrap()
+ .register(
+ "owner-token",
+ &RegisterRequest {
+ id: machine.into(),
+ name: name.into(),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ };
+ register(id, "Test host").await;
+ let env = fixtures::start_env(None, None).await;
+ relay.tunnel(id, &env.url);
+ relay.set_online(id, true, "0.0.0-mock");
+ let home = tempfile::tempdir().unwrap();
+ let runtime = Runtime::new(RuntimeConfig {
+ state_dir: Some(home.path().join("sandboxes")),
+ spaces_home: Some(home.path().join("cua")),
+ ..Default::default()
+ })
+ .unwrap();
+ runtime.spaces().set_relay(Some(RelayAccount::new(
+ &relay.url,
+ Arc::new(StaticToken("owner-token".into())),
+ )));
+ let (cua, server) = if daemon {
+ let h = server::start(
+ runtime,
+ ServerConfig {
+ socket_path: Some(home.path().join("cua.sock")),
+ loopback: Some("127.0.0.1:0".parse().unwrap()),
+ token: "daemon-token".into(),
+ discovery_path: Some(home.path().join("daemon.json")),
+ bridge_ticket_ttl: std::time::Duration::from_secs(30),
+ },
+ )
+ .await
+ .unwrap();
+ (
+ Cua::connect(h.loopback_url.clone(), Some(h.token.clone())).unwrap(),
+ Some(h),
+ )
+ } else {
+ (Cua::from_runtime(runtime), None)
+ };
+ let spaces = cua.spaces();
+ let key = format!("relay:{id}");
+ let resolved = spaces.resolve(key.clone()).await.unwrap();
+ assert_eq!(resolved.name, "Test host", "daemon={daemon}");
+ let connected = spaces.space(key).await.unwrap();
+ assert_eq!(connected.info().name, "Test host");
+ register(joined, "Late host").await;
+ let late = spaces.resolve(format!("relay:{joined}")).await.unwrap();
+ assert_eq!(late.name, "Late host", "daemon={daemon}");
+ let missing = spaces
+ .resolve("direct:127.0.0.1:9".into())
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(missing, cua_sdk::CuaError::NotFound(_)),
+ "{missing}"
+ );
+ assert!(!home.path().join("cua/spaces.json").exists());
+ drop(connected);
+ drop(cua);
+ if let Some(server) = server {
+ server.shutdown();
+ server.wait().await;
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/cloud.rs b/libs/cua/crates/cua-spaces/src/cloud.rs
index 96f55a7fef..fc6c35a9cc 100644
--- a/libs/cua/crates/cua-spaces/src/cloud.rs
+++ b/libs/cua/crates/cua-spaces/src/cloud.rs
@@ -148,11 +148,6 @@ impl Spaces {
}
// Provisioning has already succeeded. A directory outage must not
// conceal a recorded target or imply that creation should be retried.
- let listed = match self.list_all().await {
- Ok(rows) => Ok(rows),
- Err(Error::Relay(_)) => self.list(),
- Err(e) => Err(e),
- };
let unavailable = || {
Error::Relay(cua_host::Error::Relay(
concat!(
@@ -162,12 +157,7 @@ impl Spaces {
.into(),
))
};
- let info = listed
- .map_err(|_| unavailable())?
- .into_iter()
- .find(|i| i.id == id)
- .ok_or_else(unavailable)?;
- Ok(info)
+ self.find(&id).await.map_err(|_| unavailable())
}
/// The name of the cloud sandbox behind a `relay:<machine>` Space, if
diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rs
index 2366ed8543..9f6166d2df 100644
--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs
@@ -1957,7 +1957,6 @@ impl Spaces {
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
- let _ = self.relay_machines().await;
let m = match row {
Some(m) => m,
None => client.machine(&token, &machine).await?,
@@ -2193,7 +2192,7 @@ impl Spaces {
Ok(()) | Err(cua_host::Error::NotFound(_)) => {}
Err(e) => return Err(e.into()),
}
- let _ = self.relay_machines().await;
+ self.relay_forget(machine);
Ok(())
}
diff --git a/libs/cua/crates/cua-spaces/src/relay.rs b/libs/cua/crates/cua-spaces/src/relay.rs
index 9e9900443f..1a2b987ca3 100644
--- a/libs/cua/crates/cua-spaces/src/relay.rs
+++ b/libs/cua/crates/cua-spaces/src/relay.rs
@@ -197,11 +197,7 @@ impl crate::Spaces {
machine_id: machine_id.to_string(),
};
self.drop_connection(&id).await;
- self.inner
- .relay_cache
- .lock()
- .expect("relay cache")
- .retain(|m| m.id != machine_id);
+ self.relay_forget(machine_id);
let _ = self.inner.registry.remove(&id.to_string());
self.inner.thumbnails.remove(&id.to_string());
#[cfg(feature = "spaces-agents")]
diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rs
index 9c326dc0a4..f5ebdc6fc1 100644
--- a/libs/cua/crates/cua-spaces/src/share.rs
+++ b/libs/cua/crates/cua-spaces/src/share.rs
@@ -532,7 +532,7 @@ impl Spaces {
// A bare relay machine id (`space-…`) is known once the
// directory was listed.
Err(Error::NotFound(_)) if self.relay_account().is_some() => {
- let _ = self.relay_machines().await;
+ self.relay_directory(Some(space)).await?;
self.resolve(space)?
}
other => other?,
@@ -618,11 +618,7 @@ impl Spaces {
match removed {
Ok(()) => {
self.forget_attached_machine(&machine);
- self.inner
- .relay_cache
- .lock()
- .expect("relay cache")
- .retain(|m| m.id != machine);
+ self.relay_forget(&machine);
self.audit_share("detach", canonical, &format!("machine={machine}"));
None
}
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 9902eaadac..d8799ae0e8 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -397,6 +397,7 @@ impl SpacesBuilder {
#[cfg(feature = "spaces-agents")]
relay: std::sync::RwLock::new(self.relay),
relay_cache: std::sync::Mutex::new(Vec::new()),
+ relay_read: tokio::sync::Mutex::new(None),
site_login: std::sync::RwLock::new(None),
}),
}
@@ -617,6 +618,8 @@ pub(crate) struct Inner {
relay: std::sync::RwLock<Option<crate::relay::RelayAccount>>,
/// The last directory listing (so `list` and `resolve` stay sync).
pub(crate) relay_cache: std::sync::Mutex<Vec<crate::relay::RelayMachine>>,
+ /// Held across a read so only one directory read runs at a time.
+ relay_read: tokio::sync::Mutex<Option<std::time::Instant>>,
/// The Keyvault broker `request_site_login` signs in through (the
/// daemon sets it once its Keyvault is up).
site_login: std::sync::RwLock<Option<Arc<dyn crate::site_login::SiteLoginBroker>>>,
@@ -751,21 +754,7 @@ impl Spaces {
/// current directory. [`Self::list`] remains the cached, local read.
pub async fn list_all(&self) -> Result<Vec<SpaceInfo>> {
if self.relay_account().is_some() {
- self.relay_machines().await.map_err(|e| {
- // Relay errors can contain server bodies and credential-bearing
- // URLs. Discovery's public error needs only the stable kind.
- Error::Relay(match e.tag() {
- "unauthenticated" => cua_host::Error::Unauthenticated(
- "Relay authentication failed. Sign in again to refresh your machines."
- .into(),
- ),
- "permission_denied" => cua_host::Error::PermissionDenied(
- "This device could not list relay machines. Check its account access."
- .into(),
- ),
- _ => cua_host::Error::Relay("Could not refresh relay machines.".into()),
- })
- })?;
+ self.relay_machines().await?;
}
self.list()
}
@@ -846,17 +835,76 @@ impl Spaces {
/// The machines of the signed-in account on the relay (owned and shared
/// with it), each reachable as `relay:<id>`.
pub async fn relay_machines(&self) -> Result<Vec<crate::relay::RelayMachine>> {
+ self.relay_directory(None).await
+ }
+
+ const RELAY_MAX_AGE: Duration = Duration::from_secs(10);
+
+ pub(crate) async fn relay_directory(
+ &self,
+ want: Option<&str>,
+ ) -> Result<Vec<crate::relay::RelayMachine>> {
let relay = self.relay()?;
- let token = relay.tokens.access_token().await?;
- let client = cua_host::RelayClient::new(&relay.url)?;
- let machines = match &relay.device {
- Some(device) => device.machines_for(&client, &token).await?,
- None => client.machines(&token).await?,
+ let mut read_at = self.inner.relay_read.lock().await;
+ let cached = self.inner.relay_cache.lock().expect("relay cache").clone();
+ let listed = want.is_some_and(|id| cached.iter().any(|m| m.id == id));
+ if listed && read_at.is_some_and(|at| at.elapsed() < Self::RELAY_MAX_AGE) {
+ return Ok(cached);
+ }
+ let read = async {
+ let token = relay.tokens.access_token().await?;
+ let client = cua_host::RelayClient::new(&relay.url)?;
+ Ok::<_, Error>(match &relay.device {
+ Some(d) => d.machines_for(&client, &token).await?,
+ None => client.machines(&token).await?,
+ })
+ };
+ let machines = match read.await {
+ Ok(m) => m,
+ Err(_) if listed => return Ok(cached),
+ Err(e) => {
+ return Err(Error::Relay(match e.tag() {
+ "unauthenticated" => cua_host::Error::Unauthenticated(
+ "Relay authentication failed. Sign in again to refresh your machines."
+ .into(),
+ ),
+ "permission_denied" => cua_host::Error::PermissionDenied(
+ "This device could not list relay machines. Check its account access."
+ .into(),
+ ),
+ _ => cua_host::Error::Relay("Could not refresh relay machines.".into()),
+ }));
+ }
};
+ *read_at = Some(std::time::Instant::now());
*self.inner.relay_cache.lock().expect("relay cache") = machines.clone();
Ok(machines)
}
+ /// The listed row of `space`. Only a `relay:` id reads the directory.
+ pub async fn find(&self, space: &str) -> Result<SpaceInfo> {
+ let id = self.resolve(space)?;
+ let key = id.to_string();
+ if let SpaceId::Relay { machine_id } = &id
+ && self.relay_account().is_some()
+ && self.inner.registry.get(&key)?.is_none()
+ {
+ self.relay_directory(Some(machine_id)).await?;
+ }
+ self.list()?
+ .into_iter()
+ .find(|i| i.id == key)
+ .ok_or_else(|| Error::NotFound(format!("Space {key}")))
+ }
+
+ pub(crate) fn relay_forget(&self, machine_id: &str) {
+ self.inner
+ .relay_cache
+ .lock()
+ .expect("relay cache")
+ .retain(|m| m.id != machine_id);
+ }
+
/// Resolves any accepted spelling (canonical id, legacy id, URL, display
/// name, short name) to a canonical id.
pub fn resolve(&self, space: &str) -> Result<SpaceId> {
@@ -2367,7 +2415,9 @@ impl Spaces {
if let Some(sandbox) = self.cloud_sandbox_of(&id.to_string())? {
self.inner.sandboxes.delete(&sandbox).await?;
let _ = self.inner.registry.remove(&id.to_string());
- let _ = self.relay_machines().await;
+ if let SpaceId::Relay { machine_id } = &id {
+ self.relay_forget(machine_id);
+ }
return Ok(format!("Deleted {id} (sandbox {sandbox} in your cloud)."));
}
let what = match &id {
@@ -2426,14 +2476,14 @@ impl Spaces {
if let Some(m) = row.as_ref().filter(|m| crate::cloud::is_cloud_machine(m)) {
let message = self.delete_cloud_elsewhere(m).await?;
let _ = self.inner.registry.remove(&id.to_string());
- let _ = self.relay_machines().await;
+ self.relay_forget(machine_id);
return Ok(message);
}
match row.as_ref().and_then(|m| m.host.clone().map(|h| (m, h))) {
Some((m, host)) => {
let message = self.delete_on_host(m, &host).await?;
let _ = self.inner.registry.remove(&id.to_string());
- let _ = self.relay_machines().await;
+ self.relay_forget(machine_id);
return Ok(message);
}
// A Space that registered itself as a machine of yours:
@@ -2461,26 +2511,13 @@ impl Spaces {
Ok(what)
}
- /// The relay directory row of `machine_id` (cached, else refreshed);
- /// `None` without a relay account or when the relay does not list it.
+ /// The relay directory row of `machine_id`, or `None` when it is not listed.
pub(crate) async fn relay_row(&self, machine_id: &str) -> Option<crate::relay::RelayMachine> {
- self.relay_account()?;
- let cached = self
- .inner
- .relay_cache
- .lock()
- .expect("relay cache")
- .iter()
+ self.relay_directory(Some(machine_id))
+ .await
+ .ok()?
+ .into_iter()
.find(|m| m.id == machine_id)
- .cloned();
- match cached {
- Some(m) => Some(m),
- None => self
- .relay_machines()
- .await
- .ok()
- .and_then(|all| all.into_iter().find(|m| m.id == machine_id)),
- }
}
// ---------------------------------------------------------- thumbnails
@@ -2715,7 +2752,6 @@ impl Spaces {
self.drop_connection(&id).await;
let state = if on {
sandboxes.power_on(&sandbox).await?;
- let _ = self.relay_machines().await;
cua_sandbox_core::PowerState::Running
} else {
sandboxes.power_off(&sandbox).await?
diff --git a/libs/cua/crates/cua-spaces/tests/relay.rs b/libs/cua/crates/cua-spaces/tests/relay.rs
index 4881903a30..b222bd519c 100644
--- a/libs/cua/crates/cua-spaces/tests/relay.rs
+++ b/libs/cua/crates/cua-spaces/tests/relay.rs
@@ -177,6 +177,14 @@ async fn relay_spaces_need_an_account() {
assert_eq!(err.tag(), "host_capability_missing", "{err}");
let err = spaces.space(&format!("relay:{MACHINE}")).await.unwrap_err();
assert_eq!(err.tag(), "host_capability_missing", "{err}");
+ assert_eq!(
+ spaces
+ .find(&format!("relay:{MACHINE}"))
+ .await
+ .unwrap_err()
+ .tag(),
+ "not_found"
+ );
}
#[tokio::test]
@@ -261,6 +269,12 @@ async fn relay_spaces_carry_the_enrolled_device_session() {
.build();
let err = bare.relay_machines().await.unwrap_err();
assert_eq!(err.tag(), "permission_denied", "{err}");
+ let err = bare.find(&format!("relay:{MACHINE}")).await.unwrap_err();
+ assert_eq!(err.tag(), "permission_denied", "{err}");
+ assert_eq!(
+ err.to_string(),
+ "This device could not list relay machines. Check its account access."
+ );
assert_eq!(
bare.list_all().await.unwrap_err().tag(),
"permission_denied"
@@ -426,6 +440,47 @@ async fn discovery_failure_is_not_stale_success_and_empty_recovery_clears_cache(
assert_eq!(recovered.len(), 1);
assert_eq!(recovered[0].id, local.id);
assert_eq!(spaces.list().unwrap().len(), 1);
+
+ *tokens.current.lock().unwrap() = "owner".into();
+ let calls = tokens.calls.load(Ordering::SeqCst);
+ let found = spaces.find(&format!("relay:{MACHINE}")).await.unwrap();
+ assert_eq!(found.name, "studio");
+ assert_eq!(tokens.calls.load(Ordering::SeqCst), calls + 1);
+ let calls = tokens.calls.load(Ordering::SeqCst);
+ spaces.find(&format!("relay:{MACHINE}")).await.unwrap();
+ assert_eq!(tokens.calls.load(Ordering::SeqCst), calls, "max-age hit");
+ for id in ["direct:127.0.0.1:1", "local:nope", "some-name"] {
+ assert_eq!(
+ spaces.find(id).await.unwrap_err().tag(),
+ "not_found",
+ "{id}"
+ );
+ }
+ assert_eq!(tokens.calls.load(Ordering::SeqCst), calls, "non-relay");
+ let second = "abcdef0123456789";
+ cua_host::RelayClient::new(&relay.url)
+ .unwrap()
+ .register(
+ "owner",
+ &cua_host::relay::RegisterRequest {
+ id: second.into(),
+ name: "second".into(),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert!(spaces.find(&format!("relay:{second}")).await.is_ok());
+ assert_eq!(tokens.calls.load(Ordering::SeqCst), calls + 1, "late join");
+ *tokens.current.lock().unwrap() = "bad".into();
+ assert_eq!(
+ spaces
+ .find("relay:ffffffffffffffff")
+ .await
+ .unwrap_err()
+ .tag(),
+ "unauthenticated"
+ );
}
#[tokio::test]