diff --git a/pr/3073/docs/src/iroh_relay/server/client_conn.rs.html b/pr/3073/docs/src/iroh_relay/server/client_conn.rs.html index 448bc7c14b..ecf65ed4db 100644 --- a/pr/3073/docs/src/iroh_relay/server/client_conn.rs.html +++ b/pr/3073/docs/src/iroh_relay/server/client_conn.rs.html @@ -672,7 +672,51 @@ 671 672 673 -674
//! The server-side representation of an ongoing client relaying connection.
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
+685
+686
+687
+688
+689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
//! The server-side representation of an ongoing client relaying connection.
 
 use std::{future::Future, num::NonZeroU32, pin::Pin, sync::Arc, task::Poll, time::Duration};
 
@@ -705,6 +749,9 @@
     pub(super) data: Bytes,
 }
 
+/// Number of times we try to send to a client connection before dropping the data;
+const RETRIES: usize = 3;
+
 /// Configuration for a [`ClientConn`].
 #[derive(Debug)]
 pub(super) struct ClientConnConfig {
@@ -721,29 +768,27 @@
 /// [`Client`]: crate::client::Client
 #[derive(Debug)]
 pub(super) struct ClientConn {
-    /// Unique counter, incremented each time we accept a new connection.
-    pub(super) conn_num: usize,
     /// Identity of the connected peer.
-    pub(super) key: NodeId,
+    node_id: NodeId,
     /// Used to close the connection loop.
     done: CancellationToken,
     /// Actor handle.
     handle: AbortOnDropHandle<()>,
     /// Queue of packets intended for the client.
-    pub(super) send_queue: mpsc::Sender<Packet>,
+    send_queue: mpsc::Sender<Packet>,
     /// Queue of disco packets intended for the client.
-    pub(super) disco_send_queue: mpsc::Sender<Packet>,
+    disco_send_queue: mpsc::Sender<Packet>,
     /// Channel to notify the client that a previous sender has disconnected.
-    pub(super) peer_gone: mpsc::Sender<NodeId>,
+    peer_gone: mpsc::Sender<NodeId>,
 }
 
 impl ClientConn {
     /// Creates a client from a connection & starts a read and write loop to handle io to and from
     /// the client
     /// Call [`ClientConn::shutdown`] to close the read and write loops before dropping the [`ClientConn`]
-    pub fn new(config: ClientConnConfig, clients: &Clients, conn_num: usize) -> ClientConn {
+    pub(super) fn new(config: ClientConnConfig, clients: &Clients) -> ClientConn {
         let ClientConnConfig {
-            node_id: key,
+            node_id,
             stream: io,
             write_timeout,
             channel_capacity,
@@ -763,7 +808,6 @@
         };
 
         let done = CancellationToken::new();
-        let client_id = (key, conn_num);
         let (send_queue_s, send_queue_r) = mpsc::channel(channel_capacity);
 
         let (disco_send_queue_s, disco_send_queue_r) = mpsc::channel(channel_capacity);
@@ -775,25 +819,23 @@
             send_queue: send_queue_r,
             disco_send_queue: disco_send_queue_r,
             node_gone: peer_gone_r,
-            key,
+            node_id,
             preferred: false,
             clients: clients.clone(),
         };
 
         // start io loop
         let io_done = done.clone();
-        let io_client_id = client_id;
+        let io_client_id = node_id;
         let handle = tokio::task::spawn(
             async move {
-                let (key, conn_num) = io_client_id;
+                let key = io_client_id;
                 match actor.run(io_done).await {
                     Err(e) => {
-                        warn!(
-                            "connection manager for {key:?} {conn_num}: writer closed in error {e}"
-                        );
+                        warn!("connection manager for {key:?}: writer closed in error {e}");
                     }
                     Ok(()) => {
-                        info!("connection manager for {key:?} {conn_num}: writer closed");
+                        info!("connection manager for {key:?}: writer closed");
                     }
                 }
             }
@@ -801,8 +843,7 @@
         );
 
         ClientConn {
-            conn_num,
-            key,
+            node_id,
             handle: AbortOnDropHandle::new(handle),
             done,
             send_queue: send_queue_s,
@@ -814,15 +855,60 @@
     /// Shutdown the reader and writer loops and closes the connection.
     ///
     /// Any shutdown errors will be logged as warnings.
-    pub async fn shutdown(self) {
+    pub(super) async fn shutdown(self) {
         self.done.cancel();
         if let Err(e) = self.handle.await {
             warn!(
-                "error closing actor loop for client connection {:?} {}: {e:?}",
-                self.key, self.conn_num
+                "error closing actor loop for client connection {:?}: {e:?}",
+                self.node_id,
             );
         };
     }
+
+    pub(super) fn send_packet(&self, src: NodeId, data: Bytes) -> Result<(), SendError> {
+        try_send(&self.send_queue, Packet { src, data })
+    }
+
+    pub(super) fn send_disco_packet(&self, src: NodeId, data: Bytes) -> Result<(), SendError> {
+        try_send(&self.disco_send_queue, Packet { src, data })
+    }
+
+    pub(super) fn send_peer_gone(&self, key: NodeId) -> Result<(), SendError> {
+        let res = try_send(&self.peer_gone, key);
+        match res {
+            Ok(_) => {
+                inc!(Metrics, other_packets_sent);
+            }
+            Err(_) => {
+                inc!(Metrics, other_packets_dropped);
+            }
+        }
+        res
+    }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub(super) enum SendError {
+    #[error("packet dropped")]
+    PacketDropped,
+    #[error("sender closed")]
+    SenderClosed,
+}
+
+/// Tries up to `3` times to send a message into the given channel, retrying iff it is full.
+fn try_send<T>(sender: &mpsc::Sender<T>, msg: T) -> Result<(), SendError> {
+    let mut msg = msg;
+    for _ in 0..RETRIES {
+        match sender.try_send(msg) {
+            Ok(_) => return Ok(()),
+            // if the queue is full, try again (max 3 times)
+            Err(mpsc::error::TrySendError::Full(m)) => msg = m,
+            // only other option is `TrySendError::Closed`, report the
+            // closed error
+            Err(_) => return Err(SendError::SenderClosed),
+        }
+    }
+    Err(SendError::PacketDropped)
 }
 
 /// Manages all the reads and writes to this client. It periodically sends a `KEEP_ALIVE`
@@ -856,7 +942,7 @@
     /// Notify the client that a previous sender has disconnected
     node_gone: mpsc::Receiver<NodeId>,
     /// [`NodeId`] of this client
-    key: NodeId,
+    node_id: NodeId,
     /// Reference to the other connected clients.
     clients: Clients,
     /// Notes that the client considers this the preferred connection (important in cases
@@ -978,10 +1064,12 @@
     async fn handle_frame_send_packet(&self, dst: NodeId, data: Bytes) -> Result<()> {
         if disco::looks_like_disco_wrapper(&data) {
             inc!(Metrics, disco_packets_recv);
-            self.clients.send_disco_packet(dst, data, self.key).await?;
+            self.clients
+                .send_disco_packet(dst, data, self.node_id)
+                .await?;
         } else {
             inc!(Metrics, send_packets_recv);
-            self.clients.send_packet(dst, data, self.key).await?;
+            self.clients.send_packet(dst, data, self.node_id).await?;
         }
         Ok(())
     }
@@ -1183,7 +1271,7 @@
         let (disco_send_queue_s, disco_send_queue_r) = mpsc::channel(10);
         let (peer_gone_s, peer_gone_r) = mpsc::channel(10);
 
-        let key = SecretKey::generate(rand::thread_rng()).public();
+        let node_id = SecretKey::generate(rand::thread_rng()).public();
         let (io, io_rw) = tokio::io::duplex(1024);
         let mut io_rw = Framed::new(io_rw, RelayCodec::test());
         let stream =
@@ -1196,7 +1284,7 @@
             send_queue: send_queue_r,
             disco_send_queue: disco_send_queue_r,
             node_gone: peer_gone_r,
-            key,
+            node_id,
             clients: clients.clone(),
             preferred: true,
         };
@@ -1212,7 +1300,7 @@
         // send packet
         println!("  send packet");
         let packet = Packet {
-            src: key,
+            src: node_id,
             data: Bytes::from(&data[..]),
         };
         send_queue_s.send(packet.clone()).await?;
@@ -1220,7 +1308,7 @@
         assert_eq!(
             frame,
             Frame::RecvPacket {
-                src_key: key,
+                src_key: node_id,
                 content: data.to_vec().into()
             }
         );
@@ -1232,16 +1320,16 @@
         assert_eq!(
             frame,
             Frame::RecvPacket {
-                src_key: key,
+                src_key: node_id,
                 content: data.to_vec().into()
             }
         );
 
         // send peer_gone
         println!("send peer gone");
-        peer_gone_s.send(key).await?;
+        peer_gone_s.send(node_id).await?;
         let frame = recv_frame(FrameType::PeerGone, &mut io_rw).await?;
-        assert_eq!(frame, Frame::NodeGone { node_id: key });
+        assert_eq!(frame, Frame::NodeGone { node_id });
 
         // Read tests
         println!("--read");
diff --git a/pr/3073/docs/src/iroh_relay/server/clients.rs.html b/pr/3073/docs/src/iroh_relay/server/clients.rs.html
index 8c00eb8fae..73c0d245c3 100644
--- a/pr/3073/docs/src/iroh_relay/server/clients.rs.html
+++ b/pr/3073/docs/src/iroh_relay/server/clients.rs.html
@@ -192,128 +192,18 @@
 191
 192
 193
-194
-195
-196
-197
-198
-199
-200
-201
-202
-203
-204
-205
-206
-207
-208
-209
-210
-211
-212
-213
-214
-215
-216
-217
-218
-219
-220
-221
-222
-223
-224
-225
-226
-227
-228
-229
-230
-231
-232
-233
-234
-235
-236
-237
-238
-239
-240
-241
-242
-243
-244
-245
-246
-247
-248
-249
-250
-251
-252
-253
-254
-255
-256
-257
-258
-259
-260
-261
-262
-263
-264
-265
-266
-267
-268
-269
-270
-271
-272
-273
-274
-275
-276
-277
-278
-279
-280
-281
-282
-283
-284
-285
-286
-287
-288
-289
-290
-291
-292
-293
//! The "Server" side of the client. Uses the `ClientConnManager`.
+194
//! The "Server" side of the client. Uses the `ClientConnManager`.
 // Based on tailscale/derp/derp_server.go
 
-use std::{
-    collections::HashSet,
-    sync::{atomic::AtomicUsize, Arc},
-};
+use std::{collections::HashSet, sync::Arc};
 
 use anyhow::{bail, Result};
 use bytes::Bytes;
 use dashmap::DashMap;
 use iroh_base::NodeId;
-use iroh_metrics::inc;
-use tokio::sync::mpsc;
 use tracing::{trace, warn};
 
-use super::{
-    client_conn::{ClientConn, ClientConnConfig, Packet},
-    metrics::Metrics,
-};
-
-/// Number of times we try to send to a client connection before dropping the data;
-const RETRIES: usize = 3;
+use super::client_conn::{ClientConn, ClientConnConfig, SendError};
 
 /// Manages the connections to all currently connected clients.
 #[derive(Debug, Default, Clone)]
@@ -322,9 +212,9 @@
 #[derive(Debug, Default)]
 struct Inner {
     /// The list of all currently connected clients.
-    clients: DashMap<NodeId, Client>,
-    /// The next connection number to use.
-    conn_num: AtomicUsize,
+    clients: DashMap<NodeId, ClientConn>,
+    /// Map of which client has sent where
+    sent_to: DashMap<NodeId, HashSet<NodeId>>,
 }
 
 impl Clients {
@@ -339,22 +229,11 @@
         .await;
     }
 
-    fn next_conn_num(&self) -> usize {
-        self.0
-            .conn_num
-            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
-    }
-
     /// Builds the client handler and starts the read & write loops for the connection.
     pub async fn register(&self, client_config: ClientConnConfig) {
         let key = client_config.node_id;
         trace!("registering client: {:?}", key);
-        let conn_num = self.next_conn_num();
-        let client = ClientConn::new(client_config, self, conn_num);
-        // TODO: in future, do not remove clients that share a NodeId, instead,
-        // expand the `Client` struct to handle multiple connections & a policy for
-        // how to handle who we write to when multiple connections exist.
-        let client = Client::new(client);
+        let client = ClientConn::new(client_config, self);
         if let Some(old_client) = self.0.clients.insert(key, client) {
             warn!("multiple connections found for {key:?}, pruning old connection",);
             old_client.shutdown().await;
@@ -364,24 +243,19 @@
     /// Removes the client from the map of clients, & sends a notification
     /// to each client that peers has sent data to, to let them know that
     /// peer is gone from the network.
-    pub async fn unregister(&self, dst: NodeId, conn_num: Option<usize>) {
+    async fn unregister(&self, dst: NodeId) {
         trace!("unregistering client: {:?}", dst);
         if let Some((_, client)) = self.0.clients.remove(&dst) {
-            if let Some(conn_num) = conn_num {
-                if client.conn.conn_num != conn_num {
-                    // put it back
-                    self.0.clients.insert(dst, client);
-                    return;
-                }
-            }
-            for key in client.sent_to.iter() {
-                match client.send_peer_gone(dst) {
-                    Ok(_) => {}
-                    Err(SendError::PacketDropped) => {
-                        warn!("client {key:?} too busy to receive packet, dropping packet");
-                    }
-                    Err(SendError::SenderClosed) => {
-                        warn!("Can no longer write to client {key:?}");
+            if let Some((_, sent_to)) = self.0.sent_to.remove(&dst) {
+                for key in sent_to {
+                    match client.send_peer_gone(key) {
+                        Ok(_) => {}
+                        Err(SendError::PacketDropped) => {
+                            warn!("client {key:?} too busy to receive packet, dropping packet");
+                        }
+                        Err(SendError::SenderClosed) => {
+                            warn!("Can no longer write to client {key:?}");
+                        }
                     }
                 }
             }
@@ -415,9 +289,9 @@
     ) -> Result<()> {
         match res {
             Ok(_) => {
-                if let Some(ref mut client) = self.0.clients.get_mut(&src) {
-                    client.record_send(dst);
-                }
+                // Record send_to relationship
+                let mut e = self.0.sent_to.entry(src).or_default();
+                e.insert(dst);
                 return Ok(());
             }
             Err(SendError::PacketDropped) => {
@@ -425,85 +299,13 @@
             }
             Err(SendError::SenderClosed) => {
                 warn!("Can no longer write to client {dst:?}, dropping message and pruning connection");
-                self.unregister(dst, None).await;
+                self.unregister(dst).await;
             }
         }
         bail!("unable to send msg");
     }
 }
 
-/// Represents a connection to a client.
-// TODO: expand to allow for _multiple connections_ associated with a single NodeId. This
-// introduces some questions around which connection should be prioritized when forwarding packets
-#[derive(Debug)]
-pub(super) struct Client {
-    /// The client connection associated with the [`NodeId`]
-    conn: ClientConn,
-    /// list of peers we have sent messages to
-    sent_to: HashSet<NodeId>,
-}
-
-impl Client {
-    fn new(conn: ClientConn) -> Self {
-        Self {
-            conn,
-            sent_to: HashSet::default(),
-        }
-    }
-
-    /// Record that this client sent a packet to the `dst` client
-    fn record_send(&mut self, dst: NodeId) {
-        self.sent_to.insert(dst);
-    }
-
-    async fn shutdown(self) {
-        self.conn.shutdown().await;
-    }
-
-    fn send_packet(&self, src: NodeId, data: Bytes) -> Result<(), SendError> {
-        try_send(&self.conn.send_queue, Packet { src, data })
-    }
-
-    fn send_disco_packet(&self, src: NodeId, data: Bytes) -> Result<(), SendError> {
-        try_send(&self.conn.disco_send_queue, Packet { src, data })
-    }
-
-    fn send_peer_gone(&self, key: NodeId) -> Result<(), SendError> {
-        let res = try_send(&self.conn.peer_gone, key);
-        match res {
-            Ok(_) => {
-                inc!(Metrics, other_packets_sent);
-            }
-            Err(_) => {
-                inc!(Metrics, other_packets_dropped);
-            }
-        }
-        res
-    }
-}
-
-/// Tries up to `3` times to send a message into the given channel, retrying iff it is full.
-fn try_send<T>(sender: &mpsc::Sender<T>, msg: T) -> Result<(), SendError> {
-    let mut msg = msg;
-    for _ in 0..RETRIES {
-        match sender.try_send(msg) {
-            Ok(_) => return Ok(()),
-            // if the queue is full, try again (max 3 times)
-            Err(mpsc::error::TrySendError::Full(m)) => msg = m,
-            // only other option is `TrySendError::Closed`, report the
-            // closed error
-            Err(_) => return Err(SendError::SenderClosed),
-        }
-    }
-    Err(SendError::PacketDropped)
-}
-
-#[derive(Debug)]
-enum SendError {
-    PacketDropped,
-    SenderClosed,
-}
-
 #[cfg(test)]
 mod tests {
     use std::time::Duration;
@@ -576,7 +378,7 @@
         );
 
         // send peer_gone
-        clients.unregister(a_key, None).await;
+        clients.unregister(a_key).await;
 
         assert!(!clients.0.clients.contains_key(&a_key));
         clients.shutdown().await;