handle.rs
1 use std::sync::Arc; 2 3 use dashmap::DashMap; 4 use distrox_network::connection::runner::Blocklist; 5 use iroh::EndpointAddr; 6 use iroh::EndpointId; 7 use tokio_util::sync::CancellationToken; 8 9 use crate::command::InstanceCommand; 10 use crate::error::Error; 11 12 #[derive(Clone)] 13 pub struct InstanceHandle { 14 pub(crate) connections: Arc<DashMap<EndpointId, distrox_network::connection::ConnectionHandle>>, 15 pub(crate) endpoint_id: EndpointId, 16 pub(crate) endpoint_addr: EndpointAddr, 17 pub(crate) sender: tokio::sync::mpsc::Sender<InstanceCommand>, 18 pub(crate) blocklist: Blocklist, 19 pub(crate) instance_cancellation_token: CancellationToken, 20 } 21 22 impl InstanceHandle { 23 pub async fn wait_online(&self) -> Result<(), Error> { 24 let (sender, recv) = tokio::sync::oneshot::channel(); 25 if self 26 .sender 27 .send(InstanceCommand::WaitOnline(sender)) 28 .await 29 .is_err() 30 { 31 tracing::error!("Internal channel error"); 32 } 33 recv.await.map_err(|_| Error::InternalChannelError)?; 34 Ok(()) 35 } 36 37 /// Connect to a remote instance 38 /// 39 /// # Warning 40 /// 41 /// See [Instance::connect_to]. 42 pub async fn connect_to( 43 &self, 44 target: EndpointAddr, 45 services: distrox_network::connection::Services, 46 ) -> Result<distrox_network::connection::ConnectionHandle, Error> { 47 let (result_sender, result_recv) = tokio::sync::oneshot::channel(); 48 if self 49 .sender 50 .send(InstanceCommand::ConnectTo { 51 target, 52 result_sender, 53 services, 54 }) 55 .await 56 .is_err() 57 { 58 tracing::error!("Internal channel error"); 59 } 60 61 result_recv.await.map_err(|_| Error::InternalChannelError)? 62 } 63 64 pub async fn shutdown(&self) -> Result<(), Error> { 65 let (result_sender, result_recv) = tokio::sync::oneshot::channel(); 66 if self 67 .sender 68 .send(InstanceCommand::Shutdown(result_sender)) 69 .await 70 .is_err() 71 { 72 tracing::error!("Internal channel error"); 73 } 74 result_recv.await.map_err(|_| Error::InternalChannelError) 75 } 76 77 pub fn endpoint_id(&self) -> iroh::PublicKey { 78 self.endpoint_id 79 } 80 81 pub fn endpoint_address(&self) -> &EndpointAddr { 82 &self.endpoint_addr 83 } 84 85 pub fn connections( 86 &self, 87 ) -> Arc<DashMap<EndpointId, distrox_network::connection::ConnectionHandle>> { 88 self.connections.clone() 89 } 90 91 pub fn blocklist(&self) -> Blocklist { 92 self.blocklist.clone() 93 } 94 95 pub fn instance_cancellation_token(&self) -> &CancellationToken { 96 &self.instance_cancellation_token 97 } 98 }