Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/architecture/peer-device-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
41 changes: 37 additions & 4 deletions src/apps/cli/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<T>(current: Option<&Arc<T>>, expected: &Arc<T>) -> bool {
Expand Down Expand Up @@ -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");
Expand Down
2 changes: 2 additions & 0 deletions src/apps/desktop/src/api/remote_connect_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2674,6 +2674,8 @@ async fn connect_route_devices(route: RelayRoute) -> Result<Vec<OnlineDeviceInfo
&relay_url,
&session.token,
&device_name,
// Desktop serves the device ahead of a CLI/daemon on this machine.
openbitfun_core::service::remote_connect::relay_client::DeviceRoutingPriority::Primary,
Arc::new(DesktopHostStreamNotifier(route)),
)
.await
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ pub trait AccountRuntimeHost: Send + Sync {
async fn start_device_routing(&self, request: AccountRoutingStartRequest) -> 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 {
Expand All @@ -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<String>,
}

Expand Down Expand Up @@ -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()),
})
}
Expand Down
5 changes: 4 additions & 1 deletion src/crates/assembly/core/src/service/remote_connect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn host_stream::HostStreamNotifier>,
) -> Result<(
tokio::sync::mpsc::Receiver<relay_client::RelayEvent>,
Expand All @@ -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?;

Expand Down
7 changes: 6 additions & 1 deletion src/crates/interfaces/app-server/src/management/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ fn compute_initial_identity() -> DeviceIdentity {
}
}

fn identity_file_path() -> Result<PathBuf> {
pub(crate) fn identity_file_path() -> Result<PathBuf> {
#[cfg(test)]
{
let override_path = TEST_IDENTITY_PATH.with(|cell| cell.borrow().clone());
Expand Down
Loading
Loading