Skip to main content

Module listener

Module listener 

Source
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::Client and the set of tracked channels, and executes LISTEN / UNLISTEN commands sent by the PgListener handle.
  • A driver task per connection polls Connection::poll_message. It never blocks: each notification is try_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 a recv that is parked on an empty queue.
  • The supervisor watches the connection: when the driver reports its end, or when a SELECT 1 ping (sent after a ping_interval without any notification) or a LISTEN / UNLISTEN command fails on the connection or goes unanswered for a ping_interval, the connection is lost. It then either reports PgListenerEvent::Disconnected, reconnects with exponential backoff, re-LISTENs every tracked channel and reports PgListenerEvent::Reconnected, or (with reconnect disabled) records the error and stops. It also stops once reconnecting gives up (see max_reconnect_attempts). Every connection attempt, handshake included, is bounded by PgConfig::connect_timeout plus ping_interval; one that runs out counts as a failed attempt.
  • Each new connection runs SET idle_session_timeout = 0 (bounded by ping_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 NOTIFY messages.
PgListenerBuilder
Builder for a PgListener with non-default PgListenerOptions.
PgListenerOptions
Tuning for a PgListener; see PgListener::builder.
PgNotification
A notification received from PostgreSQL.

Enums§

PgListenerEvent
An event delivered by PgListener::recv.