use std::{
collections::{BTreeSet, HashMap},
sync::Mutex,
};
use rho_protocol::{
Caller, ConnectionId, DeviceListParams, DeviceListResponse, DevicePairParams,
DevicePairResponse, DeviceRevokeParams, DeviceRevokeResponse, DeviceService, ErrorCode,
RpcError,
};
use super::{
auth::off_workers,
jobs::unix_now,
mcp_secrets::{open_store, store_error},
};
use crate::app::daemon_http::{
device_pair::{self, PairRefused},
devices,
pairing_codes::DeviceName,
};
#[derive(Default)]
pub(super) struct Devices {
bridged: Mutex<HashMap<ConnectionId, String>>,
}
impl Devices {
fn connected(&self) -> BTreeSet<String> {
self.bridged
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.values()
.cloned()
.collect()
}
}
impl DeviceService for Devices {
fn bridged(&self, caller: &Caller) {
if let Some(device) = caller.bridge_device() {
self.bridged
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(caller.connection, device.to_owned());
}
}
fn left(&self, connection: ConnectionId) {
self.bridged
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.remove(&connection);
}
async fn list(
&self,
caller: Caller,
_: DeviceListParams,
) -> Result<DeviceListResponse, RpcError> {
log_call(&caller, "listed the paired devices");
let connected = self.connected();
let listed = off_workers(move || {
open_store()?;
devices::list(&connected).map_err(store_error)
})
.await?;
let listed = log_failure(&caller, "list the paired devices", listed)?;
Ok(DeviceListResponse::listing(listed)
.with_this_device(caller.bridge_device().map(str::to_owned)))
}
async fn revoke(
&self,
caller: Caller,
params: DeviceRevokeParams,
) -> Result<DeviceRevokeResponse, RpcError> {
let DeviceRevokeParams { name, .. } = params;
let device = name.clone();
let revoked = off_workers(move || {
open_store()?;
devices::revoke(&name).map_err(store_error)
})
.await?;
let revoked = log_failure(&caller, "revoke a device", revoked)?;
tracing::info!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
by_device = ?caller.bridge_device(),
device = %device,
revoked,
"revoked a paired device"
);
Ok(if revoked {
DeviceRevokeResponse::revoked()
} else {
DeviceRevokeResponse::was_not_paired()
})
}
async fn pair(
&self,
caller: Caller,
params: DevicePairParams,
) -> Result<DevicePairResponse, RpcError> {
let DevicePairParams { name, .. } = params;
let chosen = name.is_some();
let answer = mint(name).await;
match &answer {
Ok(_) => tracing::info!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
chosen_name = chosen,
"minted a device pairing code"
),
Err(error) => tracing::warn!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
code = error.code,
why = %error.message,
"could not mint a device pairing code"
),
}
answer
}
}
fn log_call(caller: &Caller, what: &str) {
tracing::info!(
connection = ?caller.connection,
client = ?caller.client.name,
client_version = ?caller.client.version,
by_device = ?caller.bridge_device(),
"{what}"
);
}
fn log_failure<T>(caller: &Caller, what: &str, answer: Result<T, RpcError>) -> Result<T, RpcError> {
if let Err(error) = &answer {
tracing::warn!(
connection = ?caller.connection,
code = error.code,
why = %error.message,
"could not {what}"
);
}
answer
}
async fn mint(name: Option<String>) -> Result<DevicePairResponse, RpcError> {
let name = match name {
Some(name) => DeviceName::chosen(name)
.map_err(|error| RpcError::new(ErrorCode::InvalidParams, format!("{error:#}")))?,
None => DeviceName::FromDevice,
};
off_workers(move || {
open_store()?;
let paired = device_pair::pair(name, unix_now()).map_err(|refused| match refused {
PairRefused::NoBridge(why) => RpcError::new(ErrorCode::BridgeNotSetUp, why),
PairRefused::Failed(error) => store_error(error),
})?;
if paired.pruned > 0 {
tracing::debug!(pruned = paired.pruned, "pruned expired pairing codes");
}
Ok(DevicePairResponse::new(
paired.pairing.to_string(),
paired.expires_at,
))
})
.await?
}