fireweed-dsl-postgres 0.36.0

PostgreSQL executor for Fireweed's data-plane DSL (API-008): DDL from schemas and plain SQL for each statement.
Documentation
//! [`PgExecutor`]: the PostgreSQL executor behind [`fireweed_dsl::Executor`],
//! over a small pool of connections.

use std::future::Future;
use std::sync::Mutex;

use fireweed_dsl::{Applied, BoxFuture, Error, Executor, Program, Response, Result, Schema, Swept};
use tokio_postgres::{Client, NoTls};

type Connect = Box<
    dyn Fn() -> BoxFuture<'static, std::result::Result<Client, tokio_postgres::Error>>
        + Send
        + Sync,
>;

/// The PostgreSQL executor as a [`fireweed_dsl::Executor`]. Each call takes
/// an idle connection, or opens one, and gives it back when the call
/// finishes. A call that is dropped part way drops its connection instead,
/// so no connection with an open transaction is reused. Connections are
/// opened on demand; at most `max_idle` are kept between calls.
pub struct PgExecutor {
    connect: Connect,
    idle: Mutex<Vec<Client>>,
    max_idle: usize,
}

impl PgExecutor {
    /// Connects without TLS using `config`, spawning each connection's task
    /// on the current Tokio runtime.
    pub fn new(config: tokio_postgres::Config) -> Self {
        Self::with_connector(move || {
            let config = config.clone();
            async move {
                let (client, conn) = config.connect(NoTls).await?;
                tokio::spawn(conn);
                Ok(client)
            }
        })
    }

    /// Opens connections with `connect`, for TLS or other settings. It must
    /// also drive (spawn) each connection's task.
    pub fn with_connector<F, Fut>(connect: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = std::result::Result<Client, tokio_postgres::Error>> + Send + 'static,
    {
        Self {
            connect: Box::new(move || Box::pin(connect())),
            idle: Mutex::new(Vec::new()),
            max_idle: 16,
        }
    }

    /// How many idle connections to keep between calls (default 16).
    pub fn max_idle(mut self, n: usize) -> Self {
        self.max_idle = n;
        self
    }

    async fn take(&self) -> Result<Client> {
        loop {
            let c = self.idle.lock().unwrap_or_else(|p| p.into_inner()).pop();
            match c {
                Some(c) if c.is_closed() => continue,
                Some(c) => return Ok(c),
                None => break,
            }
        }
        (self.connect)()
            .await
            .map_err(|e| Error::Unavailable(format!("connect: {e}")))
    }

    fn give(&self, c: Client) {
        if c.is_closed() {
            return;
        }
        let mut idle = self.idle.lock().unwrap_or_else(|p| p.into_inner());
        if idle.len() < self.max_idle {
            idle.push(c);
        }
    }
}

impl Executor for PgExecutor {
    fn apply_schema<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        schema: &'a Schema,
        expected: Option<i64>,
    ) -> BoxFuture<'a, Result<Applied>> {
        Box::pin(async move {
            let mut c = self.take().await?;
            let r = crate::apply_schema(&mut c, tenant, space, schema, expected).await;
            self.give(c);
            r
        })
    }

    fn get_schema<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
    ) -> BoxFuture<'a, Result<Option<Schema>>> {
        Box::pin(async move {
            let c = self.take().await?;
            let r = crate::get_schema(&c, tenant, space).await;
            self.give(c);
            r
        })
    }

    fn execute<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        program: &'a Program,
    ) -> BoxFuture<'a, Result<Response>> {
        Box::pin(async move {
            let mut c = self.take().await?;
            let r = crate::execute(&mut c, tenant, space, program).await;
            self.give(c);
            r
        })
    }

    fn execute_batch<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        programs: &'a [Program],
    ) -> BoxFuture<'a, Result<Vec<Result<Response>>>> {
        Box::pin(async move {
            let mut c = self.take().await?;
            let r = crate::execute_batch(&mut c, tenant, space, programs).await;
            self.give(c);
            r
        })
    }

    fn sweep<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        batch: u32,
    ) -> BoxFuture<'a, Result<Swept>> {
        Box::pin(async move {
            let mut c = self.take().await?;
            let r = crate::sweep(&mut c, tenant, space, batch).await;
            self.give(c);
            r
        })
    }
}