use claviron_runtime::AppState;
use sqlx::PgPool;
use sqlx::postgres::{PgListener, PgNotification};
use tokio::sync::broadcast;
use tracing::warn;
use crate::provider::PostgresConnected;
pub enum Notice {
Changed(Vec<PgNotification>),
Resync,
}
pub struct ChannelListener {
listener: PgListener,
connected: broadcast::Receiver<PostgresConnected>,
resync: bool,
wait: bool,
resyncing: bool,
}
impl ChannelListener {
pub async fn open(
state: &AppState,
pool: &PgPool,
channels: &[&str],
) -> Self {
let mut connected =
state.events().bus().subscribe::<PostgresConnected>();
loop {
match subscribe(pool, channels).await {
Ok(listener) => {
return Self {
listener,
connected,
resync: false,
wait: false,
resyncing: false,
};
}
Err(error) => {
warn!(
"LISTEN {channels:?}: {error}; waiting for the database"
);
wait_for_connection(&mut connected).await;
}
}
}
}
pub async fn next(&mut self) -> Notice {
loop {
if self.resync {
if self.wait {
wait_for_connection(&mut self.connected).await;
self.wait = false;
}
self.resync = false;
self.resyncing = true;
return Notice::Resync;
}
match self.listener.try_recv().await {
Ok(Some(first)) => {
let mut notes = vec![first];
while let Some(more) = self.listener.next_buffered() {
notes.push(more);
}
self.resyncing = false;
return Notice::Changed(notes);
}
Ok(None) => {
warn!("LISTEN connection lost; resyncing");
self.resync = true;
}
Err(error) => {
warn!("LISTEN: {error}; waiting for the database");
self.resync = true;
self.wait = true;
}
}
}
}
pub fn missed(&mut self) {
self.resync = true;
self.wait = self.resyncing;
}
}
async fn subscribe(
pool: &PgPool,
channels: &[&str],
) -> sqlx::Result<PgListener> {
let mut listener = PgListener::connect_with(pool).await?;
listener.listen_all(channels.iter().copied()).await?;
Ok(listener)
}
async fn wait_for_connection(
connected: &mut broadcast::Receiver<PostgresConnected>
) {
match connected.recv().await {
Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
Err(broadcast::error::RecvError::Closed) => {
std::future::pending().await
}
}
}