Eagerly reconnect in PgListener::try_recv (#3585)

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.
This commit is contained in:
Sean Lynch 2024-11-27 16:52:23 -05:00 committed by GitHub
parent 5c6623dee2
commit 503a72c94f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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.
@ -69,6 +70,7 @@ impl PgListener {
buffer_tx: None,
channels: Vec::new(),
ignore_close_event: false,
eager_reconnect: true,
})
}
@ -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> {
@ -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
///
@ -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
@ -270,6 +288,10 @@ impl PgListener {
conn.close_on_drop();
}
if self.eager_reconnect {
self.connect_if_needed().await?;
}
// lost connection
return Ok(None);
}