Skip to content

Commit dedb994

Browse files
authored
fix: possible race condition during graceful shutdown (#780)
This PR just makes the behavior more reliable, also should address #661 The possible race condition: - `notify_waiters()` will notify only already registered waiters Thus, if it's called after ```rust drop(acceptor); if alive_connections.load(Ordering::Acquire) > 0 { ``` But before `notify.notified()` - it might be never notified.
1 parent c4137ed commit dedb994

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

poem/src/server.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ where
166166
let server_graceful_shutdown_token = server_graceful_shutdown_token.clone();
167167

168168
tokio::spawn(async move {
169-
let serve_connection = serve_connection(socket, local_addr, remote_addr, scheme, ep, server_graceful_shutdown_token, idle_timeout);
169+
let serve_connection = serve_connection(socket, local_addr, remote_addr, scheme, ep, server_graceful_shutdown_token.clone(), idle_timeout);
170170

171171
if timeout.is_some() {
172172
tokio::select! {
@@ -178,8 +178,11 @@ where
178178
}
179179

180180
if alive_connections.fetch_sub(1, Ordering::Acquire) == 1 {
181-
// We have to notify only if there is a registered waiter on shutdown
182-
notify.notify_waiters();
181+
// notify only if shutdown is initiated, to prevent notification when server is active.
182+
// It's a valid state to have 0 alive connections when server is not shutting down.
183+
if server_graceful_shutdown_token.is_cancelled() {
184+
notify.notify_one();
185+
}
183186
}
184187
});
185188
}

0 commit comments

Comments
 (0)