Expand description
This module implements the send/recv relaying protocol.
+Expand description
This module implements the send/recv relaying protocol.
Protocol flow:
- server occasionally sends
FrameType::Ping
diff --git a/pr/3414/docs/iroh_relay/protos/relay/struct.Datagrams.html b/pr/3414/docs/iroh_relay/protos/relay/struct.Datagrams.html
index b90d8c03a7..29961e3f18 100644
--- a/pr/3414/docs/iroh_relay/protos/relay/struct.Datagrams.html
+++ b/pr/3414/docs/iroh_relay/protos/relay/struct.Datagrams.html
@@ -9,7 +9,8 @@
segment_size: Option<NonZeroU16>The segment size if this transmission contains multiple datagrams.
This is None if the transmit only contains a single datagram
contents: BytesThe contents of the datagram(s)
-Implementations§
Source§impl Datagrams
impl Datagrams
Sourcepub fn take_segments(&mut self, num_segments: usize) -> Option<Datagrams>
pub fn take_segments(&mut self, num_segments: usize) -> Option<Datagrams>
Splits the current datagram into at maximum num_segments segments.
Implementations§
Source§impl Datagrams
impl Datagrams
Sourcepub fn take_segments(&mut self, num_segments: usize) -> Option<Datagrams>
pub fn take_segments(&mut self, num_segments: usize) -> Option<Datagrams>
Splits the current datagram into at maximum num_segments segments, potentially returning
+the batch with at most num_segments and leaving only the rest in self.
Calling this on a datagram batch that only contains a single datagram (segment_size == None)
will result in returning essentially Some(self.clone()), while making self empty afterwards.
Calling this on a datagram batch with e.g. 15 datagrams with num_segments == 10 will
diff --git a/pr/3414/docs/src/iroh/magicsock/transports/relay.rs.html b/pr/3414/docs/src/iroh/magicsock/transports/relay.rs.html
index a834d8ffd2..4e009efbca 100644
--- a/pr/3414/docs/src/iroh/magicsock/transports/relay.rs.html
+++ b/pr/3414/docs/src/iroh/magicsock/transports/relay.rs.html
@@ -103,296 +103,302 @@
103 if buf_out.len() < dm.datagrams.contents.len() {
104 // Our receive buffer isn't big enough to process this datagram.
105 // Continuing would cause a panic.
-106 break;
-107 // In theory we could put some logic in here to fragment the datagram in case
-108 // we still have enough room in our `buf_out` left to fit a couple of
-109 // `dm.datagrams.segment_size`es, but we *should* have cut those datagrams
-110 // to appropriate sizes earlier in the pipeline (just before we put them
-111 // into the `relay_datagram_recv_queue` in the `ActiveRelayActor`).
-112 // So the only case in which this happens is we receive a datagram via the relay
-113 // that's essentially bigger than our configured `max_udp_payload_size`.
-114 // In that case we drop it and let MTU discovery take over.
-115 }
-116 buf_out[..dm.datagrams.contents.len()].copy_from_slice(&dm.datagrams.contents);
-117 meta_out.len = dm.datagrams.contents.len();
-118 meta_out.stride = dm
-119 .datagrams
-120 .segment_size
-121 .map_or(dm.datagrams.contents.len(), |s| u16::from(s) as usize);
-122 meta_out.ecn = None;
-123 meta_out.dst_ip = None; // TODO: insert the relay url for this relay
-124
-125 *addr = (dm.url, dm.src).into();
-126 num_msgs += 1;
-127 }
-128
-129 // If we have any msgs to report, they are in the first `num_msgs_total` slots
-130 if num_msgs > 0 {
-131 debug_assert!(num_msgs <= metas.len());
-132 Poll::Ready(Ok(num_msgs))
-133 } else {
-134 Poll::Pending
-135 }
-136 }
-137
-138 pub(super) fn local_addr_watch(
-139 &self,
-140 ) -> n0_watcher::Map<n0_watcher::Direct<Option<RelayUrl>>, Option<(RelayUrl, NodeId)>> {
-141 let my_node_id = self.my_node_id;
-142 self.my_relay
-143 .watch()
-144 .map(move |url| url.map(|url| (url, my_node_id)))
-145 .expect("disconnected")
-146 }
-147
-148 pub(super) fn create_network_change_sender(&self) -> RelayNetworkChangeSender {
-149 RelayNetworkChangeSender {
-150 sender: self.actor_sender.clone(),
-151 }
+106 warn!(
+107 quinn_buf_len = buf_out.len(),
+108 datagram_len = dm.datagrams.contents.len(),
+109 segment_size = ?dm.datagrams.segment_size,
+110 "dropping received datagram: quinn buffer too small"
+111 );
+112 break;
+113 // In theory we could put some logic in here to fragment the datagram in case
+114 // we still have enough room in our `buf_out` left to fit a couple of
+115 // `dm.datagrams.segment_size`es, but we *should* have cut those datagrams
+116 // to appropriate sizes earlier in the pipeline (just before we put them
+117 // into the `relay_datagram_recv_queue` in the `ActiveRelayActor`).
+118 // So the only case in which this happens is we receive a datagram via the relay
+119 // that's essentially bigger than our configured `max_udp_payload_size`.
+120 // In that case we drop it and let MTU discovery take over.
+121 }
+122 buf_out[..dm.datagrams.contents.len()].copy_from_slice(&dm.datagrams.contents);
+123 meta_out.len = dm.datagrams.contents.len();
+124 meta_out.stride = dm
+125 .datagrams
+126 .segment_size
+127 .map_or(dm.datagrams.contents.len(), |s| u16::from(s) as usize);
+128 meta_out.ecn = None;
+129 meta_out.dst_ip = None; // TODO: insert the relay url for this relay
+130
+131 *addr = (dm.url, dm.src).into();
+132 num_msgs += 1;
+133 }
+134
+135 // If we have any msgs to report, they are in the first `num_msgs_total` slots
+136 if num_msgs > 0 {
+137 debug_assert!(num_msgs <= metas.len());
+138 Poll::Ready(Ok(num_msgs))
+139 } else {
+140 Poll::Pending
+141 }
+142 }
+143
+144 pub(super) fn local_addr_watch(
+145 &self,
+146 ) -> n0_watcher::Map<n0_watcher::Direct<Option<RelayUrl>>, Option<(RelayUrl, NodeId)>> {
+147 let my_node_id = self.my_node_id;
+148 self.my_relay
+149 .watch()
+150 .map(move |url| url.map(|url| (url, my_node_id)))
+151 .expect("disconnected")
152 }
-153}
-154
-155#[derive(Debug)]
-156pub(super) struct RelayNetworkChangeSender {
-157 sender: mpsc::Sender<RelayActorMessage>,
-158}
-159
-160impl RelayNetworkChangeSender {
-161 pub(super) fn on_network_change(&self, report: &crate::magicsock::Report) {
-162 self.send_relay_actor(RelayActorMessage::NetworkChange {
-163 report: report.clone(),
-164 });
-165 }
-166
-167 pub(super) fn rebind(&self) -> io::Result<()> {
-168 self.send_relay_actor(RelayActorMessage::MaybeCloseRelaysOnRebind);
-169
-170 Ok(())
+153
+154 pub(super) fn create_network_change_sender(&self) -> RelayNetworkChangeSender {
+155 RelayNetworkChangeSender {
+156 sender: self.actor_sender.clone(),
+157 }
+158 }
+159}
+160
+161#[derive(Debug)]
+162pub(super) struct RelayNetworkChangeSender {
+163 sender: mpsc::Sender<RelayActorMessage>,
+164}
+165
+166impl RelayNetworkChangeSender {
+167 pub(super) fn on_network_change(&self, report: &crate::magicsock::Report) {
+168 self.send_relay_actor(RelayActorMessage::NetworkChange {
+169 report: report.clone(),
+170 });
171 }
172
-173 fn send_relay_actor(&self, msg: RelayActorMessage) {
-174 match self.sender.try_send(msg) {
-175 Ok(_) => {}
-176 Err(mpsc::error::TrySendError::Closed(_)) => {
-177 warn!("unable to send to relay actor, already closed");
-178 }
-179 Err(mpsc::error::TrySendError::Full(_)) => {
-180 warn!("dropping message for relay actor, channel is full");
-181 }
-182 }
-183 }
-184}
-185
-186/// Sender to send datagrams to the [`RelayActor`].
-187///
-188/// This includes the waker coordination required to support [`quinn::UdpSender::poll_send`].
-189#[derive(Debug, Clone)]
-190pub(crate) struct RelaySender {
-191 sender: PollSender<RelaySendItem>,
-192}
-193
-194impl RelaySender {
-195 pub(super) fn is_valid_send_addr(&self, _url: &RelayUrl, _node_id: &NodeId) -> bool {
-196 true
-197 }
-198
-199 pub(super) async fn send(
-200 &self,
-201 dest_url: RelayUrl,
-202 dest_node: NodeId,
-203 transmit: &Transmit<'_>,
-204 ) -> io::Result<()> {
-205 let contents = datagrams_from_transmit(transmit);
-206
-207 let item = RelaySendItem {
-208 remote_node: dest_node,
-209 url: dest_url.clone(),
-210 datagrams: contents,
-211 };
+173 pub(super) fn rebind(&self) -> io::Result<()> {
+174 self.send_relay_actor(RelayActorMessage::MaybeCloseRelaysOnRebind);
+175
+176 Ok(())
+177 }
+178
+179 fn send_relay_actor(&self, msg: RelayActorMessage) {
+180 match self.sender.try_send(msg) {
+181 Ok(_) => {}
+182 Err(mpsc::error::TrySendError::Closed(_)) => {
+183 warn!("unable to send to relay actor, already closed");
+184 }
+185 Err(mpsc::error::TrySendError::Full(_)) => {
+186 warn!("dropping message for relay actor, channel is full");
+187 }
+188 }
+189 }
+190}
+191
+192/// Sender to send datagrams to the [`RelayActor`].
+193///
+194/// This includes the waker coordination required to support [`quinn::UdpSender::poll_send`].
+195#[derive(Debug, Clone)]
+196pub(crate) struct RelaySender {
+197 sender: PollSender<RelaySendItem>,
+198}
+199
+200impl RelaySender {
+201 pub(super) fn is_valid_send_addr(&self, _url: &RelayUrl, _node_id: &NodeId) -> bool {
+202 true
+203 }
+204
+205 pub(super) async fn send(
+206 &self,
+207 dest_url: RelayUrl,
+208 dest_node: NodeId,
+209 transmit: &Transmit<'_>,
+210 ) -> io::Result<()> {
+211 let contents = datagrams_from_transmit(transmit);
212
-213 let dest_node = item.remote_node;
-214 let dest_url = item.url.clone();
-215 let Some(sender) = self.sender.get_ref() else {
-216 return Err(io::Error::other("channel closed"));
+213 let item = RelaySendItem {
+214 remote_node: dest_node,
+215 url: dest_url.clone(),
+216 datagrams: contents,
217 };
-218 match sender.send(item).await {
-219 Ok(_) => {
-220 trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-221 "send relay: message queued");
-222 Ok(())
-223 }
-224 Err(mpsc::error::SendError(_)) => {
-225 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-226 "send relay: message dropped, channel to actor is closed");
-227 Err(io::Error::new(
-228 io::ErrorKind::ConnectionReset,
-229 "channel to actor is closed",
-230 ))
-231 }
-232 }
-233 }
-234
-235 pub(super) fn poll_send(
-236 &mut self,
-237 cx: &mut Context,
-238 dest_url: RelayUrl,
-239 dest_node: NodeId,
-240 transmit: &Transmit<'_>,
-241 ) -> Poll<io::Result<()>> {
-242 match ready!(self.sender.poll_reserve(cx)) {
-243 Ok(()) => {
-244 trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-245 "send relay: message queued");
-246
-247 let contents = datagrams_from_transmit(transmit);
-248 let item = RelaySendItem {
-249 remote_node: dest_node,
-250 url: dest_url.clone(),
-251 datagrams: contents,
-252 };
-253 let dest_node = item.remote_node;
-254 let dest_url = item.url.clone();
-255
-256 match self.sender.send_item(item) {
-257 Ok(()) => Poll::Ready(Ok(())),
-258 Err(_err) => {
-259 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-260 "send relay: message dropped, channel to actor is closed");
-261 Poll::Ready(Err(io::Error::new(
-262 io::ErrorKind::ConnectionReset,
-263 "channel to actor is closed",
-264 )))
-265 }
-266 }
-267 }
-268 Err(_err) => {
-269 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-270 "send relay: message dropped, channel to actor is closed");
-271 Poll::Ready(Err(io::Error::new(
-272 io::ErrorKind::ConnectionReset,
-273 "channel to actor is closed",
-274 )))
-275 }
-276 }
-277 }
-278
-279 pub(super) fn try_send(
-280 &self,
-281 dest_url: RelayUrl,
-282 dest_node: NodeId,
-283 transmit: &Transmit<'_>,
-284 ) -> io::Result<()> {
-285 let contents = datagrams_from_transmit(transmit);
-286
-287 let item = RelaySendItem {
-288 remote_node: dest_node,
-289 url: dest_url.clone(),
-290 datagrams: contents,
-291 };
+218
+219 let dest_node = item.remote_node;
+220 let dest_url = item.url.clone();
+221 let Some(sender) = self.sender.get_ref() else {
+222 return Err(io::Error::other("channel closed"));
+223 };
+224 match sender.send(item).await {
+225 Ok(_) => {
+226 trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+227 "send relay: message queued");
+228 Ok(())
+229 }
+230 Err(mpsc::error::SendError(_)) => {
+231 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+232 "send relay: message dropped, channel to actor is closed");
+233 Err(io::Error::new(
+234 io::ErrorKind::ConnectionReset,
+235 "channel to actor is closed",
+236 ))
+237 }
+238 }
+239 }
+240
+241 pub(super) fn poll_send(
+242 &mut self,
+243 cx: &mut Context,
+244 dest_url: RelayUrl,
+245 dest_node: NodeId,
+246 transmit: &Transmit<'_>,
+247 ) -> Poll<io::Result<()>> {
+248 match ready!(self.sender.poll_reserve(cx)) {
+249 Ok(()) => {
+250 trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+251 "send relay: message queued");
+252
+253 let contents = datagrams_from_transmit(transmit);
+254 let item = RelaySendItem {
+255 remote_node: dest_node,
+256 url: dest_url.clone(),
+257 datagrams: contents,
+258 };
+259 let dest_node = item.remote_node;
+260 let dest_url = item.url.clone();
+261
+262 match self.sender.send_item(item) {
+263 Ok(()) => Poll::Ready(Ok(())),
+264 Err(_err) => {
+265 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+266 "send relay: message dropped, channel to actor is closed");
+267 Poll::Ready(Err(io::Error::new(
+268 io::ErrorKind::ConnectionReset,
+269 "channel to actor is closed",
+270 )))
+271 }
+272 }
+273 }
+274 Err(_err) => {
+275 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+276 "send relay: message dropped, channel to actor is closed");
+277 Poll::Ready(Err(io::Error::new(
+278 io::ErrorKind::ConnectionReset,
+279 "channel to actor is closed",
+280 )))
+281 }
+282 }
+283 }
+284
+285 pub(super) fn try_send(
+286 &self,
+287 dest_url: RelayUrl,
+288 dest_node: NodeId,
+289 transmit: &Transmit<'_>,
+290 ) -> io::Result<()> {
+291 let contents = datagrams_from_transmit(transmit);
292
-293 let dest_node = item.remote_node;
-294 let dest_url = item.url.clone();
-295
-296 let Some(sender) = self.sender.get_ref() else {
-297 return Err(io::Error::other("channel closed"));
-298 };
-299
-300 match sender.try_send(item) {
-301 Ok(_) => {
-302 trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-303 "send relay: message queued");
-304 Ok(())
-305 }
-306 Err(mpsc::error::TrySendError::Closed(_)) => {
-307 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-308 "send relay: message dropped, channel to actor is closed");
-309 Err(io::Error::new(
-310 io::ErrorKind::ConnectionReset,
-311 "channel to actor is closed",
-312 ))
-313 }
-314 Err(mpsc::error::TrySendError::Full(_)) => {
-315 warn!(node = %dest_node.fmt_short(), relay_url = %dest_url,
-316 "send relay: message dropped, channel to actor is full");
-317 Err(io::Error::new(io::ErrorKind::WouldBlock, "channel full"))
-318 }
-319 }
-320 }
-321}
-322
-323/// Translate a UDP transmit to the `Datagrams` type for sending over the relay.
-324fn datagrams_from_transmit(transmit: &Transmit<'_>) -> Datagrams {
-325 Datagrams {
-326 ecn: transmit.ecn.map(|ecn| match ecn {
-327 quinn_udp::EcnCodepoint::Ect0 => quinn_proto::EcnCodepoint::Ect0,
-328 quinn_udp::EcnCodepoint::Ect1 => quinn_proto::EcnCodepoint::Ect1,
-329 quinn_udp::EcnCodepoint::Ce => quinn_proto::EcnCodepoint::Ce,
-330 }),
-331 segment_size: transmit
-332 .segment_size
-333 .map(|ss| ss as u16)
-334 .and_then(NonZeroU16::new),
-335 contents: Bytes::copy_from_slice(transmit.contents),
-336 }
-337}
-338
-339#[cfg(test)]
-340mod tests {
-341 use std::{collections::BTreeSet, time::Duration};
-342
-343 use iroh_base::NodeId;
-344 use tokio::task::JoinSet;
-345 use tracing::debug;
-346
-347 use super::*;
-348 use crate::defaults::staging;
-349
-350 #[tokio::test(flavor = "multi_thread")]
-351 async fn test_relay_datagram_queue() {
-352 let capacity = 16;
-353 let (sender, mut receiver) = mpsc::channel(capacity);
-354 let url = staging::default_na_relay_node().url;
+293 let item = RelaySendItem {
+294 remote_node: dest_node,
+295 url: dest_url.clone(),
+296 datagrams: contents,
+297 };
+298
+299 let dest_node = item.remote_node;
+300 let dest_url = item.url.clone();
+301
+302 let Some(sender) = self.sender.get_ref() else {
+303 return Err(io::Error::other("channel closed"));
+304 };
+305
+306 match sender.try_send(item) {
+307 Ok(_) => {
+308 trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+309 "send relay: message queued");
+310 Ok(())
+311 }
+312 Err(mpsc::error::TrySendError::Closed(_)) => {
+313 error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+314 "send relay: message dropped, channel to actor is closed");
+315 Err(io::Error::new(
+316 io::ErrorKind::ConnectionReset,
+317 "channel to actor is closed",
+318 ))
+319 }
+320 Err(mpsc::error::TrySendError::Full(_)) => {
+321 warn!(node = %dest_node.fmt_short(), relay_url = %dest_url,
+322 "send relay: message dropped, channel to actor is full");
+323 Err(io::Error::new(io::ErrorKind::WouldBlock, "channel full"))
+324 }
+325 }
+326 }
+327}
+328
+329/// Translate a UDP transmit to the `Datagrams` type for sending over the relay.
+330fn datagrams_from_transmit(transmit: &Transmit<'_>) -> Datagrams {
+331 Datagrams {
+332 ecn: transmit.ecn.map(|ecn| match ecn {
+333 quinn_udp::EcnCodepoint::Ect0 => quinn_proto::EcnCodepoint::Ect0,
+334 quinn_udp::EcnCodepoint::Ect1 => quinn_proto::EcnCodepoint::Ect1,
+335 quinn_udp::EcnCodepoint::Ce => quinn_proto::EcnCodepoint::Ce,
+336 }),
+337 segment_size: transmit
+338 .segment_size
+339 .map(|ss| ss as u16)
+340 .and_then(NonZeroU16::new),
+341 contents: Bytes::copy_from_slice(transmit.contents),
+342 }
+343}
+344
+345#[cfg(test)]
+346mod tests {
+347 use std::{collections::BTreeSet, time::Duration};
+348
+349 use iroh_base::NodeId;
+350 use tokio::task::JoinSet;
+351 use tracing::debug;
+352
+353 use super::*;
+354 use crate::defaults::staging;
355
-356 let mut tasks = JoinSet::new();
-357
-358 tasks.spawn({
-359 async move {
-360 let mut expected_msgs: BTreeSet<usize> = (0..capacity).collect();
-361 while !expected_msgs.is_empty() {
-362 let datagram: RelayRecvDatagram = receiver.recv().await.unwrap();
-363 let msg_num = usize::from_le_bytes(datagram.datagrams.contents.as_ref().try_into().unwrap());
-364 debug!("Received {msg_num}");
-365
-366 if !expected_msgs.remove(&msg_num) {
-367 panic!("Received message number {msg_num} twice or more, but expected it only exactly once.");
-368 }
-369 }
-370 }
-371 });
-372
-373 for i in 0..capacity {
-374 tasks.spawn({
-375 let sender = sender.clone();
-376 let url = url.clone();
-377 async move {
-378 debug!("Sending {i}");
-379 sender
-380 .try_send(RelayRecvDatagram {
-381 url,
-382 src: NodeId::from_bytes(&[0u8; 32]).unwrap(),
-383 datagrams: Datagrams::from(&i.to_le_bytes()),
-384 })
-385 .unwrap();
-386 }
-387 });
-388 }
-389
-390 // We expect all of this work to be done in 10 seconds max.
-391 if tokio::time::timeout(Duration::from_secs(10), tasks.join_all())
-392 .await
-393 .is_err()
-394 {
-395 panic!("Timeout - not all messages between 0 and {capacity} received.");
-396 }
-397 }
-398}