diff --git a/core/src/message/handlers/mod.rs b/core/src/message/handlers/mod.rs index bad80170c..b5e23a989 100644 --- a/core/src/message/handlers/mod.rs +++ b/core/src/message/handlers/mod.rs @@ -13,13 +13,11 @@ use std::sync::Arc; use async_recursion::async_recursion; use async_trait::async_trait; -use super::CustomMessage; use super::Message; use super::MessagePayload; use crate::dht::vnode::VirtualNode; use crate::dht::Did; use crate::dht::PeerRing; -use crate::error::Error; use crate::error::Result; use crate::message::ConnectNodeReport; use crate::message::ConnectNodeSend; @@ -40,44 +38,6 @@ pub mod subring; /// Type alias for message payload. pub type Payload = MessagePayload; -/// Trait of message callback. -#[cfg_attr(feature = "wasm", async_trait(?Send))] -#[cfg_attr(not(feature = "wasm"), async_trait)] -pub trait MessageCallback { - /// Message handler for custom message - async fn custom_message( - &self, - ctx: &MessagePayload, - msg: &CustomMessage, - ) -> Vec; - /// Message handler for builtin message - async fn builtin_message(&self, ctx: &MessagePayload) -> Vec; -} - -/// Trait of message validator. -#[cfg_attr(feature = "wasm", async_trait(?Send))] -#[cfg_attr(not(feature = "wasm"), async_trait)] -pub trait MessageValidator { - /// Externality validator - async fn validate(&self, ctx: &MessagePayload) -> Option; -} - -/// Boxed Callback, for non-wasm, it should be Sized, Send and Sync. -#[cfg(not(feature = "wasm"))] -pub type CallbackFn = Box; - -/// Boxed Callback -#[cfg(feature = "wasm")] -pub type CallbackFn = Box; - -/// Boxed Validator -#[cfg(not(feature = "wasm"))] -pub type ValidatorFn = Box; - -/// Boxed Validator, for non-wasm, it should be Sized, Send and Sync. -#[cfg(feature = "wasm")] -pub type ValidatorFn = Box; - type NextHop = Did; /// MessageHandlerEvent that will be handled by Swarm. @@ -127,10 +87,6 @@ pub enum MessageHandlerEvent { #[derive(Clone)] pub struct MessageHandler { dht: Arc, - /// CallbackFn implement `customMessage` and `builtin_message`. - callback: Arc>, - /// A specific validator implement ValidatorFn. - validator: Arc>, } /// Generic trait for handle message ,inspired by Actor-Model. @@ -147,47 +103,8 @@ pub trait HandleMsg { impl MessageHandler { /// Create a new MessageHandler Instance. - pub fn new( - dht: Arc, - callback: Option, - validator: Option, - ) -> Self { - Self { - dht, - callback: Arc::new(callback), - validator: Arc::new(validator), - } - } - - /// Invoke callback, which will be call after builtin handler. - async fn invoke_callback(&self, payload: &MessagePayload) -> Vec { - if let Some(ref cb) = *self.callback { - match payload.data { - Message::CustomMessage(ref msg) => { - if self.dht.did == payload.relay.destination { - tracing::debug!("INVOKE CUSTOM MESSAGE CALLBACK {}", &payload.tx_id); - return cb.custom_message(payload, msg).await; - } - } - _ => return cb.builtin_message(payload).await, - }; - } else if let Message::CustomMessage(ref msg) = payload.data { - if self.dht.did == payload.relay.destination { - tracing::warn!("No callback registered, skip invoke_callback of {:?}", msg); - } - } - vec![] - } - - /// Validate message. - async fn validate(&self, payload: &MessagePayload) -> Result<()> { - if let Some(ref v) = *self.validator { - v.validate(payload) - .await - .map(|info| Err(Error::InvalidMessage(info))) - .unwrap_or(Ok(()))?; - }; - Ok(()) + pub fn new(dht: Arc) -> Self { + Self { dht } } /// Handle builtin message. @@ -203,9 +120,7 @@ impl MessageHandler { } tracing::debug!("START HANDLE MESSAGE: {} {}", &payload.tx_id, &payload.data); - self.validate(payload).await?; - - let mut events = match &payload.data { + let events = match &payload.data { Message::JoinDHT(ref msg) => self.handle(payload, msg).await, Message::LeaveDHT(ref msg) => self.handle(payload, msg).await, Message::ConnectNodeSend(ref msg) => self.handle(payload, msg).await, @@ -223,10 +138,6 @@ impl MessageHandler { Message::QueryForTopoInfoReport(ref msg) => self.handle(payload, msg).await, }?; - tracing::debug!("INVOKE CALLBACK {}", &payload.tx_id); - - events.extend(self.invoke_callback(payload).await); - tracing::debug!("FINISH HANDLE MESSAGE {}", &payload.tx_id); Ok(events) } @@ -243,12 +154,13 @@ pub mod tests { use crate::dht::Did; use crate::ecc::SecretKey; use crate::message::PayloadSender; + use crate::swarm::callback::SwarmCallback; use crate::swarm::Swarm; use crate::tests::default::prepare_node_with_callback; use crate::tests::manually_establish_connection; #[derive(Clone)] - struct MessageCallbackInstance { + struct CallbackInstance { #[allow(clippy::type_complexity)] handler_messages: Arc)>>>, } @@ -259,40 +171,34 @@ pub mod tests { let key2 = SecretKey::random(); #[async_trait] - impl MessageCallback for MessageCallbackInstance { - async fn custom_message( + impl SwarmCallback for CallbackInstance { + async fn on_payload( &self, - ctx: &MessagePayload, - msg: &CustomMessage, - ) -> Vec { - self.handler_messages - .lock() - .await - .push((ctx.addr, msg.0.clone())); - println!("{:?}, {:?}, {:?}", ctx, ctx.addr, msg); - vec![] - } + payload: &MessagePayload, + ) -> std::result::Result<(), Box> { + println!("{:?}, {:?}, {:?}", payload, payload.addr, payload.data); + + if let Message::CustomMessage(ref msg) = payload.data { + self.handler_messages + .lock() + .await + .push((payload.addr, msg.0.clone())) + } - async fn builtin_message( - &self, - ctx: &MessagePayload, - ) -> Vec { - println!("{:?}, {:?}", ctx, ctx.addr); - vec![] + Ok(()) } } - let msg_callback1 = MessageCallbackInstance { + let cb1 = CallbackInstance { handler_messages: Arc::new(Mutex::new(vec![])), }; - let msg_callback2 = MessageCallbackInstance { + + let cb2 = CallbackInstance { handler_messages: Arc::new(Mutex::new(vec![])), }; - let cb1: CallbackFn = Box::new(msg_callback1.clone()); - let cb2: CallbackFn = Box::new(msg_callback2.clone()); - let (node1, _path1) = prepare_node_with_callback(key1, Some(cb1)).await; - let (node2, _path2) = prepare_node_with_callback(key2, Some(cb2)).await; + let (node1, _path1) = prepare_node_with_callback(key1, Some(cb1.clone().boxed())).await; + let (node2, _path2) = prepare_node_with_callback(key2, Some(cb2.clone().boxed())).await; manually_establish_connection(&node1, &node2).await; @@ -343,12 +249,12 @@ pub mod tests { sleep(Duration::from_secs(5)).await; - assert_eq!(msg_callback1.handler_messages.lock().await.as_slice(), &[ + assert_eq!(cb1.handler_messages.lock().await.as_slice(), &[ (node2.did(), "Hello world 2 to 1 - 1".as_bytes().to_vec()), (node2.did(), "Hello world 2 to 1 - 2".as_bytes().to_vec()) ]); - assert_eq!(msg_callback2.handler_messages.lock().await.as_slice(), &[ + assert_eq!(cb2.handler_messages.lock().await.as_slice(), &[ (node1.did(), "Hello world 1 to 2 - 1".as_bytes().to_vec()), (node1.did(), "Hello world 1 to 2 - 2".as_bytes().to_vec()), (node1.did(), "Hello world 1 to 2 - 3".as_bytes().to_vec()) diff --git a/core/src/message/mod.rs b/core/src/message/mod.rs index c07ecf4bc..293c27731 100644 --- a/core/src/message/mod.rs +++ b/core/src/message/mod.rs @@ -20,12 +20,9 @@ pub mod handlers; pub use handlers::storage::ChordStorageInterface; pub use handlers::storage::ChordStorageInterfaceCacheChecker; pub use handlers::subring::SubringInterface; -pub use handlers::CallbackFn; pub use handlers::HandleMsg; -pub use handlers::MessageCallback; pub use handlers::MessageHandler; pub use handlers::MessageHandlerEvent; -pub use handlers::ValidatorFn; mod protocols; pub use protocols::MessageRelay; diff --git a/core/src/swarm/builder.rs b/core/src/swarm/builder.rs index fe37d48ef..5378c0f1a 100644 --- a/core/src/swarm/builder.rs +++ b/core/src/swarm/builder.rs @@ -4,21 +4,24 @@ use std::sync::Arc; -use rings_transport::core::callback::Callback; +use rings_transport::core::callback::TransportCallback; use crate::channels::Channel; use crate::dht::PeerRing; -use crate::message::CallbackFn; use crate::message::MessageHandler; -use crate::message::ValidatorFn; use crate::session::SessionSk; use crate::storage::PersistenceStorage; +use crate::swarm::callback::BoxedSwarmCallback; +use crate::swarm::callback::InnerSwarmCallback; use crate::swarm::callback::SwarmCallback; use crate::swarm::MeasureImpl; use crate::swarm::Swarm; use crate::types::channel::Channel as ChannelTrait; use crate::types::Transport; +struct DefaultCallback; +impl SwarmCallback for DefaultCallback {} + /// Creates a SwarmBuilder to configure a Swarm. pub struct SwarmBuilder { ice_servers: String, @@ -28,8 +31,7 @@ pub struct SwarmBuilder { session_sk: SessionSk, session_ttl: Option, measure: Option, - message_callback: Option, - message_validator: Option, + callback: Option, } impl SwarmBuilder { @@ -43,8 +45,7 @@ impl SwarmBuilder { session_sk, session_ttl: None, measure: None, - message_callback: None, - message_validator: None, + callback: None, } } @@ -73,15 +74,9 @@ impl SwarmBuilder { self } - /// Bind message callback function for Swarm. - pub fn message_callback(mut self, callback: CallbackFn) -> Self { - self.message_callback = Some(callback); - self - } - - /// Bind message vilidator function implementation for Swarm. - pub fn message_validator(mut self, validator: ValidatorFn) -> Self { - self.message_validator = Some(validator); + /// Bind callback for Swarm. + pub fn callback(mut self, callback: BoxedSwarmCallback) -> Self { + self.callback = Some(callback); self } @@ -95,12 +90,15 @@ impl SwarmBuilder { self.dht_storage, )); - let message_handler = - MessageHandler::new(dht.clone(), self.message_callback, self.message_validator); + let message_handler = MessageHandler::new(dht.clone()); + let swarm_callback = self.callback.unwrap_or_else(|| DefaultCallback {}.boxed()); let transport_event_channel = Channel::new(); + let transport = Box::new(Transport::new(&self.ice_servers, self.external_address)); - let callback = Arc::new(SwarmCallback::new(transport_event_channel.sender()).boxed()); + let transport_callback = Arc::new( + InnerSwarmCallback::new(transport_event_channel.sender(), swarm_callback).boxed(), + ); Swarm { transport_event_channel, @@ -109,7 +107,7 @@ impl SwarmBuilder { session_sk: self.session_sk, message_handler, transport, - callback, + transport_callback, } } } diff --git a/core/src/swarm/callback.rs b/core/src/swarm/callback.rs index 4dfbb1173..a02b3ce44 100644 --- a/core/src/swarm/callback.rs +++ b/core/src/swarm/callback.rs @@ -1,32 +1,77 @@ use std::str::FromStr; use async_trait::async_trait; -use rings_transport::core::callback::Callback; +use rings_transport::core::callback::TransportCallback; use rings_transport::core::transport::WebrtcConnectionState; use crate::channels::Channel; use crate::dht::Did; +use crate::message::Message; +use crate::message::MessagePayload; use crate::types::channel::Channel as ChannelTrait; use crate::types::channel::TransportEvent; type TransportEventSender = as ChannelTrait>::Sender; +type CallbackError = Box; -pub struct SwarmCallback { +pub enum SwarmEvent { + ConnectionStateChange { + did: Did, + state: WebrtcConnectionState, + }, +} + +/// Any object that implements this trait can be used as a callback for the connection. +#[cfg_attr(feature = "swarm", async_trait(?Send))] +#[cfg_attr(not(feature = "swarm"), async_trait)] +pub trait SwarmCallback { + /// Used to turn object into [BoxedTransportCallback] to be used + /// in [ConnectionCreation](super::transport::ConnectionCreation) + fn boxed(self) -> BoxedSwarmCallback + where Self: Sized + Send + Sync + 'static { + Box::new(self) + } + + /// This method is invoked when a new message is received and before handling. + async fn on_validate(&self, _payload: &MessagePayload) -> Result<(), CallbackError> { + Ok(()) + } + + /// This method is invoked when a new message is received and after handling. + async fn on_payload(&self, _payload: &MessagePayload) -> Result<(), CallbackError> { + Ok(()) + } + + /// This method is invoked after the Swarm handling. + async fn on_event(&self, _event: &SwarmEvent) -> Result<(), CallbackError> { + Ok(()) + } +} + +#[cfg(not(feature = "wasm"))] +pub type BoxedSwarmCallback = Box; + +#[cfg(feature = "wasm")] +pub type BoxedSwarmCallback = Box; + +pub struct InnerSwarmCallback { transport_event_sender: TransportEventSender, + callback: BoxedSwarmCallback, } -impl SwarmCallback { - pub fn new(transport_event_sender: TransportEventSender) -> Self { +impl InnerSwarmCallback { + pub fn new(transport_event_sender: TransportEventSender, callback: BoxedSwarmCallback) -> Self { Self { transport_event_sender, + callback, } } } #[cfg_attr(feature = "wasm", async_trait(?Send))] #[cfg_attr(not(feature = "wasm"), async_trait)] -impl Callback for SwarmCallback { - async fn on_message(&self, _cid: &str, msg: &[u8]) -> Result<(), Box> { +impl TransportCallback for InnerSwarmCallback { + async fn on_message(&self, _cid: &str, msg: &[u8]) -> Result<(), CallbackError> { Channel::send( &self.transport_event_sender, TransportEvent::DataChannelMessage(msg.into()), @@ -39,7 +84,7 @@ impl Callback for SwarmCallback { &self, cid: &str, s: WebrtcConnectionState, - ) -> Result<(), Box> { + ) -> Result<(), CallbackError> { let Ok(did) = Did::from_str(cid) else { tracing::warn!("on_peer_connection_state_change parse did failed: {}", cid); return Ok(()); @@ -56,6 +101,10 @@ impl Callback for SwarmCallback { } _ => Ok(()), } - .map_err(|e| e.into()) + .map_err(Box::new)?; + + self.callback + .on_event(&SwarmEvent::ConnectionStateChange { did, state: s }) + .await } } diff --git a/core/src/swarm/impls.rs b/core/src/swarm/impls.rs index 80f65724f..abae4bd55 100644 --- a/core/src/swarm/impls.rs +++ b/core/src/swarm/impls.rs @@ -143,7 +143,7 @@ impl Swarm { pub async fn new_connection(&self, did: Did) -> Result { let cid = did.to_string(); self.transport - .new_connection(&cid, self.callback.clone()) + .new_connection(&cid, self.transport_callback.clone()) .await .map_err(Error::Transport)?; self.transport.connection(&cid).map_err(|e| e.into()) diff --git a/core/src/swarm/mod.rs b/core/src/swarm/mod.rs index 3460eebc2..fcf55b882 100644 --- a/core/src/swarm/mod.rs +++ b/core/src/swarm/mod.rs @@ -13,7 +13,7 @@ use async_recursion::async_recursion; use async_trait::async_trait; pub use builder::SwarmBuilder; use rings_derive::JudgeConnection; -use rings_transport::core::callback::BoxedCallback; +use rings_transport::core::callback::BoxedTransportCallback; use rings_transport::core::transport::BoxedTransport; use rings_transport::core::transport::ConnectionInterface; use rings_transport::core::transport::TransportMessage; @@ -58,7 +58,7 @@ pub struct Swarm { session_sk: SessionSk, message_handler: MessageHandler, transport: BoxedTransport, - callback: Arc, + transport_callback: Arc, } impl Swarm { diff --git a/core/src/tests/default/mod.rs b/core/src/tests/default/mod.rs index 198cdd368..bff837fb0 100644 --- a/core/src/tests/default/mod.rs +++ b/core/src/tests/default/mod.rs @@ -4,9 +4,9 @@ use crate::dht::Did; use crate::dht::PeerRing; use crate::ecc::SecretKey; use crate::error::Result; -use crate::message::CallbackFn; use crate::session::SessionSk; use crate::storage::PersistenceStorage; +use crate::swarm::callback::BoxedSwarmCallback; use crate::swarm::Swarm; use crate::swarm::SwarmBuilder; @@ -15,7 +15,7 @@ mod test_stabilization; pub async fn prepare_node_with_callback( key: SecretKey, - message_callback: Option, + swarm_callback: Option, ) -> (Arc, String) { let stun = "stun://stun.l.google.com:19302"; let path = PersistenceStorage::random_path("./tmp"); @@ -27,8 +27,8 @@ pub async fn prepare_node_with_callback( let mut swarm_builder = SwarmBuilder::new(stun, storage, session_sk); - if let Some(callback) = message_callback { - swarm_builder = swarm_builder.message_callback(callback); + if let Some(callback) = swarm_callback { + swarm_builder = swarm_builder.callback(callback); } let swarm = Arc::new(swarm_builder.build()); diff --git a/core/src/tests/wasm/test_wasm_transport.rs b/core/src/tests/wasm/test_wasm_transport.rs index 4b58cfc62..83500e1e7 100644 --- a/core/src/tests/wasm/test_wasm_transport.rs +++ b/core/src/tests/wasm/test_wasm_transport.rs @@ -12,7 +12,7 @@ use super::prepare_node; use crate::channels::Channel as CbChannel; use crate::ecc::SecretKey; use crate::error::Result; -use crate::swarm::callback::SwarmCallback; +use crate::swarm::callback::InnerSwarmCallback; use crate::tests::manually_establish_connection; use crate::types::channel::Channel; use crate::types::channel::TransportEvent; @@ -36,7 +36,7 @@ async fn prepare_transport(channel: Option>>) -> T Some(c) => Arc::clone(&c), None => Arc::new( as Channel>::new()), }; - let callback = SwarmCallback::new(ch.sender()).boxed(); + let callback = InnerSwarmCallback::new(ch.sender()).boxed(); let trans = Transport::new("stun://stun.l.google.com:19302", None); trans .new_connection("test", Arc::new(callback)) diff --git a/core/src/types/mod.rs b/core/src/types/mod.rs index d8cd52b60..8e59123cb 100644 --- a/core/src/types/mod.rs +++ b/core/src/types/mod.rs @@ -4,13 +4,17 @@ pub mod channel; use rings_transport::connection_ref::ConnectionRef; +#[cfg(feature = "dummy")] +pub use rings_transport::connections::DummyConnection as ConnectionOwner; +#[cfg(feature = "dummy")] +pub use rings_transport::connections::DummyTransport as Transport; #[cfg(feature = "wasm")] pub use rings_transport::connections::WebSysWebrtcConnection as ConnectionOwner; #[cfg(feature = "wasm")] pub use rings_transport::connections::WebSysWebrtcTransport as Transport; -#[cfg(not(feature = "wasm"))] +#[cfg(all(not(feature = "wasm"), not(feature = "dummy")))] pub use rings_transport::connections::WebrtcConnection as ConnectionOwner; -#[cfg(not(feature = "wasm"))] +#[cfg(all(not(feature = "wasm"), not(feature = "dummy")))] pub use rings_transport::connections::WebrtcTransport as Transport; pub type Connection = ConnectionRef; diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index b1a72a3f7..0e410b7e9 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -1,18 +1,18 @@ use std::sync::Arc; use rings_transport::connection_ref::ConnectionRef; -use rings_transport::core::callback::BoxedCallback; +use rings_transport::core::callback::BoxedTransportCallback; use rings_transport::core::transport::BoxedTransport; use rings_transport::core::transport::ConnectionInterface; pub struct Swarm { transport: BoxedTransport, backend: B, - callback: Arc, + callback: Arc, } pub trait Backend { - fn callback(&self) -> BoxedCallback; + fn callback(&self) -> BoxedTransportCallback; } impl Swarm diff --git a/transport/src/callback.rs b/transport/src/callback.rs index 6b5398081..79a85e36f 100644 --- a/transport/src/callback.rs +++ b/transport/src/callback.rs @@ -1,27 +1,27 @@ -//! This module contains the [InnerCallback] struct. +//! This module contains the [InnerTransportCallback] struct. use std::sync::Arc; use bytes::Bytes; -use crate::core::callback::BoxedCallback; +use crate::core::callback::BoxedTransportCallback; use crate::core::transport::TransportMessage; use crate::core::transport::WebrtcConnectionState; use crate::notifier::Notifier; -/// [InnerCallback] wraps the [BoxedCallback] with inner handling for a specific connection. -pub struct InnerCallback { +/// [InnerTransportCallback] wraps the [BoxedTransportCallback] with inner handling for a specific connection. +pub struct InnerTransportCallback { /// The id of the connection to which the current callback is assigned. pub cid: String, - callback: Arc, + callback: Arc, data_channel_open_notifier: Notifier, } -impl InnerCallback { - /// Create a new [InnerCallback]. +impl InnerTransportCallback { + /// Create a new [InnerTransportCallback]. pub fn new( cid: &str, - callback: Arc, + callback: Arc, data_channel_open_notifier: Notifier, ) -> Self { Self { diff --git a/transport/src/connections/dummy/mod.rs b/transport/src/connections/dummy/mod.rs index 84cce634b..31947d266 100644 --- a/transport/src/connections/dummy/mod.rs +++ b/transport/src/connections/dummy/mod.rs @@ -10,9 +10,9 @@ use rand::distributions::Distribution; use serde::Deserialize; use serde::Serialize; -use crate::callback::InnerCallback; +use crate::callback::InnerTransportCallback; use crate::connection_ref::ConnectionRef; -use crate::core::callback::BoxedCallback; +use crate::core::callback::BoxedTransportCallback; use crate::core::transport::ConnectionInterface; use crate::core::transport::TransportInterface; use crate::core::transport::TransportMessage; @@ -33,7 +33,7 @@ const SEND_MESSAGE_DELAY: bool = true; const CHANNEL_OPEN_DELAY: bool = false; lazy_static! { - static ref CBS: DashMap> = DashMap::new(); + static ref CBS: DashMap> = DashMap::new(); static ref CONNS: DashMap> = DashMap::new(); } @@ -65,11 +65,11 @@ impl DummyConnection { } } - fn callback(&self) -> Arc { + fn callback(&self) -> Arc { CBS.get(&self.cid).unwrap().clone() } - fn remote_callback(&self) -> Arc { + fn remote_callback(&self) -> Arc { let cid = { self.remote_cid.lock().unwrap().clone() }.unwrap(); CBS.get(&cid).unwrap().clone() } @@ -178,7 +178,7 @@ impl TransportInterface for DummyTransport { type Connection = DummyConnection; type Error = Error; - async fn new_connection(&self, cid: &str, callback: Arc) -> Result<()> { + async fn new_connection(&self, cid: &str, callback: Arc) -> Result<()> { if let Ok(existed_conn) = self.pool.connection(cid) { if matches!( existed_conn.webrtc_connection_state(), @@ -196,7 +196,7 @@ impl TransportInterface for DummyTransport { CONNS.insert(cid.to_string(), self.connection(cid)?); CBS.insert( cid.to_string(), - Arc::new(InnerCallback::new(cid, callback, Notifier::default())), + Arc::new(InnerTransportCallback::new(cid, callback, Notifier::default())), ); Ok(()) } diff --git a/transport/src/connections/native_webrtc/mod.rs b/transport/src/connections/native_webrtc/mod.rs index c9760d3f0..109dd9806 100644 --- a/transport/src/connections/native_webrtc/mod.rs +++ b/transport/src/connections/native_webrtc/mod.rs @@ -14,9 +14,9 @@ use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState; use webrtc::peer_connection::sdp::session_description::RTCSessionDescription; use webrtc::peer_connection::RTCPeerConnection; -use crate::callback::InnerCallback; +use crate::callback::InnerTransportCallback; use crate::connection_ref::ConnectionRef; -use crate::core::callback::BoxedCallback; +use crate::core::callback::BoxedTransportCallback; use crate::core::transport::ConnectionInterface; use crate::core::transport::TransportInterface; use crate::core::transport::TransportMessage; @@ -168,7 +168,7 @@ impl TransportInterface for WebrtcTransport { type Connection = WebrtcConnection; type Error = Error; - async fn new_connection(&self, cid: &str, callback: Arc) -> Result<()> { + async fn new_connection(&self, cid: &str, callback: Arc) -> Result<()> { if let Ok(existed_conn) = self.pool.connection(cid) { if matches!( existed_conn.webrtc_connection_state(), @@ -213,7 +213,7 @@ impl TransportInterface for WebrtcTransport { // Set callbacks // let webrtc_data_channel_open_notifier = Notifier::default(); - let inner_cb = Arc::new(InnerCallback::new( + let inner_cb = Arc::new(InnerTransportCallback::new( cid, callback, webrtc_data_channel_open_notifier.clone(), diff --git a/transport/src/connections/web_sys_webrtc/mod.rs b/transport/src/connections/web_sys_webrtc/mod.rs index ed26727c1..b6f82baf8 100644 --- a/transport/src/connections/web_sys_webrtc/mod.rs +++ b/transport/src/connections/web_sys_webrtc/mod.rs @@ -21,9 +21,9 @@ use web_sys::RtcSessionDescription; use web_sys::RtcSessionDescriptionInit; use web_sys::RtcStatsReport; -use crate::callback::InnerCallback; +use crate::callback::InnerTransportCallback; use crate::connection_ref::ConnectionRef; -use crate::core::callback::BoxedCallback; +use crate::core::callback::BoxedTransportCallback; use crate::core::transport::ConnectionInterface; use crate::core::transport::TransportInterface; use crate::core::transport::TransportMessage; @@ -211,7 +211,7 @@ impl TransportInterface for WebSysWebrtcTransport { type Connection = WebSysWebrtcConnection; type Error = Error; - async fn new_connection(&self, cid: &str, callback: Arc) -> Result<()> { + async fn new_connection(&self, cid: &str, callback: Arc) -> Result<()> { if let Ok(existed_conn) = self.pool.connection(cid) { if matches!( existed_conn.webrtc_connection_state(), @@ -241,7 +241,7 @@ impl TransportInterface for WebSysWebrtcTransport { // Set callbacks // let webrtc_data_channel_open_notifier = Notifier::default(); - let inner_cb = Arc::new(InnerCallback::new( + let inner_cb = Arc::new(InnerTransportCallback::new( cid, callback, webrtc_data_channel_open_notifier.clone(), diff --git a/transport/src/core/callback.rs b/transport/src/core/callback.rs index 47246c84a..1f1643c01 100644 --- a/transport/src/core/callback.rs +++ b/transport/src/core/callback.rs @@ -1,9 +1,9 @@ -//! The main entity of this module is the [Callback] trait, which defines +//! The main entity of this module is the [TransportCallback] trait, which defines //! a series of methods that receive connection events. //! //! The `new_connection` method of //! [ConnectionCreation](super::transport::ConnectionCreation) trait will -//! accept boxed [Callback] trait object. +//! accept boxed [TransportCallback] trait object. use async_trait::async_trait; @@ -14,10 +14,10 @@ type CallbackError = Box; /// Any object that implements this trait can be used as a callback for the connection. #[cfg_attr(feature = "web-sys-webrtc", async_trait(?Send))] #[cfg_attr(not(feature = "web-sys-webrtc"), async_trait)] -pub trait Callback { - /// Used to turn object into [BoxedCallback] to be used +pub trait TransportCallback { + /// Used to turn object into [BoxedTransportCallback] to be used /// in [ConnectionCreation](super::transport::ConnectionCreation) - fn boxed(self) -> BoxedCallback + fn boxed(self) -> BoxedTransportCallback where Self: Sized + Send + Sync + 'static { Box::new(self) } @@ -39,12 +39,12 @@ pub trait Callback { /// The `new_connection` method of /// [ConnectionCreation](super::transport::ConnectionCreation) trait will -/// accept boxed [Callback] trait object. +/// accept boxed [TransportCallback] trait object. #[cfg(not(feature = "web-sys-webrtc"))] -pub type BoxedCallback = Box; +pub type BoxedTransportCallback = Box; /// The `new_connection` method of /// [ConnectionCreation](super::transport::ConnectionCreation) trait will -/// accept boxed [Callback] trait object. +/// accept boxed [TransportCallback] trait object. #[cfg(feature = "web-sys-webrtc")] -pub type BoxedCallback = Box; +pub type BoxedTransportCallback = Box; diff --git a/transport/src/core/transport.rs b/transport/src/core/transport.rs index bbd1a0ede..ec6d99194 100644 --- a/transport/src/core/transport.rs +++ b/transport/src/core/transport.rs @@ -12,7 +12,7 @@ use serde::Deserialize; use serde::Serialize; use crate::connection_ref::ConnectionRef; -use crate::core::callback::BoxedCallback; +use crate::core::callback::BoxedTransportCallback; /// Wrapper for the data that is sent over the data channel. #[derive(Deserialize, Serialize, Debug, Clone)] @@ -137,7 +137,7 @@ pub trait TransportInterface { async fn new_connection( &self, cid: &str, - callback: Arc, + callback: Arc, ) -> Result<(), Self::Error>; /// This method closes and releases the connection from transport.