Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement UdpSocket::poll_recv_from #211

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/net/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ use crate::{
ToSocketAddrs, World, TRACING_TARGET,
};

use std::future::Future;
use std::pin::pin;
use std::task::{ready, Context, Poll};
use std::{
cmp,
io::{self, Error, ErrorKind, Result},
net::{Ipv6Addr, SocketAddr},
};
use tokio::io::ReadBuf;

/// A simulated UDP socket.
///
Expand Down Expand Up @@ -60,6 +64,22 @@ impl Rx {
Ok((limit, datagram, origin))
}

/// Tries to receive from either the buffered message or the mpsc channel.
fn poll_recv_from(
&mut self,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<Result<SocketAddr>> {
let (datagram, origin) = if let Some(datagram) = self.buffer.take() {
datagram
} else {
ready!(self.recv.poll_recv(cx)).expect("sender should never be dropped")
};
let limit = cmp::min(buf.remaining(), datagram.0.len());
buf.put_slice(&datagram.0[..limit]);
Poll::Ready(Ok(origin))
}

/// Waits for the socket to become readable.
///
/// This function is usually paired with `try_recv_from()`.
Expand Down Expand Up @@ -247,6 +267,21 @@ impl UdpSocket {
Ok((limit, origin))
}

/// Tries to receive a single datagram message on the socket. On success,
/// appends to `buf` and returns the origin.
///
/// If a message is too long to fit in the unfilled part of `buf` ,
/// excess bytes may be discarded.
Comment on lines +273 to +274
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this also doesn't match the upstream — I think its critical to maintain precise fidelity. We'll need to keep the data around somewhere to avoid discarding it.

The only hack I can think of offhand is to keep a Vec<u8> or similar inside of of Rx. If there is overflow, write data there and immediately schedule a wakeup.

Ultimately, I think dropping data here is too much of a footgun to merge as is.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I was under the impression that is what tokio does. Does it just deliver the remaining bytes on the next receive call then? I was sure I had had issues with truncated messages in tokio in the past, but it might not have been UDP. I agree, we should match tokio behavior exactly. There is already a buffer in there, so keeping it for the next call would be straight forward.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah! I read a lot of code to get to the bottom of this. This does in fact seem to be the (undocumented from Tokio's side) behavior. The exact semantics are platform dependent and also depend on the type of socket you are connected to. Windows will definitely drop them, it seems like Linux can do either.

I think Turmoil dropping these bytes is the harshest and correct behavior (but maybe we should log as we do it?)

https://linux.die.net/man/2/recvfrom

If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the right action here is:

  • Capture that this is the behavior in a test
  • Log or otherwise communicate to the turmoil user that this happened so they can get to the bottom of the problem more easily

pub fn poll_recv_from(
&self,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<Result<SocketAddr>> {
let lock_future = pin!(self.rx.lock());
let mut rx = ready!(lock_future.poll(cx));
rx.poll_recv_from(cx, buf)
}

/// Waits for the socket to become readable.
///
/// This function is usually paired with `try_recv_from()`.
Expand Down
60 changes: 59 additions & 1 deletion tests/udp.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use std::future::poll_fn;
use std::task::Poll;
use std::{
io::{self, ErrorKind},
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
rc::Rc,
sync::{atomic::AtomicUsize, atomic::Ordering},
time::Duration,
};

use tokio::io::ReadBuf;
use tokio::time::sleep;
use tokio::{sync::oneshot, time::timeout};
use turmoil::{
lookup,
Expand Down Expand Up @@ -159,6 +162,61 @@ fn try_ping_pong() -> Result {
sim.run()
}

#[test]
fn poll_recv() -> Result {
let mut sim = Builder::new().build();

sim.client("server", async {
let expected_origin = lookup("client");
let sock = bind().await?;
let buffer = &mut [0u8; 64];
let mut read_buf = ReadBuf::new(buffer);

poll_fn(|cx| {
let received = sock.poll_recv_from(cx, &mut read_buf);
assert!(matches!(received, Poll::Pending));
Poll::Ready(())
})
.await;

// before client sends
sleep(Duration::from_millis(1000)).await;
// after client sends

poll_fn(|cx| {
let received = sock.poll_recv_from(cx, &mut read_buf);
assert!(matches!(received , Poll::Ready(Ok(x)) if x.ip() == expected_origin));
Poll::Ready(())
})
.await;
sock.readable().await?;
poll_fn(|cx| {
let received = sock.poll_recv_from(cx, &mut read_buf);
assert!(matches!(received , Poll::Ready(Ok(x)) if x.ip() == expected_origin));
Poll::Ready(())
})
.await;
poll_fn(|cx| {
let received = sock.poll_recv_from(cx, &mut read_buf);
assert!(matches!(received, Poll::Pending));
Poll::Ready(())
})
.await;
assert_eq!(read_buf.filled(), b"pingping");
Ok(())
});

sim.client("client", async {
let sock = bind().await.unwrap();
sleep(Duration::from_millis(500)).await;
try_send_ping(&sock)?;
try_send_ping(&sock)?;
Ok(())
});

sim.run()
}

#[test]
fn recv_buf_is_clipped() -> Result {
let mut sim = Builder::new().build();
Expand Down