From 0eb500a0f66fd92e7bbb2b6e35b3a2730a99fbcd Mon Sep 17 00:00:00 2001 From: matheus23 Date: Tue, 29 Jul 2025 13:49:26 +0000 Subject: [PATCH] deploy: 13fa2c69f0edb11005f32e1edf6ca560ee1ecc5a --- .../protos/relay/enum.RelayToClientMsg.html | 2 +- .../docs/iroh_relay/protos/relay/index.html | 2 +- .../protos/relay/struct.Datagrams.html | 3 +- .../iroh/magicsock/transports/relay.rs.html | 578 ++++---- .../docs/src/iroh_relay/protos/relay.rs.html | 1258 +++++++++-------- 5 files changed, 926 insertions(+), 917 deletions(-) diff --git a/pr/3414/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html b/pr/3414/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html index 09a7c3e678..ec346f738b 100644 --- a/pr/3414/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html +++ b/pr/3414/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html @@ -35,7 +35,7 @@ than a few seconds.

other side with a ClientToRelayMsg::Pong with the given payload.

§

Pong([u8; 8])

Reply to a ClientToRelayMsg::Ping from a client with the payload sent previously in the ping.

-

Implementations§

Source§

impl RelayToClientMsg

Source

pub fn typ(&self) -> FrameType

Returns this frame’s corresponding frame type.

+

Implementations§

Source§

impl RelayToClientMsg

Source

pub fn typ(&self) -> FrameType

Returns this frame’s corresponding frame type.

Trait Implementations§

Source§

impl Clone for RelayToClientMsg

Source§

fn clone(&self) -> RelayToClientMsg

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RelayToClientMsg

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for RelayToClientMsg

Source§

fn eq(&self, other: &RelayToClientMsg) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for RelayToClientMsg

Source§

impl StructuralPartialEq for RelayToClientMsg

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where diff --git a/pr/3414/docs/iroh_relay/protos/relay/index.html b/pr/3414/docs/iroh_relay/protos/relay/index.html index 30bdf44ff7..74dbdd2b1d 100644 --- a/pr/3414/docs/iroh_relay/protos/relay/index.html +++ b/pr/3414/docs/iroh_relay/protos/relay/index.html @@ -1,4 +1,4 @@ -iroh_relay::protos::relay - Rust

Module relay

Source
Expand description

This module implements the send/recv relaying protocol.

+iroh_relay::protos::relay - Rust

Module relay

Source
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: Bytes

The contents of the datagram(s)

-

Implementations§

Source§

impl Datagrams

Source

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

Source

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}

