Skip to content

improve is_closed effectiveness #41

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

Open
wants to merge 3 commits into
base: neon
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
5 changes: 5 additions & 0 deletions postgres/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,11 @@ impl Client {
self.connection.block_on(self.client.batch_execute(query))
}

/// Check the connection is alive and wait for the confirmation.
pub fn check_connection(&mut self) -> Result<(), Error> {
self.connection.block_on(self.client.check_connection())
}

/// Begins a new database transaction.
///
/// The transaction will roll back by default - use the `commit` method to commit it.
Expand Down
21 changes: 21 additions & 0 deletions postgres/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,24 @@ fn check_send() {
is_send::<Statement>();
is_send::<Transaction<'_>>();
}

#[test]
fn is_closed() {
let mut client = Client::connect("host=localhost port=5433 user=postgres", NoTls).unwrap();
assert!(!client.is_closed());
client.check_connection().unwrap();

let row = client.query_one("select pg_backend_pid()", &[]).unwrap();
let pid: i32 = row.get(0);

{
let mut client2 = Client::connect("host=localhost port=5433 user=postgres", NoTls).unwrap();
client2
.query("SELECT pg_terminate_backend($1)", &[&pid])
.unwrap();
}

assert!(!client.is_closed());
client.check_connection().unwrap_err();
assert!(client.is_closed());
}
6 changes: 6 additions & 0 deletions tokio-postgres/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,12 @@ impl Client {
simple_query::batch_execute(self.inner(), query).await
}

/// Check the connection is alive and wait for the confirmation.
pub async fn check_connection(&self) -> Result<(), Error> {
// sync is a very quick message to test the connection health.
query::sync(self.inner()).await
}
Comment on lines +492 to +496

Choose a reason for hiding this comment

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

The Sync message affects the protocol state, it's not a simple "no-op" message. Per docs:

At completion of each series of extended-query messages, the frontend should issue a Sync message. This parameterless message causes the backend to close the current transaction if it's not inside a BEGIN/COMMIT transaction block (“close” meaning to commit if no error, or roll back if error). Then a ReadyForQuery response is issued. The purpose of Sync is to provide a resynchronization point for error recovery.

So we'll have to be careful to only call it when not in the middle of processing a query.

Copy link
Author

Choose a reason for hiding this comment

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

That's true, fortunately the query encoding on the client is always atomic


/// Begins a new database transaction.
///
/// The transaction will roll back by default - use the `commit` method to commit it.
Expand Down
29 changes: 21 additions & 8 deletions tokio-postgres/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,14 +318,7 @@ where
self.parameters.get(name).map(|s| &**s)
}

/// Polls for asynchronous messages from the server.
///
/// The server can send notices as well as notifications asynchronously to the client. Applications that wish to
/// examine those messages should use this method to drive the connection rather than its `Future` implementation.
///
/// Return values of `None` or `Some(Err(_))` are "terminal"; callers should not invoke this method again after
/// receiving one of those values.
pub fn poll_message(
fn poll_message_inner(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Option<Result<AsyncMessage, Error>>> {
Expand All @@ -343,6 +336,26 @@ where
},
}
}

/// Polls for asynchronous messages from the server.
///
/// The server can send notices as well as notifications asynchronously to the client. Applications that wish to
/// examine those messages should use this method to drive the connection rather than its `Future` implementation.
///
/// Return values of `None` or `Some(Err(_))` are "terminal"; callers should not invoke this method again after
/// receiving one of those values.
pub fn poll_message(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Option<Result<AsyncMessage, Error>>> {
match self.poll_message_inner(cx) {
nominal @ (Poll::Pending | Poll::Ready(Some(Ok(_)))) => nominal,
terminal @ (Poll::Ready(None) | Poll::Ready(Some(Err(_)))) => {
self.receiver.close();
terminal
}
}
}
}

impl<S, T> Future for Connection<S, T>
Expand Down
10 changes: 10 additions & 0 deletions tokio-postgres/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,13 @@ impl RowStream {
self.rows_affected
}
}

pub async fn sync(client: &InnerClient) -> Result<(), Error> {
let buf = Bytes::from_static(b"S\0\0\0\x04");
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;

match responses.next().await? {
Message::ReadyForQuery(_) => Ok(()),
_ => Err(Error::unexpected_message()),
}
}
6 changes: 6 additions & 0 deletions tokio-postgres/tests/test/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ async fn scram_password_ok() {
connect("user=scram_user password=password dbname=postgres").await;
}

#[tokio::test]
async fn sync() {
let client = connect("user=postgres").await;
client.check_connection().await.unwrap();
}

#[tokio::test]
async fn pipelined_prepare() {
let client = connect("user=postgres").await;
Expand Down
Loading