Skip to content
Merged
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
20 changes: 18 additions & 2 deletions src/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,12 @@ impl Acceptor for tokio::net::TcpListener {

#[inline]
fn accept(&self) -> impl Future<Output = tokio::io::Result<Self::Socket>> + Send {
tokio::net::TcpListener::accept(self).and_then(|(s, _)| futures::future::ok(s))
tokio::net::TcpListener::accept(self).and_then(|(s, _)| {
// Failing here would end the accept loop: a connection the peer
// already reset can refuse it.
set_nodelay(&s, s.set_nodelay(true));
futures::future::ok(s)
})
}

#[inline]
Expand All @@ -124,12 +129,23 @@ impl Connection for std::net::TcpStream {
}
}

/// Report a failure to disable Nagle's algorithm on `stream`, which is not worth
/// failing the connection over. Without it, the last segment of a message
/// spanning several waits on the peer's delayed ACK.
fn set_nodelay(stream: &impl std::fmt::Debug, result: std::io::Result<()>) {
if let Err(e) = result {
warn!("failed to set TCP_NODELAY on {stream:?}: {e}");
}
}

// Helper function to create a stream. Uses dynamic dispatch to make code more
// readable.
pub fn connect(addr: &SocketAddr) -> std::io::Result<Box<dyn Connection>> {
match addr {
SocketAddr::Net(addr) => {
std::net::TcpStream::connect(addr).map(|s| Box::new(s) as Box<dyn Connection>)
let stream = std::net::TcpStream::connect(addr)?;
set_nodelay(&stream, stream.set_nodelay(true));
Ok(Box::new(stream) as Box<dyn Connection>)
}
#[cfg(unix)]
SocketAddr::Unix(p) => {
Expand Down
39 changes: 35 additions & 4 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -674,10 +674,12 @@ where
W: Write,
S: Serialize,
{
let bytes = bincode::serialize(&data)?;
let mut len = [0; 4];
BigEndian::write_u32(&mut len, bytes.len() as u32);
writer.write_all(&len)?;
// One write: with TCP_NODELAY, writing the length on its own would send it
// as a separate packet whenever the body overflows the caller's BufWriter.
let mut bytes = vec![0; 4];
bincode::serialize_into(&mut bytes, &data)?;
let len = (bytes.len() - 4) as u32;
BigEndian::write_u32(&mut bytes[..4], len);
writer.write_all(&bytes)?;
writer.flush()?;
Ok(())
Expand Down Expand Up @@ -2651,4 +2653,33 @@ mod tests {
.unwrap();
assert_ne!(h1, h2);
}

#[test]
fn test_write_length_prefixed_bincode_single_write() {
use super::write_length_prefixed_bincode;
use byteorder::{BigEndian, ByteOrder};
use std::io::Write;

#[derive(Default)]
struct Writes(Vec<Vec<u8>>);
impl Write for Writes {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.push(buf.to_vec());
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

let data = vec![7u8; 20_000];
let mut writes = Writes::default();
write_length_prefixed_bincode(&mut writes, &data).unwrap();

assert_eq!(writes.0.len(), 1);
let frame = &writes.0[0];
let body = bincode::serialize(&data).unwrap();
assert_eq!(BigEndian::read_u32(&frame[..4]) as usize, body.len());
assert_eq!(&frame[4..], &body[..]);
}
}
Loading