\ No newline at end of file +356 #[tokio::test(flavor = "multi_thread")] +357 async fn test_relay_datagram_queue() { +358 let capacity = 16; +359 let (sender, mut receiver) = mpsc::channel(capacity); +360 let url = staging::default_na_relay_node().url; +361 +362 let mut tasks = JoinSet::new(); +363 +364 tasks.spawn({ +365 async move { +366 let mut expected_msgs: BTreeSet<usize> = (0..capacity).collect(); +367 while !expected_msgs.is_empty() { +368 let datagram: RelayRecvDatagram = receiver.recv().await.unwrap(); +369 let msg_num = usize::from_le_bytes(datagram.datagrams.contents.as_ref().try_into().unwrap()); +370 debug!("Received {msg_num}"); +371 +372 if !expected_msgs.remove(&msg_num) { +373 panic!("Received message number {msg_num} twice or more, but expected it only exactly once."); +374 } +375 } +376 } +377 }); +378 +379 for i in 0..capacity { +380 tasks.spawn({ +381 let sender = sender.clone(); +382 let url = url.clone(); +383 async move { +384 debug!("Sending {i}"); +385 sender +386 .try_send(RelayRecvDatagram { +387 url, +388 src: NodeId::from_bytes(&[0u8; 32]).unwrap(), +389 datagrams: Datagrams::from(&i.to_le_bytes()), +390 }) +391 .unwrap(); +392 } +393 }); +394 } +395 +396 // We expect all of this work to be done in 10 seconds max. +397 if tokio::time::timeout(Duration::from_secs(10), tasks.join_all()) +398 .await +399 .is_err() +400 { +401 panic!("Timeout - not all messages between 0 and {capacity} received."); +402 } +403 } +404}
\ No newline at end of file diff --git a/pr/3414/docs/src/iroh_relay/protos/relay.rs.html b/pr/3414/docs/src/iroh_relay/protos/relay.rs.html index 350fa84813..fb9ec1d95a 100644 --- a/pr/3414/docs/src/iroh_relay/protos/relay.rs.html +++ b/pr/3414/docs/src/iroh_relay/protos/relay.rs.html @@ -157,633 +157,635 @@ 157} 158 159impl Datagrams { -160 /// Splits the current datagram into at maximum `num_segments` segments. -161 /// -162 /// Calling this on a datagram batch that only contains a single datagram (`segment_size == None`) -163 /// will result in returning essentially `Some(self.clone())`, while making `self` empty afterwards. -164 /// -165 /// Calling this on a datagram batch with e.g. 15 datagrams with `num_segments == 10` will -166 /// result in returning `Some(datagram_batch)` where that `datagram_batch` contains 10 datagrams and -167 /// `self` contains 5 datagrams. -168 /// -169 /// Calling this on a datagram batch that doesn't contain `num_segments` datagrams, but less -170 /// will result in making `self` empty and returning essentially a clone of `self`. -171 /// -172 /// Calling this on an empty datagram batch (i.e. one where `contents.is_empty()`) will return `None`. -173 pub fn take_segments(&mut self, num_segments: usize) -> Option<Datagrams> { -174 if self.contents.is_empty() { -175 return None; -176 } -177 -178 let Some(segment_size) = self.segment_size else { -179 let contents = std::mem::take(&mut self.contents); -180 return Some(Datagrams { -181 ecn: self.ecn, -182 segment_size: None, -183 contents, -184 }); -185 }; -186 -187 let usize_segment_size = usize::from(u16::from(segment_size)); -188 let max_content_len = num_segments * usize_segment_size; -189 let contents = self -190 .contents -191 .split_to(std::cmp::min(max_content_len, self.contents.len())); -192 -193 Some(Datagrams { -194 ecn: self.ecn, -195 segment_size: (num_segments > 1 && usize_segment_size < contents.len()) -196 .then_some(segment_size), -197 contents, -198 }) -199 } -200 -201 fn write_to<O: BufMut>(&self, mut dst: O) -> O { -202 let ecn = self.ecn.map_or(0, |ecn| ecn as u8); -203 dst.put_u8(ecn); -204 if let Some(segment_size) = self.segment_size { -205 dst.put_u16(segment_size.into()); -206 } -207 dst.put(self.contents.as_ref()); -208 dst -209 } -210 -211 fn encoded_len(&self) -> usize { -212 1 // ECN byte -213 + self.segment_size.map_or(0, |_| 2) // segment size, when None, then a packed representation is assumed -214 + self.contents.len() -215 } -216 -217 #[allow(clippy::len_zero)] -218 fn from_bytes(mut bytes: Bytes, is_batch: bool) -> Result<Self, Error> { -219 if is_batch { -220 // 1 bytes ECN, 2 bytes segment size -221 snafu::ensure!(bytes.len() >= 3, InvalidFrameSnafu); -222 } else { -223 snafu::ensure!(bytes.len() >= 1, InvalidFrameSnafu); -224 } -225 -226 let ecn_byte = bytes.get_u8(); -227 let ecn = quinn_proto::EcnCodepoint::from_bits(ecn_byte); -228 -229 let segment_size = if is_batch { -230 let segment_size = bytes.get_u16(); // length checked above -231 NonZeroU16::new(segment_size) -232 } else { -233 None -234 }; -235 -236 Ok(Self { -237 ecn, -238 segment_size, -239 contents: bytes, -240 }) -241 } -242} -243 -244impl RelayToClientMsg { -245 /// Returns this frame's corresponding frame type. -246 pub fn typ(&self) -> FrameType { -247 match self { -248 Self::Datagrams { datagrams, .. } => { -249 if datagrams.segment_size.is_some() { -250 FrameType::RelayToClientDatagramBatch -251 } else { -252 FrameType::RelayToClientDatagram -253 } -254 } -255 Self::NodeGone { .. } => FrameType::NodeGone, -256 Self::Ping { .. } => FrameType::Ping, -257 Self::Pong { .. } => FrameType::Pong, -258 Self::Health { .. } => FrameType::Health, -259 Self::Restarting { .. } => FrameType::Restarting, -260 } -261 } -262 -263 #[cfg(feature = "server")] -264 pub(crate) fn to_bytes(&self) -> BytesMut { -265 self.write_to(BytesMut::with_capacity(self.encoded_len())) -266 } -267 -268 /// Encodes this frame for sending over websockets. -269 /// -270 /// Specifically meant for being put into a binary websocket message frame. -271 #[cfg(feature = "server")] -272 pub(crate) fn write_to<O: BufMut>(&self, mut dst: O) -> O { -273 dst = self.typ().write_to(dst); -274 match self { -275 Self::Datagrams { -276 remote_node_id, -277 datagrams, -278 } => { -279 dst.put(remote_node_id.as_ref()); -280 dst = datagrams.write_to(dst); -281 } -282 Self::NodeGone(node_id) => { -283 dst.put(node_id.as_ref()); -284 } -285 Self::Ping(data) => { -286 dst.put(&data[..]); -287 } -288 Self::Pong(data) => { -289 dst.put(&data[..]); -290 } -291 Self::Health { problem } => { -292 dst.put(problem.as_ref()); -293 } -294 Self::Restarting { -295 reconnect_in, -296 try_for, -297 } => { -298 dst.put_u32(reconnect_in.as_millis() as u32); -299 dst.put_u32(try_for.as_millis() as u32); -300 } -301 } -302 dst -303 } -304 -305 #[cfg(feature = "server")] -306 pub(crate) fn encoded_len(&self) -> usize { -307 let payload_len = match self { -308 Self::Datagrams { datagrams, .. } => { -309 32 // nodeid -310 + datagrams.encoded_len() -311 } -312 Self::NodeGone(_) => 32, -313 Self::Ping(_) | Self::Pong(_) => 8, -314 Self::Health { problem } => problem.len(), -315 Self::Restarting { .. } => { -316 4 // u32 -317 + 4 // u32 -318 } -319 }; -320 self.typ().encoded_len() + payload_len -321 } -322 -323 /// Tries to decode a frame received over websockets. -324 /// -325 /// Specifically, bytes received from a binary websocket message frame. -326 #[allow(clippy::result_large_err)] -327 pub(crate) fn from_bytes(mut content: Bytes, cache: &KeyCache) -> Result<Self, Error> { -328 let frame_type = FrameType::from_bytes(&mut content)?; -329 let frame_len = content.len(); -330 snafu::ensure!( -331 frame_len <= MAX_PACKET_SIZE, -332 FrameTooLargeSnafu { frame_len } -333 ); -334 -335 let res = match frame_type { -336 FrameType::RelayToClientDatagram | FrameType::RelayToClientDatagramBatch => { -337 snafu::ensure!(content.len() >= NodeId::LENGTH, InvalidFrameSnafu); -338 -339 let remote_node_id = cache -340 .key_from_slice(&content[..NodeId::LENGTH]) -341 .context(InvalidPublicKeySnafu)?; -342 let datagrams = Datagrams::from_bytes( -343 content.slice(NodeId::LENGTH..), -344 frame_type == FrameType::RelayToClientDatagramBatch, -345 )?; -346 Self::Datagrams { -347 remote_node_id, -348 datagrams, -349 } -350 } -351 FrameType::NodeGone => { -352 snafu::ensure!(content.len() == NodeId::LENGTH, InvalidFrameSnafu); -353 let node_id = cache -354 .key_from_slice(content.as_ref()) -355 .context(InvalidPublicKeySnafu)?; -356 Self::NodeGone(node_id) -357 } -358 FrameType::Ping => { -359 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); -360 let mut data = [0u8; 8]; -361 data.copy_from_slice(&content[..8]); -362 Self::Ping(data) -363 } -364 FrameType::Pong => { -365 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); -366 let mut data = [0u8; 8]; -367 data.copy_from_slice(&content[..8]); -368 Self::Pong(data) -369 } -370 FrameType::Health => { -371 let problem = std::str::from_utf8(&content) -372 .context(InvalidProtocolMessageEncodingSnafu)? -373 .to_owned(); -374 Self::Health { problem } -375 } -376 FrameType::Restarting => { -377 snafu::ensure!(content.len() == 4 + 4, InvalidFrameSnafu); -378 let reconnect_in = u32::from_be_bytes( -379 content[..4] -380 .try_into() -381 .map_err(|_| InvalidFrameSnafu.build())?, -382 ); -383 let try_for = u32::from_be_bytes( -384 content[4..] -385 .try_into() -386 .map_err(|_| InvalidFrameSnafu.build())?, -387 ); -388 let reconnect_in = Duration::from_millis(reconnect_in as u64); -389 let try_for = Duration::from_millis(try_for as u64); -390 Self::Restarting { -391 reconnect_in, -392 try_for, -393 } -394 } -395 _ => { -396 return Err(InvalidFrameTypeSnafu { frame_type }.build()); -397 } -398 }; -399 Ok(res) -400 } -401} -402 -403impl ClientToRelayMsg { -404 pub(crate) fn typ(&self) -> FrameType { -405 match self { -406 Self::Datagrams { datagrams, .. } => { -407 if datagrams.segment_size.is_some() { -408 FrameType::ClientToRelayDatagramBatch -409 } else { -410 FrameType::ClientToRelayDatagram -411 } -412 } -413 Self::Ping { .. } => FrameType::Ping, -414 Self::Pong { .. } => FrameType::Pong, -415 } -416 } -417 -418 pub(crate) fn to_bytes(&self) -> BytesMut { -419 self.write_to(BytesMut::with_capacity(self.encoded_len())) -420 } -421 -422 /// Encodes this frame for sending over websockets. -423 /// -424 /// Specifically meant for being put into a binary websocket message frame. -425 pub(crate) fn write_to<O: BufMut>(&self, mut dst: O) -> O { -426 dst = self.typ().write_to(dst); -427 match self { -428 Self::Datagrams { -429 dst_node_id, -430 datagrams, -431 } => { -432 dst.put(dst_node_id.as_ref()); -433 dst = datagrams.write_to(dst); -434 } -435 Self::Ping(data) => { -436 dst.put(&data[..]); -437 } -438 Self::Pong(data) => { -439 dst.put(&data[..]); -440 } -441 } -442 dst -443 } -444 -445 pub(crate) fn encoded_len(&self) -> usize { -446 let payload_len = match self { -447 Self::Ping(_) | Self::Pong(_) => 8, -448 Self::Datagrams { datagrams, .. } => { -449 32 // node id -450 + datagrams.encoded_len() -451 } -452 }; -453 self.typ().encoded_len() + payload_len -454 } -455 -456 /// Tries to decode a frame received over websockets. -457 /// -458 /// Specifically, bytes received from a binary websocket message frame. -459 #[allow(clippy::result_large_err)] -460 #[cfg(feature = "server")] -461 pub(crate) fn from_bytes(mut content: Bytes, cache: &KeyCache) -> Result<Self, Error> { -462 let frame_type = FrameType::from_bytes(&mut content)?; -463 let frame_len = content.len(); -464 snafu::ensure!( -465 frame_len <= MAX_PACKET_SIZE, -466 FrameTooLargeSnafu { frame_len } -467 ); -468 -469 let res = match frame_type { -470 FrameType::ClientToRelayDatagram | FrameType::ClientToRelayDatagramBatch => { -471 let dst_node_id = cache -472 .key_from_slice(&content[..NodeId::LENGTH]) -473 .context(InvalidPublicKeySnafu)?; -474 let datagrams = Datagrams::from_bytes( -475 content.slice(NodeId::LENGTH..), -476 frame_type == FrameType::ClientToRelayDatagramBatch, -477 )?; -478 Self::Datagrams { -479 dst_node_id, -480 datagrams, -481 } -482 } -483 FrameType::Ping => { -484 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); -485 let mut data = [0u8; 8]; -486 data.copy_from_slice(&content[..8]); -487 Self::Ping(data) -488 } -489 FrameType::Pong => { -490 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); -491 let mut data = [0u8; 8]; -492 data.copy_from_slice(&content[..8]); -493 Self::Pong(data) -494 } -495 _ => { -496 return Err(InvalidFrameTypeSnafu { frame_type }.build()); -497 } -498 }; -499 Ok(res) -500 } -501} -502 -503#[cfg(test)] -504#[cfg(feature = "server")] -505mod tests { -506 use data_encoding::HEXLOWER; -507 use iroh_base::SecretKey; -508 use n0_snafu::Result; -509 -510 use super::*; +160 /// Splits the current datagram into at maximum `num_segments` segments, potentially returning +161 /// the batch with at most `num_segments` and leaving only the rest in `self`. +162 /// +163 /// Calling this on a datagram batch that only contains a single datagram (`segment_size == None`) +164 /// will result in returning essentially `Some(self.clone())`, while making `self` empty afterwards. +165 /// +166 /// Calling this on a datagram batch with e.g. 15 datagrams with `num_segments == 10` will +167 /// result in returning `Some(datagram_batch)` where that `datagram_batch` contains 10 datagrams and +168 /// `self` contains 5 datagrams. +169 /// +170 /// Calling this on a datagram batch that doesn't contain `num_segments` datagrams, but less +171 /// will result in making `self` empty and returning essentially a clone of `self`. +172 /// +173 /// Calling this on an empty datagram batch (i.e. one where `contents.is_empty()`) will return `None`. +174 pub fn take_segments(&mut self, num_segments: usize) -> Option<Datagrams> { +175 if self.contents.is_empty() { +176 return None; +177 } +178 +179 let Some(segment_size) = self.segment_size else { +180 let contents = std::mem::take(&mut self.contents); +181 return Some(Datagrams { +182 ecn: self.ecn, +183 segment_size: None, +184 contents, +185 }); +186 }; +187 +188 let usize_segment_size = usize::from(u16::from(segment_size)); +189 let max_content_len = num_segments * usize_segment_size; +190 let contents = self +191 .contents +192 .split_to(std::cmp::min(max_content_len, self.contents.len())); +193 +194 let is_datagram_batch = num_segments > 1 && usize_segment_size < contents.len(); +195 +196 Some(Datagrams { +197 ecn: self.ecn, +198 segment_size: is_datagram_batch.then_some(segment_size), +199 contents, +200 }) +201 } +202 +203 fn write_to<O: BufMut>(&self, mut dst: O) -> O { +204 let ecn = self.ecn.map_or(0, |ecn| ecn as u8); +205 dst.put_u8(ecn); +206 if let Some(segment_size) = self.segment_size { +207 dst.put_u16(segment_size.into()); +208 } +209 dst.put(self.contents.as_ref()); +210 dst +211 } +212 +213 fn encoded_len(&self) -> usize { +214 1 // ECN byte +215 + self.segment_size.map_or(0, |_| 2) // segment size, when None, then a packed representation is assumed +216 + self.contents.len() +217 } +218 +219 #[allow(clippy::len_zero)] +220 fn from_bytes(mut bytes: Bytes, is_batch: bool) -> Result<Self, Error> { +221 if is_batch { +222 // 1 bytes ECN, 2 bytes segment size +223 snafu::ensure!(bytes.len() >= 3, InvalidFrameSnafu); +224 } else { +225 snafu::ensure!(bytes.len() >= 1, InvalidFrameSnafu); +226 } +227 +228 let ecn_byte = bytes.get_u8(); +229 let ecn = quinn_proto::EcnCodepoint::from_bits(ecn_byte); +230 +231 let segment_size = if is_batch { +232 let segment_size = bytes.get_u16(); // length checked above +233 NonZeroU16::new(segment_size) +234 } else { +235 None +236 }; +237 +238 Ok(Self { +239 ecn, +240 segment_size, +241 contents: bytes, +242 }) +243 } +244} +245 +246impl RelayToClientMsg { +247 /// Returns this frame's corresponding frame type. +248 pub fn typ(&self) -> FrameType { +249 match self { +250 Self::Datagrams { datagrams, .. } => { +251 if datagrams.segment_size.is_some() { +252 FrameType::RelayToClientDatagramBatch +253 } else { +254 FrameType::RelayToClientDatagram +255 } +256 } +257 Self::NodeGone { .. } => FrameType::NodeGone, +258 Self::Ping { .. } => FrameType::Ping, +259 Self::Pong { .. } => FrameType::Pong, +260 Self::Health { .. } => FrameType::Health, +261 Self::Restarting { .. } => FrameType::Restarting, +262 } +263 } +264 +265 #[cfg(feature = "server")] +266 pub(crate) fn to_bytes(&self) -> BytesMut { +267 self.write_to(BytesMut::with_capacity(self.encoded_len())) +268 } +269 +270 /// Encodes this frame for sending over websockets. +271 /// +272 /// Specifically meant for being put into a binary websocket message frame. +273 #[cfg(feature = "server")] +274 pub(crate) fn write_to<O: BufMut>(&self, mut dst: O) -> O { +275 dst = self.typ().write_to(dst); +276 match self { +277 Self::Datagrams { +278 remote_node_id, +279 datagrams, +280 } => { +281 dst.put(remote_node_id.as_ref()); +282 dst = datagrams.write_to(dst); +283 } +284 Self::NodeGone(node_id) => { +285 dst.put(node_id.as_ref()); +286 } +287 Self::Ping(data) => { +288 dst.put(&data[..]); +289 } +290 Self::Pong(data) => { +291 dst.put(&data[..]); +292 } +293 Self::Health { problem } => { +294 dst.put(problem.as_ref()); +295 } +296 Self::Restarting { +297 reconnect_in, +298 try_for, +299 } => { +300 dst.put_u32(reconnect_in.as_millis() as u32); +301 dst.put_u32(try_for.as_millis() as u32); +302 } +303 } +304 dst +305 } +306 +307 #[cfg(feature = "server")] +308 pub(crate) fn encoded_len(&self) -> usize { +309 let payload_len = match self { +310 Self::Datagrams { datagrams, .. } => { +311 32 // nodeid +312 + datagrams.encoded_len() +313 } +314 Self::NodeGone(_) => 32, +315 Self::Ping(_) | Self::Pong(_) => 8, +316 Self::Health { problem } => problem.len(), +317 Self::Restarting { .. } => { +318 4 // u32 +319 + 4 // u32 +320 } +321 }; +322 self.typ().encoded_len() + payload_len +323 } +324 +325 /// Tries to decode a frame received over websockets. +326 /// +327 /// Specifically, bytes received from a binary websocket message frame. +328 #[allow(clippy::result_large_err)] +329 pub(crate) fn from_bytes(mut content: Bytes, cache: &KeyCache) -> Result<Self, Error> { +330 let frame_type = FrameType::from_bytes(&mut content)?; +331 let frame_len = content.len(); +332 snafu::ensure!( +333 frame_len <= MAX_PACKET_SIZE, +334 FrameTooLargeSnafu { frame_len } +335 ); +336 +337 let res = match frame_type { +338 FrameType::RelayToClientDatagram | FrameType::RelayToClientDatagramBatch => { +339 snafu::ensure!(content.len() >= NodeId::LENGTH, InvalidFrameSnafu); +340 +341 let remote_node_id = cache +342 .key_from_slice(&content[..NodeId::LENGTH]) +343 .context(InvalidPublicKeySnafu)?; +344 let datagrams = Datagrams::from_bytes( +345 content.slice(NodeId::LENGTH..), +346 frame_type == FrameType::RelayToClientDatagramBatch, +347 )?; +348 Self::Datagrams { +349 remote_node_id, +350 datagrams, +351 } +352 } +353 FrameType::NodeGone => { +354 snafu::ensure!(content.len() == NodeId::LENGTH, InvalidFrameSnafu); +355 let node_id = cache +356 .key_from_slice(content.as_ref()) +357 .context(InvalidPublicKeySnafu)?; +358 Self::NodeGone(node_id) +359 } +360 FrameType::Ping => { +361 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); +362 let mut data = [0u8; 8]; +363 data.copy_from_slice(&content[..8]); +364 Self::Ping(data) +365 } +366 FrameType::Pong => { +367 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); +368 let mut data = [0u8; 8]; +369 data.copy_from_slice(&content[..8]); +370 Self::Pong(data) +371 } +372 FrameType::Health => { +373 let problem = std::str::from_utf8(&content) +374 .context(InvalidProtocolMessageEncodingSnafu)? +375 .to_owned(); +376 Self::Health { problem } +377 } +378 FrameType::Restarting => { +379 snafu::ensure!(content.len() == 4 + 4, InvalidFrameSnafu); +380 let reconnect_in = u32::from_be_bytes( +381 content[..4] +382 .try_into() +383 .map_err(|_| InvalidFrameSnafu.build())?, +384 ); +385 let try_for = u32::from_be_bytes( +386 content[4..] +387 .try_into() +388 .map_err(|_| InvalidFrameSnafu.build())?, +389 ); +390 let reconnect_in = Duration::from_millis(reconnect_in as u64); +391 let try_for = Duration::from_millis(try_for as u64); +392 Self::Restarting { +393 reconnect_in, +394 try_for, +395 } +396 } +397 _ => { +398 return Err(InvalidFrameTypeSnafu { frame_type }.build()); +399 } +400 }; +401 Ok(res) +402 } +403} +404 +405impl ClientToRelayMsg { +406 pub(crate) fn typ(&self) -> FrameType { +407 match self { +408 Self::Datagrams { datagrams, .. } => { +409 if datagrams.segment_size.is_some() { +410 FrameType::ClientToRelayDatagramBatch +411 } else { +412 FrameType::ClientToRelayDatagram +413 } +414 } +415 Self::Ping { .. } => FrameType::Ping, +416 Self::Pong { .. } => FrameType::Pong, +417 } +418 } +419 +420 pub(crate) fn to_bytes(&self) -> BytesMut { +421 self.write_to(BytesMut::with_capacity(self.encoded_len())) +422 } +423 +424 /// Encodes this frame for sending over websockets. +425 /// +426 /// Specifically meant for being put into a binary websocket message frame. +427 pub(crate) fn write_to<O: BufMut>(&self, mut dst: O) -> O { +428 dst = self.typ().write_to(dst); +429 match self { +430 Self::Datagrams { +431 dst_node_id, +432 datagrams, +433 } => { +434 dst.put(dst_node_id.as_ref()); +435 dst = datagrams.write_to(dst); +436 } +437 Self::Ping(data) => { +438 dst.put(&data[..]); +439 } +440 Self::Pong(data) => { +441 dst.put(&data[..]); +442 } +443 } +444 dst +445 } +446 +447 pub(crate) fn encoded_len(&self) -> usize { +448 let payload_len = match self { +449 Self::Ping(_) | Self::Pong(_) => 8, +450 Self::Datagrams { datagrams, .. } => { +451 32 // node id +452 + datagrams.encoded_len() +453 } +454 }; +455 self.typ().encoded_len() + payload_len +456 } +457 +458 /// Tries to decode a frame received over websockets. +459 /// +460 /// Specifically, bytes received from a binary websocket message frame. +461 #[allow(clippy::result_large_err)] +462 #[cfg(feature = "server")] +463 pub(crate) fn from_bytes(mut content: Bytes, cache: &KeyCache) -> Result<Self, Error> { +464 let frame_type = FrameType::from_bytes(&mut content)?; +465 let frame_len = content.len(); +466 snafu::ensure!( +467 frame_len <= MAX_PACKET_SIZE, +468 FrameTooLargeSnafu { frame_len } +469 ); +470 +471 let res = match frame_type { +472 FrameType::ClientToRelayDatagram | FrameType::ClientToRelayDatagramBatch => { +473 let dst_node_id = cache +474 .key_from_slice(&content[..NodeId::LENGTH]) +475 .context(InvalidPublicKeySnafu)?; +476 let datagrams = Datagrams::from_bytes( +477 content.slice(NodeId::LENGTH..), +478 frame_type == FrameType::ClientToRelayDatagramBatch, +479 )?; +480 Self::Datagrams { +481 dst_node_id, +482 datagrams, +483 } +484 } +485 FrameType::Ping => { +486 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); +487 let mut data = [0u8; 8]; +488 data.copy_from_slice(&content[..8]); +489 Self::Ping(data) +490 } +491 FrameType::Pong => { +492 snafu::ensure!(content.len() == 8, InvalidFrameSnafu); +493 let mut data = [0u8; 8]; +494 data.copy_from_slice(&content[..8]); +495 Self::Pong(data) +496 } +497 _ => { +498 return Err(InvalidFrameTypeSnafu { frame_type }.build()); +499 } +500 }; +501 Ok(res) +502 } +503} +504 +505#[cfg(test)] +506#[cfg(feature = "server")] +507mod tests { +508 use data_encoding::HEXLOWER; +509 use iroh_base::SecretKey; +510 use n0_snafu::Result; 511 -512 fn check_expected_bytes(frames: Vec<(Vec<u8>, &str)>) { -513 for (bytes, expected_hex) in frames { -514 let stripped: Vec<u8> = expected_hex -515 .chars() -516 .filter_map(|s| { -517 if s.is_ascii_whitespace() { -518 None -519 } else { -520 Some(s as u8) -521 } -522 }) -523 .collect(); -524 let expected_bytes = HEXLOWER.decode(&stripped).unwrap(); -525 assert_eq!(HEXLOWER.encode(&bytes), HEXLOWER.encode(&expected_bytes)); -526 } -527 } -528 -529 #[test] -530 fn test_server_client_frames_snapshot() -> Result { -531 let client_key = SecretKey::from_bytes(&[42u8; 32]); -532 -533 check_expected_bytes(vec![ -534 ( -535 RelayToClientMsg::Health { -536 problem: "Hello? Yes this is dog.".into(), -537 } -538 .write_to(Vec::new()), -539 "0b 48 65 6c 6c 6f 3f 20 59 65 73 20 74 68 69 73 -540 20 69 73 20 64 6f 67 2e", -541 ), -542 ( -543 RelayToClientMsg::NodeGone(client_key.public()).write_to(Vec::new()), -544 "08 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e -545 a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d -546 61", -547 ), -548 ( -549 RelayToClientMsg::Ping([42u8; 8]).write_to(Vec::new()), -550 "09 2a 2a 2a 2a 2a 2a 2a 2a", -551 ), -552 ( -553 RelayToClientMsg::Pong([42u8; 8]).write_to(Vec::new()), -554 "0a 2a 2a 2a 2a 2a 2a 2a 2a", -555 ), -556 ( -557 RelayToClientMsg::Datagrams { -558 remote_node_id: client_key.public(), -559 datagrams: Datagrams { -560 ecn: Some(quinn::EcnCodepoint::Ce), -561 segment_size: NonZeroU16::new(6), -562 contents: "Hello World!".into(), -563 }, -564 } -565 .write_to(Vec::new()), -566 // frame type -567 // public key first 16 bytes -568 // public key second 16 bytes -569 // ECN byte -570 // segment size -571 // hello world contents bytes -572 "07 -573 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 -574 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 -575 03 -576 00 06 -577 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", -578 ), -579 ( -580 RelayToClientMsg::Datagrams { -581 remote_node_id: client_key.public(), -582 datagrams: Datagrams { -583 ecn: Some(quinn::EcnCodepoint::Ce), -584 segment_size: None, -585 contents: "Hello World!".into(), -586 }, -587 } -588 .write_to(Vec::new()), -589 // frame type -590 // public key first 16 bytes -591 // public key second 16 bytes -592 // ECN byte -593 // hello world contents bytes -594 "06 -595 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 -596 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 -597 03 -598 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", -599 ), -600 ( -601 RelayToClientMsg::Restarting { -602 reconnect_in: Duration::from_millis(10), -603 try_for: Duration::from_millis(20), -604 } -605 .write_to(Vec::new()), -606 "0c 00 00 00 0a 00 00 00 14", -607 ), -608 ]); -609 -610 Ok(()) -611 } -612 -613 #[test] -614 fn test_client_server_frames_snapshot() -> Result { -615 let client_key = SecretKey::from_bytes(&[42u8; 32]); -616 -617 check_expected_bytes(vec![ -618 ( -619 ClientToRelayMsg::Ping([42u8; 8]).write_to(Vec::new()), -620 "09 2a 2a 2a 2a 2a 2a 2a 2a", -621 ), -622 ( -623 ClientToRelayMsg::Pong([42u8; 8]).write_to(Vec::new()), -624 "0a 2a 2a 2a 2a 2a 2a 2a 2a", -625 ), -626 ( -627 ClientToRelayMsg::Datagrams { -628 dst_node_id: client_key.public(), -629 datagrams: Datagrams { -630 ecn: Some(quinn::EcnCodepoint::Ce), -631 segment_size: NonZeroU16::new(6), -632 contents: "Hello World!".into(), -633 }, -634 } -635 .write_to(Vec::new()), -636 // frame type -637 // public key first 16 bytes -638 // public key second 16 bytes -639 // ECN byte -640 // Segment size -641 // hello world contents -642 "05 -643 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 -644 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 -645 03 -646 00 06 -647 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", -648 ), -649 ( -650 ClientToRelayMsg::Datagrams { -651 dst_node_id: client_key.public(), -652 datagrams: Datagrams { -653 ecn: Some(quinn::EcnCodepoint::Ce), -654 segment_size: None, -655 contents: "Hello World!".into(), -656 }, -657 } -658 .write_to(Vec::new()), -659 // frame type -660 // public key first 16 bytes -661 // public key second 16 bytes -662 // ECN byte -663 // hello world contents -664 "04 -665 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 -666 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 -667 03 -668 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", -669 ), -670 ]); -671 -672 Ok(()) -673 } -674} -675 -676#[cfg(all(test, feature = "server"))] -677mod proptests { -678 use iroh_base::SecretKey; -679 use proptest::prelude::*; -680 -681 use super::*; +512 use super::*; +513 +514 fn check_expected_bytes(frames: Vec<(Vec<u8>, &str)>) { +515 for (bytes, expected_hex) in frames { +516 let stripped: Vec<u8> = expected_hex +517 .chars() +518 .filter_map(|s| { +519 if s.is_ascii_whitespace() { +520 None +521 } else { +522 Some(s as u8) +523 } +524 }) +525 .collect(); +526 let expected_bytes = HEXLOWER.decode(&stripped).unwrap(); +527 assert_eq!(HEXLOWER.encode(&bytes), HEXLOWER.encode(&expected_bytes)); +528 } +529 } +530 +531 #[test] +532 fn test_server_client_frames_snapshot() -> Result { +533 let client_key = SecretKey::from_bytes(&[42u8; 32]); +534 +535 check_expected_bytes(vec![ +536 ( +537 RelayToClientMsg::Health { +538 problem: "Hello? Yes this is dog.".into(), +539 } +540 .write_to(Vec::new()), +541 "0b 48 65 6c 6c 6f 3f 20 59 65 73 20 74 68 69 73 +542 20 69 73 20 64 6f 67 2e", +543 ), +544 ( +545 RelayToClientMsg::NodeGone(client_key.public()).write_to(Vec::new()), +546 "08 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e +547 a7 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d +548 61", +549 ), +550 ( +551 RelayToClientMsg::Ping([42u8; 8]).write_to(Vec::new()), +552 "09 2a 2a 2a 2a 2a 2a 2a 2a", +553 ), +554 ( +555 RelayToClientMsg::Pong([42u8; 8]).write_to(Vec::new()), +556 "0a 2a 2a 2a 2a 2a 2a 2a 2a", +557 ), +558 ( +559 RelayToClientMsg::Datagrams { +560 remote_node_id: client_key.public(), +561 datagrams: Datagrams { +562 ecn: Some(quinn::EcnCodepoint::Ce), +563 segment_size: NonZeroU16::new(6), +564 contents: "Hello World!".into(), +565 }, +566 } +567 .write_to(Vec::new()), +568 // frame type +569 // public key first 16 bytes +570 // public key second 16 bytes +571 // ECN byte +572 // segment size +573 // hello world contents bytes +574 "07 +575 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 +576 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 +577 03 +578 00 06 +579 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", +580 ), +581 ( +582 RelayToClientMsg::Datagrams { +583 remote_node_id: client_key.public(), +584 datagrams: Datagrams { +585 ecn: Some(quinn::EcnCodepoint::Ce), +586 segment_size: None, +587 contents: "Hello World!".into(), +588 }, +589 } +590 .write_to(Vec::new()), +591 // frame type +592 // public key first 16 bytes +593 // public key second 16 bytes +594 // ECN byte +595 // hello world contents bytes +596 "06 +597 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 +598 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 +599 03 +600 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", +601 ), +602 ( +603 RelayToClientMsg::Restarting { +604 reconnect_in: Duration::from_millis(10), +605 try_for: Duration::from_millis(20), +606 } +607 .write_to(Vec::new()), +608 "0c 00 00 00 0a 00 00 00 14", +609 ), +610 ]); +611 +612 Ok(()) +613 } +614 +615 #[test] +616 fn test_client_server_frames_snapshot() -> Result { +617 let client_key = SecretKey::from_bytes(&[42u8; 32]); +618 +619 check_expected_bytes(vec![ +620 ( +621 ClientToRelayMsg::Ping([42u8; 8]).write_to(Vec::new()), +622 "09 2a 2a 2a 2a 2a 2a 2a 2a", +623 ), +624 ( +625 ClientToRelayMsg::Pong([42u8; 8]).write_to(Vec::new()), +626 "0a 2a 2a 2a 2a 2a 2a 2a 2a", +627 ), +628 ( +629 ClientToRelayMsg::Datagrams { +630 dst_node_id: client_key.public(), +631 datagrams: Datagrams { +632 ecn: Some(quinn::EcnCodepoint::Ce), +633 segment_size: NonZeroU16::new(6), +634 contents: "Hello World!".into(), +635 }, +636 } +637 .write_to(Vec::new()), +638 // frame type +639 // public key first 16 bytes +640 // public key second 16 bytes +641 // ECN byte +642 // Segment size +643 // hello world contents +644 "05 +645 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 +646 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 +647 03 +648 00 06 +649 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", +650 ), +651 ( +652 ClientToRelayMsg::Datagrams { +653 dst_node_id: client_key.public(), +654 datagrams: Datagrams { +655 ecn: Some(quinn::EcnCodepoint::Ce), +656 segment_size: None, +657 contents: "Hello World!".into(), +658 }, +659 } +660 .write_to(Vec::new()), +661 // frame type +662 // public key first 16 bytes +663 // public key second 16 bytes +664 // ECN byte +665 // hello world contents +666 "04 +667 19 7f 6b 23 e1 6c 85 32 c6 ab c8 38 fa cd 5e a7 +668 89 be 0c 76 b2 92 03 34 03 9b fa 8b 3d 36 8d 61 +669 03 +670 48 65 6c 6c 6f 20 57 6f 72 6c 64 21", +671 ), +672 ]); +673 +674 Ok(()) +675 } +676} +677 +678#[cfg(all(test, feature = "server"))] +679mod proptests { +680 use iroh_base::SecretKey; +681 use proptest::prelude::*; 682 -683 fn secret_key() -> impl Strategy<Value = SecretKey> { -684 prop::array::uniform32(any::<u8>()).prop_map(SecretKey::from) -685 } -686 -687 fn key() -> impl Strategy<Value = NodeId> { -688 secret_key().prop_map(|key| key.public()) -689 } -690 -691 fn ecn() -> impl Strategy<Value = Option<quinn_proto::EcnCodepoint>> { -692 (0..=3).prop_map(|n| match n { -693 1 => Some(quinn_proto::EcnCodepoint::Ce), -694 2 => Some(quinn_proto::EcnCodepoint::Ect0), -695 3 => Some(quinn_proto::EcnCodepoint::Ect1), -696 _ => None, -697 }) -698 } -699 -700 fn datagrams() -> impl Strategy<Value = Datagrams> { -701 // The max payload size (conservatively, since with segment_size = 0 we'd have slightly more space) -702 const MAX_PAYLOAD_SIZE: usize = MAX_PACKET_SIZE - NodeId::LENGTH - 1 /* ECN bytes */ - 2 /* segment size */; -703 ( -704 ecn(), -705 prop::option::of(MAX_PAYLOAD_SIZE / 20..MAX_PAYLOAD_SIZE), -706 prop::collection::vec(any::<u8>(), 0..MAX_PAYLOAD_SIZE), -707 ) -708 .prop_map(|(ecn, segment_size, data)| Datagrams { -709 ecn, -710 segment_size: segment_size -711 .map(|ss| std::cmp::min(data.len(), ss) as u16) -712 .and_then(NonZeroU16::new), -713 contents: Bytes::from(data), -714 }) -715 } -716 -717 /// Generates a random valid frame -718 fn server_client_frame() -> impl Strategy<Value = RelayToClientMsg> { -719 let recv_packet = (key(), datagrams()).prop_map(|(remote_node_id, datagrams)| { -720 RelayToClientMsg::Datagrams { -721 remote_node_id, -722 datagrams, -723 } -724 }); -725 let node_gone = key().prop_map(RelayToClientMsg::NodeGone); -726 let ping = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Ping); -727 let pong = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Pong); -728 let health = ".{0,65536}" -729 .prop_filter("exceeds MAX_PACKET_SIZE", |s| { -730 s.len() < MAX_PACKET_SIZE // a single unicode character can match a regex "." but take up multiple bytes -731 }) -732 .prop_map(|problem| RelayToClientMsg::Health { problem }); -733 let restarting = (any::<u32>(), any::<u32>()).prop_map(|(reconnect_in, try_for)| { -734 RelayToClientMsg::Restarting { -735 reconnect_in: Duration::from_millis(reconnect_in.into()), -736 try_for: Duration::from_millis(try_for.into()), -737 } -738 }); -739 prop_oneof![recv_packet, node_gone, ping, pong, health, restarting] -740 } -741 -742 fn client_server_frame() -> impl Strategy<Value = ClientToRelayMsg> { -743 let send_packet = -744 (key(), datagrams()).prop_map(|(dst_node_id, datagrams)| ClientToRelayMsg::Datagrams { -745 dst_node_id, -746 datagrams, -747 }); -748 let ping = prop::array::uniform8(any::<u8>()).prop_map(ClientToRelayMsg::Ping); -749 let pong = prop::array::uniform8(any::<u8>()).prop_map(ClientToRelayMsg::Pong); -750 prop_oneof![send_packet, ping, pong] -751 } -752 -753 proptest! { -754 #[test] -755 fn server_client_frame_roundtrip(frame in server_client_frame()) { -756 let encoded = frame.to_bytes().freeze(); -757 let decoded = RelayToClientMsg::from_bytes(encoded, &KeyCache::test()).unwrap(); -758 prop_assert_eq!(frame, decoded); -759 } -760 -761 #[test] -762 fn client_server_frame_roundtrip(frame in client_server_frame()) { -763 let encoded = frame.to_bytes().freeze(); -764 let decoded = ClientToRelayMsg::from_bytes(encoded, &KeyCache::test()).unwrap(); -765 prop_assert_eq!(frame, decoded); -766 } -767 -768 #[test] -769 fn server_client_frame_encoded_len(frame in server_client_frame()) { -770 let claimed_encoded_len = frame.encoded_len(); -771 let actual_encoded_len = frame.to_bytes().len(); -772 prop_assert_eq!(claimed_encoded_len, actual_encoded_len); -773 } -774 -775 #[test] -776 fn client_server_frame_encoded_len(frame in client_server_frame()) { -777 let claimed_encoded_len = frame.encoded_len(); -778 let actual_encoded_len = frame.to_bytes().len(); -779 prop_assert_eq!(claimed_encoded_len, actual_encoded_len); -780 } -781 -782 #[test] -783 fn datagrams_encoded_len(datagrams in datagrams()) { -784 let claimed_encoded_len = datagrams.encoded_len(); -785 let actual_encoded_len = datagrams.write_to(Vec::new()).len(); -786 prop_assert_eq!(claimed_encoded_len, actual_encoded_len); -787 } -788 } -789}

\ No newline at end of file +683 use super::*; +684 +685 fn secret_key() -> impl Strategy<Value = SecretKey> { +686 prop::array::uniform32(any::<u8>()).prop_map(SecretKey::from) +687 } +688 +689 fn key() -> impl Strategy<Value = NodeId> { +690 secret_key().prop_map(|key| key.public()) +691 } +692 +693 fn ecn() -> impl Strategy<Value = Option<quinn_proto::EcnCodepoint>> { +694 (0..=3).prop_map(|n| match n { +695 1 => Some(quinn_proto::EcnCodepoint::Ce), +696 2 => Some(quinn_proto::EcnCodepoint::Ect0), +697 3 => Some(quinn_proto::EcnCodepoint::Ect1), +698 _ => None, +699 }) +700 } +701 +702 fn datagrams() -> impl Strategy<Value = Datagrams> { +703 // The max payload size (conservatively, since with segment_size = 0 we'd have slightly more space) +704 const MAX_PAYLOAD_SIZE: usize = MAX_PACKET_SIZE - NodeId::LENGTH - 1 /* ECN bytes */ - 2 /* segment size */; +705 ( +706 ecn(), +707 prop::option::of(MAX_PAYLOAD_SIZE / 20..MAX_PAYLOAD_SIZE), +708 prop::collection::vec(any::<u8>(), 0..MAX_PAYLOAD_SIZE), +709 ) +710 .prop_map(|(ecn, segment_size, data)| Datagrams { +711 ecn, +712 segment_size: segment_size +713 .map(|ss| std::cmp::min(data.len(), ss) as u16) +714 .and_then(NonZeroU16::new), +715 contents: Bytes::from(data), +716 }) +717 } +718 +719 /// Generates a random valid frame +720 fn server_client_frame() -> impl Strategy<Value = RelayToClientMsg> { +721 let recv_packet = (key(), datagrams()).prop_map(|(remote_node_id, datagrams)| { +722 RelayToClientMsg::Datagrams { +723 remote_node_id, +724 datagrams, +725 } +726 }); +727 let node_gone = key().prop_map(RelayToClientMsg::NodeGone); +728 let ping = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Ping); +729 let pong = prop::array::uniform8(any::<u8>()).prop_map(RelayToClientMsg::Pong); +730 let health = ".{0,65536}" +731 .prop_filter("exceeds MAX_PACKET_SIZE", |s| { +732 s.len() < MAX_PACKET_SIZE // a single unicode character can match a regex "." but take up multiple bytes +733 }) +734 .prop_map(|problem| RelayToClientMsg::Health { problem }); +735 let restarting = (any::<u32>(), any::<u32>()).prop_map(|(reconnect_in, try_for)| { +736 RelayToClientMsg::Restarting { +737 reconnect_in: Duration::from_millis(reconnect_in.into()), +738 try_for: Duration::from_millis(try_for.into()), +739 } +740 }); +741 prop_oneof![recv_packet, node_gone, ping, pong, health, restarting] +742 } +743 +744 fn client_server_frame() -> impl Strategy<Value = ClientToRelayMsg> { +745 let send_packet = +746 (key(), datagrams()).prop_map(|(dst_node_id, datagrams)| ClientToRelayMsg::Datagrams { +747 dst_node_id, +748 datagrams, +749 }); +750 let ping = prop::array::uniform8(any::<u8>()).prop_map(ClientToRelayMsg::Ping); +751 let pong = prop::array::uniform8(any::<u8>()).prop_map(ClientToRelayMsg::Pong); +752 prop_oneof![send_packet, ping, pong] +753 } +754 +755 proptest! { +756 #[test] +757 fn server_client_frame_roundtrip(frame in server_client_frame()) { +758 let encoded = frame.to_bytes().freeze(); +759 let decoded = RelayToClientMsg::from_bytes(encoded, &KeyCache::test()).unwrap(); +760 prop_assert_eq!(frame, decoded); +761 } +762 +763 #[test] +764 fn client_server_frame_roundtrip(frame in client_server_frame()) { +765 let encoded = frame.to_bytes().freeze(); +766 let decoded = ClientToRelayMsg::from_bytes(encoded, &KeyCache::test()).unwrap(); +767 prop_assert_eq!(frame, decoded); +768 } +769 +770 #[test] +771 fn server_client_frame_encoded_len(frame in server_client_frame()) { +772 let claimed_encoded_len = frame.encoded_len(); +773 let actual_encoded_len = frame.to_bytes().len(); +774 prop_assert_eq!(claimed_encoded_len, actual_encoded_len); +775 } +776 +777 #[test] +778 fn client_server_frame_encoded_len(frame in client_server_frame()) { +779 let claimed_encoded_len = frame.encoded_len(); +780 let actual_encoded_len = frame.to_bytes().len(); +781 prop_assert_eq!(claimed_encoded_len, actual_encoded_len); +782 } +783 +784 #[test] +785 fn datagrams_encoded_len(datagrams in datagrams()) { +786 let claimed_encoded_len = datagrams.encoded_len(); +787 let actual_encoded_len = datagrams.write_to(Vec::new()).len(); +788 prop_assert_eq!(claimed_encoded_len, actual_encoded_len); +789 } +790 } +791}
\ No newline at end of file