Skip to main content

PgListener

Struct PgListener 

Source
pub struct PgListener { /* private fields */ }
Expand description

A dedicated connection receiving PostgreSQL NOTIFY messages.

The connection is not taken from a pool. Dropping the listener closes it and stops its background tasks.

§Connect directly to PostgreSQL

A LISTEN subscription belongs to one server session, so the listener must connect to PostgreSQL itself, not through a transaction-mode pooler (such as PgBouncer with pool_mode = transaction) or a multiplexing proxy such as Amazon RDS Proxy, which do not keep the client connection tied to one server session: notifications would be lost or never arrive. When the application’s pool goes through such a proxy, build the listener from a PgConfig that points at the database server directly rather than with from_pool, which copies the pool’s host.

§Security

PostgreSQL has no privileges on channels: any role that can connect to the database can NOTIFY on any channel, including the ones this listener subscribes to. A notification proves nothing about who sent it or whether its payload is true. Use it as a cue to re-read the authoritative data, or verify an authenticated payload (such as an HMAC over it with a key only legitimate senders hold) before acting on it.

Implementations§

Source§

impl PgListener

Source

pub async fn connect(config: &PgConfig) -> PgResult<Self>

Connect with default PgListenerOptions.

Source

pub async fn from_pool(pool: &PgPool) -> PgResult<Self>

Connect a dedicated listener using pool’s configuration (including its TLS settings and host). The connection is not taken from the pool.

If the pool connects through a transaction-mode pooler or a proxy such as Amazon RDS Proxy, use connect with a config that points at PostgreSQL directly instead; see Connect directly to PostgreSQL.

Source

pub fn builder(config: &PgConfig) -> PgListenerBuilder

Start building a listener with custom PgListenerOptions.

Source

pub async fn listen(&mut self, channel: &str) -> PgResult<()>

Subscribe to channel.

The name is used verbatim (quoted as an identifier, case preserved), so it matches pg_notify(channel, ..) / PgConnection::notify with the same string. It must be non-empty, at most 63 bytes and free of NUL. Subscribing to a channel twice is a no-op.

If the server does not answer within ping_interval, this fails with a timeout error and the listener treats the connection as lost.

After a connection loss, while the listener is backing off before its next reconnect attempt, this (like unlisten and unlisten_all) returns without waiting for the server: the channel is recorded and subscribed when the connection is re-established. (During the attempt itself it waits for the attempt to finish.) If the server then rejects the channel name (for example one its encoding cannot represent), the channel is dropped and reported as PgListenerEvent::ChannelsDropped.

Source

pub async fn listen_all<I, S>(&mut self, channels: I) -> PgResult<()>
where I: IntoIterator<Item = S>, S: AsRef<str>,

Subscribe to every channel in channels.

All names are validated before any is subscribed; on a server error the channels before the failing one stay subscribed.

Source

pub async fn unlisten(&mut self, channel: &str) -> PgResult<()>

Unsubscribe from channel. Unsubscribing from a channel that is not subscribed is a no-op.

Source

pub async fn unlisten_all(&mut self) -> PgResult<()>

Unsubscribe from every channel (UNLISTEN *).

Source

pub async fn recv(&mut self) -> PgResult<PgListenerEvent>

Wait for the next event.

Events keep their order relative to the notifications: a PgListenerEvent::Disconnected, PgListenerEvent::Reconnected or PgListenerEvent::Lagged is returned after the notifications that were already queued when this first saw it, and before any queued later. On an empty queue it is returned at once, also while this is waiting. Each Disconnected comes before the Reconnected that ends its outage, and a PgListenerEvent::ChannelsDropped right before the Reconnected of the reconnect that dropped the channels; when they are due together with a Lagged, they come first. Several outages that happen before this sees the first reconnect are reported as a single Disconnected and Reconnected (with every channel dropped meanwhile), so the two always alternate.

Once the listener has stopped (the connection was lost with PgListenerOptions::reconnect disabled, or reconnecting gave up) and every queued event has been read, this returns the error that ended it, and a generic “listener closed” error on later calls.

Cancel safe: if the future is dropped before completing, no event is lost.

Source

pub fn into_stream(self) -> impl Stream<Item = PgResult<PgListenerEvent>> + Send

Turn the listener into a stream of PgListener::recv results.

The stream ends after yielding the error that closed the listener.

Trait Implementations§

Source§

impl Debug for PgListener

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more