Skip to content

Commit

Permalink
Eagerly reconnect in PgListener::try_recv (#3585)
Browse files Browse the repository at this point in the history
When PgListener's underlying connection is closed, try_recv() will
return Ok(None) and reconnect on the next call. In this case, user code
is supposed to reload its state from the database (or otherwise handle
potentially missing messages). However, if the user code uses another
database connection to do so then there is a period between when the
state is reloaded and PgListener's connection is re-established where
notifications are lost without any indication that this has happened.

This commit changes PgListener to eagerly reconnect by default. At the
suggestion of @abonander on discord, I have also included an option to
switch back to the old behaviour in the case where someone was depending
on it.

Now, if the connection is closed then, by default, user code can do
whatever it needs to do in order to recover and any notifications
emitted in the meantime will be waiting for it when it is done.
  • Loading branch information
swlynch99 authored Nov 27, 2024
1 parent 5c6623d commit 503a72c
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion sqlx-postgres/src/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct PgListener {
buffer_tx: Option<mpsc::UnboundedSender<Notification>>,
channels: Vec<String>,
ignore_close_event: bool,
eager_reconnect: bool,
}

/// An asynchronous notification from Postgres.
Expand Down Expand Up @@ -69,6 +70,7 @@ impl PgListener {
buffer_tx: None,
channels: Vec::new(),
ignore_close_event: false,
eager_reconnect: true,
})
}

Expand All @@ -95,6 +97,19 @@ impl PgListener {
self.ignore_close_event = val;
}

/// Set whether a lost connection in `try_recv()` should be re-established before it returns
/// `Ok(None)`, or on the next call to `try_recv()`.
///
/// By default, this is `true` and the connection is re-established before returning `Ok(None)`.
///
/// If this is set to `false` then notifications will continue to be lost until the next call
/// to `try_recv()`. If your recovery logic uses a different database connection then
/// notifications that occur after it completes may be lost without any way to tell that they
/// have been.
pub fn eager_reconnect(&mut self, val: bool) {
self.eager_reconnect = val;
}

/// Starts listening for notifications on a channel.
/// The channel name is quoted here to ensure case sensitivity.
pub async fn listen(&mut self, channel: &str) -> Result<(), Error> {
Expand Down Expand Up @@ -214,7 +229,8 @@ impl PgListener {
/// Receives the next notification available from any of the subscribed channels.
///
/// If the connection to PostgreSQL is lost, `None` is returned, and the connection is
/// reconnected on the next call to `try_recv()`.
/// reconnected either immediately, or on the next call to `try_recv()`, depending on
/// the value of [`eager_reconnect`].
///
/// # Example
///
Expand All @@ -234,6 +250,8 @@ impl PgListener {
/// # Result::<(), sqlx::Error>::Ok(())
/// # }).unwrap();
/// ```
///
/// [`eager_reconnect`]: PgListener::eager_reconnect
pub async fn try_recv(&mut self) -> Result<Option<PgNotification>, Error> {
// Flush the buffer first, if anything
// This would only fill up if this listener is used as a connection
Expand Down Expand Up @@ -270,6 +288,10 @@ impl PgListener {
conn.close_on_drop();
}

if self.eager_reconnect {
self.connect_if_needed().await?;
}

// lost connection
return Ok(None);
}
Expand Down

0 comments on commit 503a72c

Please sign in to comment.