diff --git a/docs/architecture/peer-device-mode.md b/docs/architecture/peer-device-mode.md index a780dc3fec..4c8a6933a8 100644 --- a/docs/architecture/peer-device-mode.md +++ b/docs/architecture/peer-device-mode.md @@ -337,6 +337,16 @@ FS) and must not be mixed with Peer Device Mode. epochs and lifecycle cancellation around `realtime_client`; TypeScript uses `AccountRealtime`. Replacing an account retires its socket and pending replies. Transient disconnection does not destroy the Runtime's tasks or journals. +- The Relay keeps one machine-scoped socket per `device_id`, and every host on a + machine shares `device_identity.json`. Hosts therefore arbitrate locally + (`remote_connect::routing_lease`) instead of replacing each other's socket: + Desktop is the primary host, CLI/TUI/daemon the secondary one. Each holds an + OS file lock per Relay endpoint next to the identity file. A secondary host + connects only while no primary holds its lock, and stands by (`Standby` + connection state) otherwise. The OS releases the lock when a host exits or is + killed, so the standing-by host reconnects within about a second. Hosts of the + same priority take turns. A host built before this change does not + arbitrate. - Relay `rpc-call` routes to the authenticated target's registered method and carries the caller's deadline (120s when omitted). The server checks account membership before routing. Missing acknowledgement after dispatch is an unknown diff --git a/src/apps/cli/src/account.rs b/src/apps/cli/src/account.rs index a2387daa6c..c8a9564829 100644 --- a/src/apps/cli/src/account.rs +++ b/src/apps/cli/src/account.rs @@ -18,8 +18,9 @@ use openbitfun_core::service::remote_connect::account_runtime::{ BackgroundRoutingOwnerRetirementError, }; use openbitfun_core::service::remote_connect::{ - self, encryption, relay_client::RelayClient, relay_client::RelayEvent, session_store, - DeviceIdentity, RemoteServer, + self, encryption, + relay_client::{ConnectionState, DeviceRoutingPriority, RelayClient, RelayEvent}, + session_store, DeviceIdentity, RemoteServer, }; pub(crate) struct CliAccountRuntimeParts { @@ -72,7 +73,12 @@ pub(crate) fn account_snapshot_projection( pub(crate) fn account_login_status_message( result: &openbitfun_core::service::remote_connect::account_runtime::AccountLoginResult, ) -> String { - if result.routing_connected { + if result.routing_standby { + format!( + "Logged in as user {} on {}. Another OpenBitFun host on this machine serves device routing; this one takes over when it exits.", + result.user_id, result.relay_url + ) + } else if result.routing_connected { format!( "Logged in as user {} on {}. Device routing connected.", result.user_id, result.relay_url @@ -173,11 +179,18 @@ impl CliAccountRoutingHost { } self.stop_routing().await; - let (client, mut event_rx) = RelayClient::new(); + // A Desktop host on this machine serves the shared device first; this + // client stands by and takes over once that host exits. + let (client, mut event_rx) = RelayClient::new_device_host(DeviceRoutingPriority::Secondary); client.connect(&request.relay_url).await?; client .connect_authenticated(&request.session.token, &request.device_name) .await?; + if client.connection_state().await == ConnectionState::Standby { + tracing::info!( + "Another OpenBitFun host on this machine serves this device; device routing is standing by" + ); + } let client = Arc::new(client); { let _routing_guard = self.lifecycle.write().await; @@ -706,6 +719,10 @@ impl AccountRuntimeHost for CliAccountRoutingHost { crate::remote_control::retire_daemon_account().await; self.stop_routing().await; } + + async fn device_routing_is_standby(&self) -> bool { + self.connection_state().await == ConnectionState::Standby + } } fn same_routing_client(current: Option<&Arc>, expected: &Arc) -> bool { @@ -883,6 +900,22 @@ mod tests { use super::*; use std::time::Duration; + #[test] + fn standby_login_does_not_claim_connected_routing() { + let result = + openbitfun_core::service::remote_connect::account_runtime::AccountLoginResult { + user_id: "user".into(), + relay_url: "https://relay.example.test".into(), + routing_owner_replaced: false, + routing_connected: false, + routing_standby: true, + routing_error: None, + }; + let message = account_login_status_message(&result); + assert!(message.contains("takes over when it exits"), "{message}"); + assert!(!message.contains("Device routing connected"), "{message}"); + } + #[test] fn stale_routing_loop_cannot_clear_replacement_client() { let stale = Arc::new("stale"); diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 6cd91f4c53..110d06bf3c 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -2674,6 +2674,8 @@ async fn connect_route_devices(route: RelayRoute) -> Result Result<()>; async fn stop_device_routing(&self); + + /// Whether started routing is standing by because another host on this + /// machine serves the shared device on the Relay. + async fn device_routing_is_standby(&self) -> bool { + false + } } pub enum AccountLoginProgress { @@ -74,6 +80,8 @@ pub struct AccountLoginResult { pub relay_url: String, pub routing_owner_replaced: bool, pub routing_connected: bool, + /// Routing started but waits for another local host to release the device. + pub routing_standby: bool, pub routing_error: Option, } @@ -431,12 +439,14 @@ impl AccountRuntime { .await; revoke_replaced_account_context(&client, previous_account_context, &relay_url, &token) .await; + let routing_standby = routing.is_ok() && self.host.device_routing_is_standby().await; Ok(AccountLoginResult { user_id, relay_url, routing_owner_replaced: retired_background_owner, - routing_connected: routing.is_ok(), + routing_connected: routing.is_ok() && !routing_standby, + routing_standby, routing_error: routing.err().map(|error| error.to_string()), }) } diff --git a/src/crates/assembly/core/src/service/remote_connect/mod.rs b/src/crates/assembly/core/src/service/remote_connect/mod.rs index eb883b36c4..f8f16a93c7 100644 --- a/src/crates/assembly/core/src/service/remote_connect/mod.rs +++ b/src/crates/assembly/core/src/service/remote_connect/mod.rs @@ -1016,11 +1016,14 @@ impl RemoteConnectService { /// /// `notifier` delivers host stream hints to subscribed controllers; the host /// adapter owns pairwise encryption and the routing lease, so it supplies it. + /// `priority` decides which host serves this device when several OpenBitFun + /// hosts on the machine share its identity. pub async fn start_device_connection( &self, relay_url: &str, token: &str, device_name: &str, + priority: relay_client::DeviceRoutingPriority, notifier: Arc, ) -> Result<( tokio::sync::mpsc::Receiver, @@ -1031,7 +1034,7 @@ impl RemoteConnectService { // Disconnect previous device connection if any. self.stop_device_connection_inner().await; - let (client, mut event_rx) = RelayClient::new(); + let (client, mut event_rx) = RelayClient::new_device_host(priority); client.connect(relay_url).await?; client.connect_authenticated(token, device_name).await?; diff --git a/src/crates/interfaces/app-server/src/management/owner.rs b/src/crates/interfaces/app-server/src/management/owner.rs index e379acd636..7b5d2a8c96 100644 --- a/src/crates/interfaces/app-server/src/management/owner.rs +++ b/src/crates/interfaces/app-server/src/management/owner.rs @@ -1774,7 +1774,12 @@ fn project_account_snapshot( fn account_login_status_message( result: &openbitfun_core::service::remote_connect::account_runtime::AccountLoginResult, ) -> String { - if result.routing_connected { + if result.routing_standby { + format!( + "Logged in as user {} on {}. Another OpenBitFun host on this machine serves device routing; this one takes over when it exits.", + result.user_id, result.relay_url + ) + } else if result.routing_connected { format!( "Logged in as user {} on {}. Device routing connected.", result.user_id, result.relay_url diff --git a/src/crates/services/services-integrations/src/remote_connect.rs b/src/crates/services/services-integrations/src/remote_connect.rs index 374fe0a517..3f1bc7cf9f 100644 --- a/src/crates/services/services-integrations/src/remote_connect.rs +++ b/src/crates/services/services-integrations/src/remote_connect.rs @@ -27,6 +27,7 @@ mod realtime_payload; pub mod relay_client; pub mod relay_failure; mod relay_http; +pub mod routing_lease; pub mod rpc_execution; pub mod session_records; pub mod session_store; @@ -70,6 +71,7 @@ pub use page_upload::{ pub use pairing::PairingState; pub use qr_generator::QrGenerator; pub use relay_client::{ensure_rustls_crypto_provider, ConnectionState, RelayClient, RelayEvent}; +pub use routing_lease::DeviceRoutingPriority; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; diff --git a/src/crates/services/services-integrations/src/remote_connect/device.rs b/src/crates/services/services-integrations/src/remote_connect/device.rs index 71b274af5c..dc901e393f 100644 --- a/src/crates/services/services-integrations/src/remote_connect/device.rs +++ b/src/crates/services/services-integrations/src/remote_connect/device.rs @@ -213,7 +213,7 @@ fn compute_initial_identity() -> DeviceIdentity { } } -fn identity_file_path() -> Result { +pub(crate) fn identity_file_path() -> Result { #[cfg(test)] { let override_path = TEST_IDENTITY_PATH.with(|cell| cell.borrow().clone()); diff --git a/src/crates/services/services-integrations/src/remote_connect/relay_client.rs b/src/crates/services/services-integrations/src/remote_connect/relay_client.rs index 1c846c6369..d66ef5657b 100644 --- a/src/crates/services/services-integrations/src/remote_connect/relay_client.rs +++ b/src/crates/services/services-integrations/src/remote_connect/relay_client.rs @@ -2,6 +2,8 @@ //! Socket.IO owns framing, heartbeat and RPC acks. This owner supplies account //! epochs, bounded delivery, method registration and reconnect policy. use super::realtime_client::{Incoming, JsonAck, RealtimeConnection, RealtimeSender}; +pub use super::routing_lease::DeviceRoutingPriority; +use super::routing_lease::{RoutingLease, RoutingLeasePaths}; use anyhow::{anyhow, bail, Result}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -14,6 +16,9 @@ use std::{ use tokio::sync::{mpsc, oneshot}; pub const RELAY_INBOUND_IDLE_TIMEOUT: Duration = Duration::from_secs(60); +/// How long a primary host waits for another primary host on this device to +/// release routing before its first connection fails. +const PRIMARY_ROUTING_WAIT: Duration = Duration::from_secs(10); pub fn ensure_rustls_crypto_provider() { openbitfun_services_core::tls_provider::ensure_ring_crypto_provider(); @@ -101,6 +106,14 @@ pub enum ConnectionState { Connecting, Connected, Reconnecting, + /// Another OpenBitFun host on this machine serves the same device on this + /// Relay. The client connects by itself once that host releases routing. + Standby, +} +enum RoutingTurn { + Proceed, + Unarbitrated, + Exit, } struct Reply { id: AckId, @@ -134,15 +147,28 @@ pub struct RelayClient { owner: Arc>, events: mpsc::Sender, machine: bool, + routing: Option, + #[cfg(test)] + routing_dir: Option, } impl RelayClient { + /// Machine-scoped client without host-local arbitration. pub fn new() -> (Self, mpsc::Receiver) { - Self::with_role(true) + Self::with_role(true, None) + } + /// Machine-scoped client for a product host that serves this device. Hosts + /// sharing the device identity take turns by `priority` instead of + /// replacing each other's socket on the Relay. + pub fn new_device_host(priority: DeviceRoutingPriority) -> (Self, mpsc::Receiver) { + Self::with_role(true, Some(priority)) } pub fn new_controller() -> (Self, mpsc::Receiver) { - Self::with_role(false) + Self::with_role(false, None) } - fn with_role(machine: bool) -> (Self, mpsc::Receiver) { + fn with_role( + machine: bool, + routing: Option, + ) -> (Self, mpsc::Receiver) { let (events, receiver) = mpsc::channel(128); ( Self { @@ -156,10 +182,29 @@ impl RelayClient { })), events, machine, + routing, + #[cfg(test)] + routing_dir: None, }, receiver, ) } + fn routing_lease(&self, url: &str) -> Option { + let priority = self.routing?; + #[cfg(test)] + if let Some(dir) = &self.routing_dir { + return Some(RoutingLease::new(RoutingLeasePaths::in_dir( + dir, url, priority, + ))); + } + match RoutingLeasePaths::for_relay(url, priority) { + Ok(paths) => Some(RoutingLease::new(paths)), + Err(error) => { + log::warn!("Relay routing arbitration unavailable; connecting without it: {error}"); + None + } + } + } pub async fn connection_state(&self) -> ConnectionState { self.owner.lock().unwrap().state.clone() } @@ -190,6 +235,7 @@ impl RelayClient { let epoch = owner.epoch; owner.sender = None; owner.replies.clear(); + let lease = self.routing_lease(&url); owner.task = Some(tokio::spawn(Self::run( self.owner.clone(), self.events.clone(), @@ -197,6 +243,7 @@ impl RelayClient { url, token.to_owned(), self.machine, + lease, ready, ))); epoch @@ -232,6 +279,8 @@ impl RelayClient { url: String, token: String, machine: bool, + // Moved into this task: dropping it releases routing to the next host. + mut lease: Option, ready: oneshot::Sender>, ) { // Every exit (including abort/panic) relinquishes this epoch's sender @@ -242,11 +291,20 @@ impl RelayClient { }; let mut ready = Some(ready); let mut delay = Duration::from_secs(1); + let mut connected_once = false; loop { + if let Some(active) = lease.as_mut() { + match Self::wait_for_routing_turn(&owner, epoch, active, &mut ready).await { + RoutingTurn::Proceed => {} + RoutingTurn::Unarbitrated => lease = None, + RoutingTurn::Exit => return, + } + } let connection = RealtimeConnection::connect(&url, &token, machine).await; match connection { Ok(mut connection) => { - let first = ready.is_some(); + let first = !connected_once; + connected_once = true; { let mut state = owner.lock().unwrap(); if state.epoch != epoch { @@ -328,6 +386,72 @@ impl RelayClient { delay = (delay * 2).min(Duration::from_secs(5)); } } + /// Hold back (re)connection while a host of higher or equal priority on + /// this machine serves the device; connecting anyway would only replace its + /// socket on the Relay and be replaced in turn. + async fn wait_for_routing_turn( + owner: &Arc>, + epoch: u64, + lease: &mut RoutingLease, + ready: &mut Option>>, + ) -> RoutingTurn { + let started = Instant::now(); + let mut standing_by = false; + loop { + match lease.may_connect() { + Ok(true) => { + if standing_by { + log::info!("Relay routing released by another OpenBitFun host; connecting"); + } + return RoutingTurn::Proceed; + } + Ok(false) => {} + Err(error) => { + log::warn!("Relay routing arbitration failed; connecting without it: {error}"); + return RoutingTurn::Unarbitrated; + } + } + let primary = lease.priority() == DeviceRoutingPriority::Primary; + if primary && ready.is_some() { + // An interactive host reports contention instead of hanging; + // the brief wait covers a restarting process and the momentary + // probe of a standing-by secondary host. + if started.elapsed() >= PRIMARY_ROUTING_WAIT { + if let Some(ready) = ready.take() { + let _ = ready.send(Err(anyhow!( + "Another OpenBitFun Desktop on this machine already serves this device on the Relay" + ))); + } + return RoutingTurn::Exit; + } + } else if !standing_by { + standing_by = true; + log::info!( + "Another OpenBitFun host on this machine serves this device on the Relay; standing by until it exits" + ); + { + let mut state = owner.lock().unwrap(); + if state.epoch != epoch { + return RoutingTurn::Exit; + } + state.state = ConnectionState::Standby; + } + // A background host is started successfully; it takes over later. + if let Some(ready) = ready.take() { + let _ = ready.send(Ok(())); + } + } + if owner.lock().unwrap().epoch != epoch { + return RoutingTurn::Exit; + } + let poll = if primary { + Duration::from_millis(200) + } else { + Duration::from_secs(1) + }; + tokio::time::sleep(poll).await; + } + } async fn route( owner: &Arc>, events: &mpsc::Sender, @@ -596,6 +720,76 @@ mod tests { assert_eq!(aliased.device_client_protocol, Some(2)); } + fn arbitrated_client( + priority: DeviceRoutingPriority, + dir: &std::path::Path, + ) -> (RelayClient, mpsc::Receiver) { + let (mut client, events) = RelayClient::new_device_host(priority); + client.routing_dir = Some(dir.to_path_buf()); + (client, events) + } + + #[tokio::test] + async fn secondary_host_stands_by_until_the_primary_host_exits() { + let dir = tempfile::tempdir().unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let mut desktop = RoutingLease::new(RoutingLeasePaths::in_dir( + dir.path(), + &url, + DeviceRoutingPriority::Primary, + )); + assert!(desktop.may_connect().unwrap()); + + let (client, _events) = arbitrated_client(DeviceRoutingPriority::Secondary, dir.path()); + client.connect(&url).await.unwrap(); + // A background host starts successfully without touching the Relay, + // where it would only replace the primary host's socket. + client + .connect_authenticated("test-token", "Host") + .await + .unwrap(); + assert_eq!(client.connection_state().await, ConnectionState::Standby); + assert!( + tokio::time::timeout(Duration::from_millis(1500), listener.accept()) + .await + .is_err() + ); + + drop(desktop); + tokio::time::timeout(Duration::from_secs(5), listener.accept()) + .await + .expect("the secondary host must connect once the primary host exits") + .unwrap(); + client.disconnect().await; + } + + #[tokio::test] + async fn primary_host_connects_while_a_secondary_host_holds_routing() { + let dir = tempfile::tempdir().unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let mut daemon = RoutingLease::new(RoutingLeasePaths::in_dir( + dir.path(), + &url, + DeviceRoutingPriority::Secondary, + )); + assert!(daemon.may_connect().unwrap()); + + let (client, _events) = arbitrated_client(DeviceRoutingPriority::Primary, dir.path()); + client.connect(&url).await.unwrap(); + let connecting = tokio::spawn(async move { + let _ = client.connect_authenticated("test-token", "Host").await; + }); + tokio::time::timeout(Duration::from_secs(2), listener.accept()) + .await + .expect("a primary host must not wait for a secondary host") + .unwrap(); + // The secondary host yields once the Relay replaces its socket. + assert!(!daemon.may_connect().unwrap()); + connecting.abort(); + } + #[tokio::test] async fn base_endpoint_preserves_proxy_prefix_without_legacy_ws_conversion() { let (client, _events) = super::RelayClient::new(); diff --git a/src/crates/services/services-integrations/src/remote_connect/routing_lease.rs b/src/crates/services/services-integrations/src/remote_connect/routing_lease.rs new file mode 100644 index 0000000000..bc64ab482d --- /dev/null +++ b/src/crates/services/services-integrations/src/remote_connect/routing_lease.rs @@ -0,0 +1,212 @@ +//! Host-local arbitration of one device's machine-scoped Relay socket. +//! +//! Every OpenBitFun host on a machine shares `device_identity.json`, and the +//! Relay keeps only the newest machine socket per `device_id`. Two hosts that +//! both reconnect would therefore replace each other indefinitely. A host holds +//! an OS advisory lock for its priority tier while it owns routing; the OS +//! releases it when the process exits, crashes or is killed, so no stale owner +//! record survives and the Relay protocol is unchanged. +//! +//! - [`DeviceRoutingPriority::Primary`] (Desktop) connects whenever it holds the +//! primary lock and never yields to a secondary host. +//! - [`DeviceRoutingPriority::Secondary`] (CLI, TUI, daemon) connects only while +//! it holds the secondary lock and no primary host holds the primary lock. It +//! stands by otherwise and resumes once the primary host exits or signs out. +//! +//! Locks are keyed by Relay endpoint: sockets on different Relays do not +//! replace each other. + +use std::fs::{File, OpenOptions}; +use std::io; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use fs2::FileExt; +use sha2::{Digest, Sha256}; + +/// Which host serves the shared device identity when several run at once. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeviceRoutingPriority { + /// Interactive Desktop host. Takes the device socket over from a secondary host. + Primary, + /// CLI, TUI or daemon host. Serves the device only while no primary host does. + Secondary, +} + +#[derive(Debug, Clone)] +pub(crate) struct RoutingLeasePaths { + priority: DeviceRoutingPriority, + own: PathBuf, + primary: PathBuf, +} + +impl RoutingLeasePaths { + /// Lock files live next to the device identity: hosts that share it are + /// exactly the hosts that authenticate as the same device. + pub(crate) fn for_relay(relay_url: &str, priority: DeviceRoutingPriority) -> Result { + let identity = super::device::identity_file_path()?; + let dir = identity + .parent() + .map(Path::to_path_buf) + .unwrap_or_default() + .join("relay-routing"); + Ok(Self::in_dir(&dir, relay_url, priority)) + } + + pub(crate) fn in_dir(dir: &Path, relay_url: &str, priority: DeviceRoutingPriority) -> Self { + let digest = Sha256::digest(relay_url.trim_end_matches('/').as_bytes()); + let key = hex::encode(&digest[..8]); + let primary = dir.join(format!("{key}.primary.lock")); + let own = match priority { + DeviceRoutingPriority::Primary => primary.clone(), + DeviceRoutingPriority::Secondary => dir.join(format!("{key}.secondary.lock")), + }; + Self { + priority, + own, + primary, + } + } +} + +/// One host's claim on routing for a Relay endpoint. Dropping it releases the +/// claim so the next host in line can connect. +pub(crate) struct RoutingLease { + paths: RoutingLeasePaths, + held: Option, +} + +impl RoutingLease { + pub(crate) fn new(paths: RoutingLeasePaths) -> Self { + Self { paths, held: None } + } + + pub(crate) fn priority(&self) -> DeviceRoutingPriority { + self.paths.priority + } + + /// Whether this host may (re)connect now. The own-tier lock is kept once + /// acquired, so a standing-by secondary host remains the designated + /// successor instead of racing other secondary hosts. + pub(crate) fn may_connect(&mut self) -> io::Result { + if self.held.is_none() { + let file = open_lock_file(&self.paths.own)?; + if !try_lock(&file, true)? { + return Ok(false); + } + self.held = Some(file); + } + match self.paths.priority { + DeviceRoutingPriority::Primary => Ok(true), + DeviceRoutingPriority::Secondary => primary_is_free(&self.paths.primary), + } + } +} + +fn open_lock_file(path: &Path) -> io::Result { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(path) +} + +fn try_lock(file: &File, exclusive: bool) -> io::Result { + let result = if exclusive { + FileExt::try_lock_exclusive(file) + } else { + FileExt::try_lock_shared(file) + }; + match result { + Ok(()) => Ok(true), + Err(error) if error.raw_os_error() == fs2::lock_contended_error().raw_os_error() => { + Ok(false) + } + Err(error) => Err(error), + } +} + +/// A shared probe conflicts only with a primary host's exclusive lock. A +/// primary host that loses this momentary race retries its acquisition. +fn primary_is_free(path: &Path) -> io::Result { + let file = open_lock_file(path)?; + if !try_lock(&file, false)? { + return Ok(false); + } + let _ = FileExt::unlock(&file); + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + + const RELAY: &str = "https://relay.example.test/v1"; + + fn lease(dir: &Path, relay_url: &str, priority: DeviceRoutingPriority) -> RoutingLease { + RoutingLease::new(RoutingLeasePaths::in_dir(dir, relay_url, priority)) + } + + #[test] + fn primary_host_preempts_a_connected_secondary_host() { + let dir = tempfile::tempdir().unwrap(); + let mut cli = lease(dir.path(), RELAY, DeviceRoutingPriority::Secondary); + assert!(cli.may_connect().unwrap()); + + let mut desktop = lease(dir.path(), RELAY, DeviceRoutingPriority::Primary); + assert!(desktop.may_connect().unwrap()); + assert!(!cli.may_connect().unwrap()); + } + + #[test] + fn secondary_host_resumes_after_the_primary_host_exits() { + let dir = tempfile::tempdir().unwrap(); + let mut desktop = lease(dir.path(), RELAY, DeviceRoutingPriority::Primary); + assert!(desktop.may_connect().unwrap()); + + let mut daemon = lease(dir.path(), RELAY, DeviceRoutingPriority::Secondary); + assert!(!daemon.may_connect().unwrap()); + // The standing-by host keeps its tier, so another CLI cannot jump ahead. + let mut other_cli = lease(dir.path(), RELAY, DeviceRoutingPriority::Secondary); + assert!(!other_cli.may_connect().unwrap()); + + drop(desktop); + assert!(daemon.may_connect().unwrap()); + assert!(!other_cli.may_connect().unwrap()); + } + + #[test] + fn hosts_of_the_same_priority_take_turns() { + let dir = tempfile::tempdir().unwrap(); + let mut first = lease(dir.path(), RELAY, DeviceRoutingPriority::Primary); + let mut second = lease(dir.path(), RELAY, DeviceRoutingPriority::Primary); + assert!(first.may_connect().unwrap()); + assert!(!second.may_connect().unwrap()); + drop(first); + assert!(second.may_connect().unwrap()); + } + + #[test] + fn different_relays_do_not_contend() { + let dir = tempfile::tempdir().unwrap(); + let mut desktop = lease(dir.path(), RELAY, DeviceRoutingPriority::Primary); + assert!(desktop.may_connect().unwrap()); + let mut lan_cli = lease( + dir.path(), + "http://192.168.1.2:9700", + DeviceRoutingPriority::Secondary, + ); + assert!(lan_cli.may_connect().unwrap()); + // A trailing slash names the same endpoint. + let mut cli = lease( + dir.path(), + &format!("{RELAY}/"), + DeviceRoutingPriority::Secondary, + ); + assert!(!cli.may_connect().unwrap()); + } +}