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

Feature: Serve::tcp_nodelay #2653

Merged
merged 5 commits into from
Apr 1, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

# Unreleased

- **added:** `axum::serve::Serve::tcp_nodelay` and `axum::serve::WithGracefulShutdown::tcp_nodelay` ([#2653])
- **fixed:** Fixed layers being cloned when calling `axum::serve` directly with
a `Router` or `MethodRouter` ([#2586])

[#2653]: https://github.com/tokio-rs/axum/pull/2653
[#2586]: https://github.com/tokio-rs/axum/pull/2586

# 0.7.4 (13. January, 2024)
Expand Down
95 changes: 95 additions & 0 deletions axum/src/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ where
Serve {
tcp_listener,
make_service,
tcp_nodelay: None,
_marker: PhantomData,
}
}
Expand All @@ -112,6 +113,7 @@ where
pub struct Serve<M, S> {
tcp_listener: TcpListener,
make_service: M,
tcp_nodelay: Option<bool>,
_marker: PhantomData<S>,
}

Expand Down Expand Up @@ -146,9 +148,35 @@ impl<M, S> Serve<M, S> {
tcp_listener: self.tcp_listener,
make_service: self.make_service,
signal,
tcp_nodelay: self.tcp_nodelay,
_marker: PhantomData,
}
}

/// Instructs the server to set the value of the `TCP_NODELAY` option on every accepted connection.
///
/// See also [`TcpStream::set_nodelay`].
///
/// # Example
/// ```
/// use axum::{Router, routing::get};
///
/// # async {
/// let router = Router::new().route("/", get(|| async { "Hello, World!" }));
///
/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
/// axum::serve(listener, router)
/// .tcp_nodelay(true)
/// .await
/// .unwrap();
/// # };
/// ```
pub fn tcp_nodelay(self, nodelay: bool) -> Self {
Self {
tcp_nodelay: Some(nodelay),
..self
}
}
}

#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
Expand All @@ -160,12 +188,14 @@ where
let Self {
tcp_listener,
make_service,
tcp_nodelay,
_marker: _,
} = self;

f.debug_struct("Serve")
.field("tcp_listener", tcp_listener)
.field("make_service", make_service)
.field("tcp_nodelay", tcp_nodelay)
.finish()
}
}
Expand All @@ -186,6 +216,7 @@ where
let Self {
tcp_listener,
mut make_service,
tcp_nodelay,
_marker: _,
} = self;

Expand All @@ -194,6 +225,13 @@ where
Some(conn) => conn,
None => continue,
};

if let Some(nodelay) = tcp_nodelay {
if let Err(err) = tcp_stream.set_nodelay(nodelay) {
trace!("failed to set TCP_NODELAY on incoming connection: {err:#}");
}
}

let tcp_stream = TokioIo::new(tcp_stream);

poll_fn(|cx| make_service.poll_ready(cx))
Expand Down Expand Up @@ -240,9 +278,42 @@ pub struct WithGracefulShutdown<M, S, F> {
tcp_listener: TcpListener,
make_service: M,
signal: F,
tcp_nodelay: Option<bool>,
_marker: PhantomData<S>,
}

impl<M, S, F> WithGracefulShutdown<M, S, F> {
/// Instructs the server to set the value of the `TCP_NODELAY` option on every accepted connection.
///
/// See also [`TcpStream::set_nodelay`].
///
/// # Example
/// ```
/// use axum::{Router, routing::get};
///
/// # async {
/// let router = Router::new().route("/", get(|| async { "Hello, World!" }));
///
/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
/// axum::serve(listener, router)
/// .with_graceful_shutdown(shutdown_signal())
/// .tcp_nodelay(true)
/// .await
/// .unwrap();
/// # };
///
/// async fn shutdown_signal() {
/// // ...
/// }
/// ```
pub fn tcp_nodelay(self, nodelay: bool) -> Self {
Self {
tcp_nodelay: Some(nodelay),
..self
}
}
}

#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
impl<M, S, F> Debug for WithGracefulShutdown<M, S, F>
where
Expand All @@ -255,13 +326,15 @@ where
tcp_listener,
make_service,
signal,
tcp_nodelay,
_marker: _,
} = self;

f.debug_struct("WithGracefulShutdown")
.field("tcp_listener", tcp_listener)
.field("make_service", make_service)
.field("signal", signal)
.field("tcp_nodelay", tcp_nodelay)
.finish()
}
}
Expand All @@ -283,6 +356,7 @@ where
tcp_listener,
mut make_service,
signal,
tcp_nodelay,
_marker: _,
} = self;

Expand Down Expand Up @@ -310,6 +384,13 @@ where
break;
}
};

if let Some(nodelay) = tcp_nodelay {
if let Err(err) = tcp_stream.set_nodelay(nodelay) {
trace!("failed to set TCP_NODELAY on incoming connection: {err:#}");
}
}

let tcp_stream = TokioIo::new(tcp_stream);

trace!("connection {remote_addr} accepted");
Expand Down Expand Up @@ -558,6 +639,20 @@ mod tests {
TcpListener::bind(addr).await.unwrap(),
handler.into_make_service_with_connect_info::<SocketAddr>(),
);

// nodelay
serve(
TcpListener::bind(addr).await.unwrap(),
handler.into_service(),
)
.tcp_nodelay(true);

serve(
TcpListener::bind(addr).await.unwrap(),
handler.into_service(),
)
.with_graceful_shutdown(async { /*...*/ })
.tcp_nodelay(true);
}

async fn handler() {}
Expand Down
Loading