From 9a9f3d301532e941543944ac4d6e500ce26f8e97 Mon Sep 17 00:00:00 2001 From: Nasr Date: Wed, 24 Jan 2024 12:46:44 -0500 Subject: [PATCH] refactor: review changes --- crates/torii/libp2p/Cargo.toml | 2 +- crates/torii/libp2p/src/client/mod.rs | 22 ++++++++-------- crates/torii/libp2p/src/server/mod.rs | 36 +++++++++++++++++---------- crates/torii/libp2p/src/tests.rs | 14 +++++------ 4 files changed, 43 insertions(+), 31 deletions(-) diff --git a/crates/torii/libp2p/Cargo.toml b/crates/torii/libp2p/Cargo.toml index fc3a11d531..b167a151eb 100644 --- a/crates/torii/libp2p/Cargo.toml +++ b/crates/torii/libp2p/Cargo.toml @@ -2,7 +2,7 @@ edition.workspace = true license-file.workspace = true license.workspace = true -name = "torii-libp2p" +name = "torii-relay" repository.workspace = true version.workspace = true diff --git a/crates/torii/libp2p/src/client/mod.rs b/crates/torii/libp2p/src/client/mod.rs index 79c00577ab..1957bc74d4 100644 --- a/crates/torii/libp2p/src/client/mod.rs +++ b/crates/torii/libp2p/src/client/mod.rs @@ -22,7 +22,7 @@ pub struct Behaviour { ping: ping::Behaviour, } -pub struct Libp2pClient { +pub struct RelayClient { pub command_sender: Sender, pub message_receiver: Receiver, pub event_loop: EventLoop, @@ -42,13 +42,13 @@ pub enum Command { Publish(ClientMessage), } -impl Libp2pClient { +impl RelayClient { #[cfg(not(target_arch = "wasm32"))] pub fn new(relay_addr: String) -> Result { let local_key = identity::Keypair::generate_ed25519(); let peer_id = PeerId::from(local_key.public()); - info!("Local peer id: {:?}", peer_id); + info!(target: "torii::relay::client", peer_id = %peer_id, "Local peer id"); let mut swarm = libp2p::SwarmBuilder::with_existing_identity(local_key) .with_tokio() @@ -76,7 +76,7 @@ impl Libp2pClient { .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(60))) .build(); - info!("Dialing relay: {:?}", relay_addr); + info!(target: "torii::relay::client", addr = %relay_addr, "Dialing relay"); swarm.dial(relay_addr.parse::()?)?; let (message_sender, message_receiver) = futures::channel::mpsc::channel(0); @@ -93,7 +93,7 @@ impl Libp2pClient { let local_key = identity::Keypair::generate_ed25519(); let peer_id = PeerId::from(local_key.public()); - info!("Local peer id: {:?}", peer_id); + info!(target: "torii::relay::client", peer_id = %peer_id, "Local peer id"); let mut swarm = libp2p::SwarmBuilder::with_existing_identity(local_key) .with_wasm_bindgen() @@ -123,7 +123,7 @@ impl Libp2pClient { .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(60))) .build(); - info!("Dialing relay: {:?}", relay_addr); + info!(target: "torii::relay::client", addr = %relay_addr, "Dialing relay"); swarm.dial(relay_addr.parse::()?)?; let (message_sender, message_receiver) = futures::channel::mpsc::channel(0); @@ -171,14 +171,16 @@ impl EventLoop { } } SwarmEvent::ConnectionClosed { cause: Some(cause), .. } => { - tracing::info!("Swarm event: {:?}", cause); + info!(target: "torii::relay::client", cause = ?cause, "Connection closed"); if let libp2p::swarm::ConnectionError::KeepAliveTimeout = cause { - tracing::info!("Keep alive timeout, shutting down"); - // return; + info!(target: "torii::relay::client", "Connection closed due to keep alive timeout. Shutting down client."); + return; } } - evt => tracing::info!("Swarm event: {:?}", evt), + evt => { + info!(target: "torii::relay::client", event = ?evt, "Unhandled event"); + } } }, } diff --git a/crates/torii/libp2p/src/server/mod.rs b/crates/torii/libp2p/src/server/mod.rs index b0fb16a861..92e413c999 100644 --- a/crates/torii/libp2p/src/server/mod.rs +++ b/crates/torii/libp2p/src/server/mod.rs @@ -33,11 +33,11 @@ pub struct Behaviour { gossipsub: gossipsub::Behaviour, } -pub struct Libp2pRelay { +pub struct Relay { swarm: Swarm, } -impl Libp2pRelay { +impl Relay { pub fn new( port: u16, port_webrtc: u16, @@ -136,9 +136,12 @@ impl Libp2pRelay { .expect("Failed to deserialize message"); info!( - "Received message {:?} from peer {:?} with topic {:?} and data \ - {:?}", - message_id, peer_id, message.topic, message.data + target: "torii::relay::server", + message_id = %message_id, + peer_id = %peer_id, + topic = %message.topic, + data = %String::from_utf8_lossy(&message.data), + "Received message" ); // forward message to room @@ -160,19 +163,26 @@ impl Libp2pRelay { peer_id, }) => { info!( - "Received identify event from peer {:?} with observed address {:?}", - peer_id, observed_addr + target: "torii::relay::server", + peer_id = %peer_id, + observed_addr = %observed_addr, + "Received identify event" ); self.swarm.add_external_address(observed_addr.clone()); } ServerEvent::Ping(ping::Event { peer, result, .. }) => { - info!("Ping success from peer {:?} with result {:?}", peer, result); + info!( + target: "torii::relay::server", + peer_id = %peer, + result = ?result, + "Received ping event" + ); } _ => {} } } SwarmEvent::NewListenAddr { address, .. } => { - info!("Listening on {:?}", address); + info!(target: "torii::relay::server", address = %address, "New listen address"); } _ => {} } @@ -184,7 +194,7 @@ fn read_or_create_identity(path: &Path) -> anyhow::Result { if path.exists() { let bytes = fs::read(path)?; - info!("Using existing identity from {}", path.display()); + info!(target: "torii::relay::server", path = %path.display(), "Using existing identity"); return Ok(identity::Keypair::from_protobuf_encoding(&bytes)?); // This only works for ed25519 but that is what we are using. } @@ -193,7 +203,7 @@ fn read_or_create_identity(path: &Path) -> anyhow::Result { fs::write(path, identity.to_protobuf_encoding()?)?; - info!("Generated new identity and wrote it to {}", path.display()); + info!(target: "torii::relay::server", path = %path.display(), "Generated new identity"); Ok(identity) } @@ -202,7 +212,7 @@ fn read_or_create_certificate(path: &Path) -> anyhow::Result { if path.exists() { let pem = fs::read_to_string(path)?; - info!("Using existing certificate from {}", path.display()); + info!(target: "torii::relay::server", path = %path.display(), "Using existing certificate"); return Ok(Certificate::from_pem(&pem)?); } @@ -210,7 +220,7 @@ fn read_or_create_certificate(path: &Path) -> anyhow::Result { let cert = Certificate::generate(&mut rand::thread_rng())?; fs::write(path, cert.serialize_pem().as_bytes())?; - info!("Generated new certificate and wrote it to {}", path.display()); + info!(target: "torii::relay::server", path = %path.display(), "Generated new certificate"); Ok(cert) } diff --git a/crates/torii/libp2p/src/tests.rs b/crates/torii/libp2p/src/tests.rs index d6fe2848a0..4fe98b189b 100644 --- a/crates/torii/libp2p/src/tests.rs +++ b/crates/torii/libp2p/src/tests.rs @@ -4,7 +4,7 @@ mod test { use futures::{SinkExt, StreamExt}; - use crate::client::{Command, Libp2pClient}; + use crate::client::{Command, RelayClient}; use crate::types::ClientMessage; #[cfg(target_arch = "wasm32")] @@ -21,17 +21,17 @@ mod test { use tokio::time::sleep; use tokio::{self, select}; - use crate::server::Libp2pRelay; + use crate::server::Relay; - let _ = tracing_subscriber::fmt().with_env_filter("torii_libp2p=debug").try_init(); + let _ = tracing_subscriber::fmt().with_env_filter("torii::relay::client=debug,torii::relay::server=debug").try_init(); // Initialize the relay server - let mut relay_server: Libp2pRelay = Libp2pRelay::new(9090, 9091, None, None)?; + let mut relay_server: Relay = Relay::new(9090, 9091, None, None)?; tokio::spawn(async move { relay_server.run().await; }); // Initialize the first client (listener) - let mut client = Libp2pClient::new("/ip4/127.0.0.1/tcp/9090".to_string())?; + let mut client = RelayClient::new("/ip4/127.0.0.1/tcp/9090".to_string())?; tokio::spawn(async move { client.event_loop.run().await; }); @@ -76,9 +76,9 @@ mod test { let _ = tracing_subscriber::fmt().with_env_filter("torii_libp2p=debug").try_init(); // Initialize the first client (listener) // Make sure the cert hash is correct - corresponding to the cert in the relay server - let mut client = Libp2pClient::new( + let mut client = RelayClient::new( "/ip4/127.0.0.1/udp/9091/webrtc-direct/certhash/\ - uEiBDKAUMioKpVK2CLQjtOL9eLPmaJkTcPPbBMtau7XaPGA" + uEiD6v3wzt8XU3s3SqgNSBJPvn9E0VMVFm8-G0iSEsIIDxw" .to_string(), )?;