From c4332dbfc7c772f75b9df3656fd39b09100ced33 Mon Sep 17 00:00:00 2001 From: Thomas Tanon Date: Wed, 25 Nov 2026 15:47:10 +0100 Subject: [PATCH] fix: stop processing queries after a TCP client disconnects The server does not read from the socket while processing a query. A long-running query can keep running after its client disconnects, until it tries to send a result. Watch a clone of the underlying TCP socket in parallel with message processing. When the socket reports that its read side has closed, drop the connection-processing future and any active result stream. This also covers TLS connections over TCP. --- Cargo.toml | 4 + src/tokio/server.rs | 36 ++++++- tests/client_disconnection_test.rs | 148 +++++++++++++++++++++++++++++ 3 files changed, 185 insertions(+), 3 deletions(-) create mode 100644 tests/client_disconnection_test.rs diff --git a/Cargo.toml b/Cargo.toml index f26c4216..8fc4eabb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -215,6 +215,10 @@ required-features = ["server-api"] name = "fatal_error_test" required-features = ["server-api"] +[[test]] +name = "client_disconnection_test" +required-features = ["server-api"] + [[example]] name = "dynamic_auth" required-features = ["server-api-aws-lc-rs"] diff --git a/src/tokio/server.rs b/src/tokio/server.rs index 285acb65..2519be0f 100644 --- a/src/tokio/server.rs +++ b/src/tokio/server.rs @@ -6,7 +6,7 @@ use std::task::{Context, Poll}; use futures::{SinkExt, StreamExt}; #[cfg(any(feature = "_ring", feature = "_aws-lc-rs"))] use rustls_pki_types::CertificateDer; -use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::io::{AsyncRead, AsyncWrite, Interest}; use tokio::net::TcpStream; #[cfg(unix)] use tokio::net::UnixStream; @@ -676,6 +676,19 @@ where Ok(()) } +/// Resolves once the client closes `socket`, a clone of its socket, without reading from it. +async fn disconnected(socket: TcpStream) { + while let Ok(ready) = socket.ready(Interest::READABLE).await { + if ready.is_read_closed() { + return; + } + // Leaves the messages of the client to the original socket, and waits for the next event + let _ = socket.try_io(Interest::READABLE, || { + Err::<(), _>(io::ErrorKind::WouldBlock.into()) + }); + } +} + /// Process a TCP client connection with optional TLS negotiation. pub async fn process_socket( tcp_socket: TcpStream, @@ -690,6 +703,8 @@ where let startup_timeout = sleep(Duration::from_millis(STARTUP_TIMEOUT_MILLIS)); tokio::pin!(startup_timeout); + let (tcp_socket, watched_tcp_socket) = clone_socket(tcp_socket)?; + // this function will process postgres ssl negotiation and consume the first // SslRequest packet if detected. let socket = tokio::select! { @@ -706,8 +721,23 @@ where return Ok(()); }; - process_socket_messages!(socket, startup_timeout, handlers); - Ok(()) + // The socket is not read while a message is processed, so a query would keep running after + // its client is gone until it fails to send its results: stop processing on disconnection. + let messages = async { + process_socket_messages!(socket, startup_timeout, handlers); + Ok(()) + }; + tokio::select! { + result = messages => result, + () = disconnected(watched_tcp_socket) => Ok(()), + } +} + +fn clone_socket(tcp_socket: TcpStream) -> Result<(TcpStream, TcpStream), io::Error> { + let tcp_socket = tcp_socket.into_std()?; + let cloned_socket = TcpStream::from_std(tcp_socket.try_clone()?)?; + let tcp_socket = TcpStream::from_std(tcp_socket)?; + Ok((tcp_socket, cloned_socket)) } #[cfg(all(test, any(feature = "_ring", feature = "_aws-lc-rs")))] diff --git a/tests/client_disconnection_test.rs b/tests/client_disconnection_test.rs new file mode 100644 index 00000000..3efa2c7e --- /dev/null +++ b/tests/client_disconnection_test.rs @@ -0,0 +1,148 @@ +//! A query is dropped once its client disconnects, even if it never sends it anything, like a +//! query aggregating a large table before returning its first row. + +use std::fmt::Debug; +use std::sync::Arc; +use std::task::Poll; +use std::time::Duration; + +use async_trait::async_trait; +use bytes::BytesMut; +use futures::{Sink, stream}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::Notify; +use tokio::time::timeout; + +use pgwire::api::auth::StartupHandler; +use pgwire::api::auth::noop::NoopStartupHandler; +use pgwire::api::query::SimpleQueryHandler; +use pgwire::api::results::{QueryResponse, Response}; +use pgwire::api::{ClientInfo, PgWireServerHandlers}; +use pgwire::error::{PgWireError, PgWireResult}; +use pgwire::messages::simplequery::Query; +use pgwire::messages::startup::Startup; +use pgwire::messages::{Message, PgWireBackendMessage}; +use pgwire::tokio::process_socket; + +/// Answers every query with rows that never come. +#[derive(Default)] +struct EndlessProcessor { + /// Held by the row stream until it is dropped. + row_stream_polled: Arc, +} + +impl NoopStartupHandler for EndlessProcessor {} + +#[async_trait] +impl SimpleQueryHandler for EndlessProcessor { + async fn do_query(&self, _client: &mut C, _query: &str) -> PgWireResult> + where + C: ClientInfo + Sink + Unpin + Send + Sync, + C::Error: Debug, + PgWireError: From<>::Error>, + { + let row_stream_polled = self.row_stream_polled.clone(); + Ok(vec![Response::Query(QueryResponse::new( + Arc::new(vec![]), + stream::poll_fn(move |_| { + row_stream_polled.notify_one(); + Poll::Pending + }), + ))]) + } +} + +struct Handlers(Arc); + +impl PgWireServerHandlers for Handlers { + fn startup_handler(&self) -> Arc { + self.0.clone() + } + + fn simple_query_handler(&self) -> Arc { + self.0.clone() + } +} + +async fn send(client: &mut TcpStream, message: &impl Message) { + let mut buf = BytesMut::new(); + message.encode(&mut buf).unwrap(); + client.write_all(&buf).await.unwrap(); +} + +/// Reads backend messages until a ReadyForQuery. +async fn read_until_ready_for_query(client: &mut TcpStream) { + loop { + let tag = client.read_u8().await.unwrap(); + let len = client.read_i32().await.unwrap() as usize; + let mut body = vec![0; len - 4]; + client.read_exact(&mut body).await.unwrap(); + if tag == b'Z' { + return; + } + } +} + +#[tokio::test] +async fn client_disconnection_drops_running_query() { + assert_disconnection_drops_running_query(false).await; +} + +#[tokio::test] +async fn client_disconnection_drops_running_query_with_unread_data() { + assert_disconnection_drops_running_query(true).await; +} + +async fn assert_disconnection_drops_running_query(send_pipelined_query: bool) { + let processor = Arc::new(EndlessProcessor::default()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let mut server = tokio::spawn({ + let handlers = Handlers(processor.clone()); + async move { + let (stream, _) = listener.accept().await.unwrap(); + process_socket(stream, None, handlers).await + } + }); + + let mut client = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + let mut startup = Startup::new(); + startup + .parameters + .insert("user".to_owned(), "postgres".to_owned()); + send(&mut client, &startup).await; + timeout( + Duration::from_secs(5), + read_until_ready_for_query(&mut client), + ) + .await + .expect("the server did not finish startup"); + send(&mut client, &Query::new("SELECT 1".to_owned())).await; + timeout( + Duration::from_secs(5), + processor.row_stream_polled.notified(), + ) + .await + .expect("the server did not start polling the query results"); + + if send_pipelined_query { + // Keep the client connected long enough for the watcher to observe unread data. + send(&mut client, &Query::new("SELECT 2".to_owned())).await; + timeout(Duration::from_millis(500), &mut server) + .await + .expect_err("the server must keep serving a connected client"); + } + + drop(client); + timeout(Duration::from_secs(5), server) + .await + .expect("the server kept running the query of a disconnected client") + .unwrap() + .unwrap(); + assert_eq!( + Arc::strong_count(&processor.row_stream_polled), + 1, + "the query must be dropped" + ); +}