encore-tokio-postgres 2.0.0

A native, asynchronous PostgreSQL client
Documentation
//! A connection its client's calls drive too.
//!
//! A [`Connection`] is a future a task runs: a request reaches the socket
//! once the client has queued it, woken that task, and a thread has taken the
//! task up. For a caller on a thread of its own, such as one calling in over
//! a C ABI, that wake is a thread switch on every request, with the request
//! written only after it.
//!
//! [`Connection::driven_by`] shares the connection between its task and its
//! client instead: a call that queues a request polls the connection there
//! and then, on its own thread, which writes the request, and wakes the task
//! only if it could not (the task, or another call, was polling it just
//! then). What the connection waits for, its socket above all, still wakes
//! the task: a call polls with the task's waker.

use crate::client::InnerClient;
use crate::{Client, Connection, Error};
use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use tokio::io::{AsyncRead, AsyncWrite};

thread_local! {
    /// Whether this thread is queuing a request it will drive itself, and so
    /// needs no wake of the connection's task for; set to [`SUPPRESSED`] once
    /// it has withheld one.
    static QUEUING: Cell<u8> = const { Cell::new(IDLE) };
}

const IDLE: u8 = 0;
const SUPPRESS: u8 = 1;
const SUPPRESSED: u8 = 2;

/// What wakes the connection's task for a new request, unless the thread
/// that queued it drives the connection itself: the waker the connection
/// polls its requests with.
pub(crate) struct Gate {
    /// The task's waker, as of its last poll.
    task: Mutex<Option<Waker>>,
}

impl Gate {
    fn task(&self) -> MutexGuard<'_, Option<Waker>> {
        self.task.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn wake_task(&self) {
        let waker = self.task().clone();
        if let Some(waker) = waker {
            waker.wake();
        }
    }
}

impl Wake for Gate {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        if QUEUING.get() == IDLE {
            self.wake_task();
        } else {
            QUEUING.set(SUPPRESSED);
        }
    }
}

/// The client's end of a driven connection.
pub(crate) trait Drive: Send + Sync {
    /// Runs `queue`, which queues a request, and then drives the connection
    /// on this thread, so that the request is written before this returns
    /// if the socket takes it. Wakes the connection's task instead only if
    /// it cannot.
    fn queue_and_drive(&self, queue: &mut dyn FnMut() -> Result<(), Error>) -> Result<(), Error>;
}

// One per connection, behind an `Arc`: its size is no matter, and a box would
// be one more pointer to follow at each poll.
#[allow(clippy::large_enum_variant)]
enum State<S, T> {
    Running(Connection<S, T>),
    /// Ended by a call that drove it, with what its task is to return.
    Ended(Option<Result<(), Error>>),
}

struct Shared<S, T> {
    state: Mutex<State<S, T>>,
    gate: Arc<Gate>,
}

impl<S, T> Drive for Shared<S, T>
where
    S: AsyncRead + AsyncWrite + Unpin + Send,
    T: AsyncRead + AsyncWrite + Unpin + Send,
{
    fn queue_and_drive(&self, queue: &mut dyn FnMut() -> Result<(), Error>) -> Result<(), Error> {
        QUEUING.set(SUPPRESS);
        let queued = queue();
        let suppressed = QUEUING.replace(IDLE) == SUPPRESSED;
        queued?;

        let driven = match self.state.try_lock() {
            Ok(mut state) => {
                let task = self.gate.task().clone();
                match (&mut *state, task) {
                    (State::Running(connection), Some(task)) => {
                        let mut cx = Context::from_waker(&task);
                        if let Poll::Ready(result) = Pin::new(connection).poll(&mut cx) {
                            // Dropping the connection fails what it had
                            // queued. Its task returns the result.
                            *state = State::Ended(Some(result));
                            drop(state);
                            task.wake();
                        }
                        true
                    }
                    // Not polled by its task yet, which will find the
                    // request when it is; or ended, the request dropped.
                    _ => false,
                }
            }
            // Polled right now, by its task or another call, which may be
            // past looking for requests.
            Err(_) => false,
        };
        if suppressed && !driven {
            self.gate.wake_task();
        }
        Ok(())
    }
}

/// A [`Connection`] that its client's calls drive as well as the task that
/// runs it: see [`Connection::driven_by`]. Like the connection, a future to
/// spawn, which resolves when the connection closes.
#[must_use = "futures do nothing unless polled"]
pub struct DrivenConnection<S, T> {
    shared: Arc<Shared<S, T>>,
}

impl<S, T> Connection<S, T>
where
    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
    /// Has `client`, this connection's, drive the connection from the calls
    /// that send its requests, on their threads, rather than wake the task
    /// running the connection for each: a request is on its way before the
    /// call that made it first returns. The returned future is spawned in
    /// the connection's place.
    ///
    /// Worth it for calls made from outside the runtime's threads, each of
    /// which would otherwise wait for one to wake.
    pub fn driven_by(mut self, client: &Client) -> DrivenConnection<S, T> {
        let gate = Arc::new(Gate {
            task: Mutex::new(None),
        });
        self.set_request_waker(Waker::from(gate.clone()));
        let shared = Arc::new(Shared {
            state: Mutex::new(State::Running(self)),
            gate,
        });
        InnerClient::set_driver(client.inner(), shared.clone());
        DrivenConnection { shared }
    }
}

impl<S, T> Future for DrivenConnection<S, T>
where
    S: AsyncRead + AsyncWrite + Unpin,
    T: AsyncRead + AsyncWrite + Unpin,
{
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
        // Held by a call only while it polls the connection, which never
        // blocks.
        let mut state = self
            .shared
            .state
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let connection = match &mut *state {
            State::Running(connection) => connection,
            State::Ended(result) => return Poll::Ready(result.take().unwrap_or(Ok(()))),
        };
        {
            let mut task = self.shared.gate.task();
            if !task.as_ref().is_some_and(|w| w.will_wake(cx.waker())) {
                *task = Some(cx.waker().clone());
            }
        }
        let result = std::task::ready!(Pin::new(connection).poll(cx));
        *state = State::Ended(None);
        Poll::Ready(result)
    }
}

impl<S, T> Drop for DrivenConnection<S, T> {
    fn drop(&mut self) {
        // The client keeps the shared state alive: the connection closes
        // with its task, as one not shared does, and lets go of the task.
        let ended = std::mem::replace(
            &mut *self
                .shared
                .state
                .lock()
                .unwrap_or_else(PoisonError::into_inner),
            State::Ended(None),
        );
        *self.shared.gate.task() = None;
        drop(ended);
    }
}