Expand description
LISTEN / NOTIFY on a dedicated connection.
A PgListener owns one non-pooled connection that subscribes to
notification channels. Notifications are buffered in a bounded queue and
read with PgListener::recv (or as a stream via
PgListener::into_stream).
Sending is done from any ordinary connection or transaction with
PgConnection::notify /
PgTransaction::notify, or
through the query engine with PgEngine::notify
(also inside PraxClient::transaction), which run
SELECT pg_notify($1, $2). Inside a transaction the notification is
delivered on commit and discarded on rollback.
use prax_postgres::{PgListener, PgListenerEvent};
let mut listener = PgListener::connect(&config).await?;
listener.listen("events").await?;
loop {
match listener.recv().await? {
PgListenerEvent::Notification(n) => println!("{}: {}", n.channel, n.payload),
PgListenerEvent::Disconnected { error, .. } => {
eprintln!("listener disconnected ({error}), reconnecting");
}
PgListenerEvent::Reconnected | PgListenerEvent::Lagged { .. } => {
// Notifications may have been missed: resynchronise.
}
PgListenerEvent::ChannelsDropped { channels, .. } => {
eprintln!("no longer subscribed to {channels:?}");
}
_ => {}
}
}§Security
Any role that can connect to the database can NOTIFY any channel; there
are no per-channel privileges. Treat a notification’s channel and payload
as untrusted input: use it as a hint to re-read the authoritative row
(with the reader’s own permissions), or authenticate the payload (for
example an HMAC with a key only the senders hold) before acting on it.
§Architecture
- A supervisor task owns the
tokio_postgres::Clientand the set of tracked channels, and executesLISTEN/UNLISTENcommands sent by thePgListenerhandle. - A driver task per connection polls
Connection::poll_message. It never blocks: each notification istry_send-ed into the bounded queue, and when the queue is full the notification is dropped and counted. The driver tells the supervisor when the connection ends. - State that must never be lost to a full queue (the drop count, the
connection losses and reconnects not yet reported with the channels a
reconnect dropped, the terminal error) lives in atomics / mutexes
shared with the handle and is collected at the top of
PgListener::recv, which then returns it after the notifications queued ahead of it. Raising one also wakes arecvthat is parked on an empty queue. - The supervisor watches the connection: when the driver reports its end,
or when a
SELECT 1ping (sent after aping_intervalwithout any notification) or aLISTEN/UNLISTENcommand fails on the connection or goes unanswered for aping_interval, the connection is lost. It then either reportsPgListenerEvent::Disconnected, reconnects with exponential backoff, re-LISTENs every tracked channel and reportsPgListenerEvent::Reconnected, or (withreconnectdisabled) records the error and stops. It also stops once reconnecting gives up (seemax_reconnect_attempts). Every connection attempt, handshake included, is bounded byPgConfig::connect_timeoutplusping_interval; one that runs out counts as a failed attempt. - Each new connection runs
SET idle_session_timeout = 0(bounded byping_interval; skipped before PostgreSQL 14), so a server default cannot close a listener that is idle while it waits.
Dropping the PgListener closes the command channel; the supervisor then
exits (also while waiting to reconnect) and drops the client, which ends
the driver task.
Structs§
- PgListener
- A dedicated connection receiving PostgreSQL
NOTIFYmessages. - PgListener
Builder - Builder for a
PgListenerwith non-defaultPgListenerOptions. - PgListener
Options - Tuning for a
PgListener; seePgListener::builder. - PgNotification
- A notification received from PostgreSQL.
Enums§
- PgListener
Event - An event delivered by
PgListener::recv.