use std::{future::poll_fn, str::FromStr};
use fraiseql_error::{FraiseQLError, Result};
use tokio::{
io::{AsyncRead, AsyncWrite},
sync::mpsc,
};
use tokio_postgres::{AsyncMessage, Client, Connection, NoTls};
use super::{PostgresConnector, PostgresSslMode, PostgresTlsConfig, pg_detail};
pub const NOTIFY_APPLICATION_NAME: &str = "fraiseql-notify";
const MAX_APPLICATION_NAME_BYTES: usize = 63;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Notification {
pub channel: String,
pub payload: String,
pub process_id: i32,
}
#[derive(Debug, Clone)]
pub struct NotifyConnector {
config: tokio_postgres::Config,
tls: PostgresTlsConfig,
}
impl NotifyConnector {
pub fn new(connection_string: &str, tls: PostgresTlsConfig) -> Result<Self> {
tls.validate()?;
let mut config = tokio_postgres::Config::from_str(connection_string).map_err(|e| {
FraiseQLError::Configuration {
message: format!("invalid database URL for the notification connection: {e}"),
}
})?;
if let Some(mode) = tls.mode {
config.ssl_mode(match mode {
PostgresSslMode::Disable => tokio_postgres::config::SslMode::Disable,
PostgresSslMode::Prefer => tokio_postgres::config::SslMode::Prefer,
PostgresSslMode::Require | PostgresSslMode::VerifyFull => {
tokio_postgres::config::SslMode::Require
},
});
}
if config.get_application_name().is_none() {
config.application_name(NOTIFY_APPLICATION_NAME);
}
Ok(Self { config, tls })
}
#[must_use]
pub fn serving(mut self, purpose: &str) -> Self {
let base = self.config.get_application_name().unwrap_or(NOTIFY_APPLICATION_NAME);
let mut name = format!("{base}/{purpose}");
while name.len() > MAX_APPLICATION_NAME_BYTES {
name.pop();
}
self.config.application_name(&name);
self
}
pub async fn connect(&self) -> Result<NotifySession> {
let (sender, notifications) = mpsc::unbounded_channel();
let client = match self.tls.connector()? {
PostgresConnector::Plaintext => {
let (client, connection) =
self.config.connect(NoTls).await.map_err(|e| connect_error(&e))?;
tokio::spawn(forward_notifications(connection, sender));
client
},
PostgresConnector::Tls(connector) => {
let (client, connection) =
self.config.connect(*connector).await.map_err(|e| connect_error(&e))?;
tokio::spawn(forward_notifications(connection, sender));
client
},
};
Ok(NotifySession {
client,
notifications,
})
}
}
fn connect_error(e: &tokio_postgres::Error) -> FraiseQLError {
FraiseQLError::ConnectionPool {
message: format!("failed to open the notification connection: {}", pg_detail(e)),
}
}
async fn forward_notifications<S, T>(
mut connection: Connection<S, T>,
sender: mpsc::UnboundedSender<Notification>,
) where
S: AsyncRead + AsyncWrite + Unpin,
T: AsyncRead + AsyncWrite + Unpin,
{
while let Some(message) = poll_fn(|cx| connection.poll_message(cx)).await {
match message {
Ok(AsyncMessage::Notification(n)) => {
let notification = Notification {
channel: n.channel().to_string(),
payload: n.payload().to_string(),
process_id: n.process_id(),
};
if sender.send(notification).is_err() {
return;
}
},
Ok(_) => {},
Err(e) => {
tracing::warn!(error = %pg_detail(&e), "notification connection lost");
return;
},
}
}
}
pub struct NotifySession {
client: Client,
notifications: mpsc::UnboundedReceiver<Notification>,
}
impl NotifySession {
pub async fn listen(&self, channel: &str) -> Result<()> {
let statement = format!("LISTEN {}", quote_identifier(channel));
self.client
.batch_execute(&statement)
.await
.map_err(|e| super::database_error(format!("LISTEN failed: {}", pg_detail(&e)), &e))
}
pub async fn notify(&self, channel: &str, payload: &str) -> Result<()> {
self.client
.execute("SELECT pg_notify($1, $2)", &[&channel, &payload])
.await
.map(drop)
.map_err(|e| super::database_error(format!("NOTIFY failed: {}", pg_detail(&e)), &e))
}
pub async fn query_bigint(&self, statement: &str) -> Result<i64> {
self.client.query_one(statement, &[]).await.map(|row| row.get(0)).map_err(|e| {
super::database_error(format!("{statement} failed: {}", pg_detail(&e)), &e)
})
}
pub async fn recv(&mut self) -> Option<Notification> {
self.notifications.recv().await
}
}
fn quote_identifier(name: &str) -> String {
format!("\"{}\"", name.replace('"', "\"\""))
}
#[cfg(test)]
#[path = "notify_tests.rs"]
mod tests;