Skip to main content

fireweed_dsl_postgres/
executor.rs

1//! [`PgExecutor`]: the PostgreSQL executor behind [`fireweed_dsl::Executor`],
2//! over a small pool of connections.
3
4use std::future::Future;
5use std::sync::Mutex;
6
7use fireweed_dsl::{Applied, BoxFuture, Error, Executor, Program, Response, Result, Schema, Swept};
8use tokio_postgres::{Client, NoTls};
9
10type Connect = Box<
11    dyn Fn() -> BoxFuture<'static, std::result::Result<Client, tokio_postgres::Error>>
12        + Send
13        + Sync,
14>;
15
16/// The PostgreSQL executor as a [`fireweed_dsl::Executor`]. Each call takes
17/// an idle connection, or opens one, and gives it back when the call
18/// finishes. A call that is dropped part way drops its connection instead,
19/// so no connection with an open transaction is reused. Connections are
20/// opened on demand; at most `max_idle` are kept between calls.
21pub struct PgExecutor {
22    connect: Connect,
23    idle: Mutex<Vec<Client>>,
24    max_idle: usize,
25}
26
27impl PgExecutor {
28    /// Connects without TLS using `config`, spawning each connection's task
29    /// on the current Tokio runtime.
30    pub fn new(config: tokio_postgres::Config) -> Self {
31        Self::with_connector(move || {
32            let config = config.clone();
33            async move {
34                let (client, conn) = config.connect(NoTls).await?;
35                tokio::spawn(conn);
36                Ok(client)
37            }
38        })
39    }
40
41    /// Opens connections with `connect`, for TLS or other settings. It must
42    /// also drive (spawn) each connection's task.
43    pub fn with_connector<F, Fut>(connect: F) -> Self
44    where
45        F: Fn() -> Fut + Send + Sync + 'static,
46        Fut: Future<Output = std::result::Result<Client, tokio_postgres::Error>> + Send + 'static,
47    {
48        Self {
49            connect: Box::new(move || Box::pin(connect())),
50            idle: Mutex::new(Vec::new()),
51            max_idle: 16,
52        }
53    }
54
55    /// How many idle connections to keep between calls (default 16).
56    pub fn max_idle(mut self, n: usize) -> Self {
57        self.max_idle = n;
58        self
59    }
60
61    async fn take(&self) -> Result<Client> {
62        loop {
63            let c = self.idle.lock().unwrap_or_else(|p| p.into_inner()).pop();
64            match c {
65                Some(c) if c.is_closed() => continue,
66                Some(c) => return Ok(c),
67                None => break,
68            }
69        }
70        (self.connect)()
71            .await
72            .map_err(|e| Error::Unavailable(format!("connect: {e}")))
73    }
74
75    fn give(&self, c: Client) {
76        if c.is_closed() {
77            return;
78        }
79        let mut idle = self.idle.lock().unwrap_or_else(|p| p.into_inner());
80        if idle.len() < self.max_idle {
81            idle.push(c);
82        }
83    }
84}
85
86impl Executor for PgExecutor {
87    fn apply_schema<'a>(
88        &'a self,
89        tenant: &'a str,
90        space: &'a str,
91        schema: &'a Schema,
92        expected: Option<i64>,
93    ) -> BoxFuture<'a, Result<Applied>> {
94        Box::pin(async move {
95            let mut c = self.take().await?;
96            let r = crate::apply_schema(&mut c, tenant, space, schema, expected).await;
97            self.give(c);
98            r
99        })
100    }
101
102    fn get_schema<'a>(
103        &'a self,
104        tenant: &'a str,
105        space: &'a str,
106    ) -> BoxFuture<'a, Result<Option<Schema>>> {
107        Box::pin(async move {
108            let c = self.take().await?;
109            let r = crate::get_schema(&c, tenant, space).await;
110            self.give(c);
111            r
112        })
113    }
114
115    fn execute<'a>(
116        &'a self,
117        tenant: &'a str,
118        space: &'a str,
119        program: &'a Program,
120    ) -> BoxFuture<'a, Result<Response>> {
121        Box::pin(async move {
122            let mut c = self.take().await?;
123            let r = crate::execute(&mut c, tenant, space, program).await;
124            self.give(c);
125            r
126        })
127    }
128
129    fn execute_batch<'a>(
130        &'a self,
131        tenant: &'a str,
132        space: &'a str,
133        programs: &'a [Program],
134    ) -> BoxFuture<'a, Result<Vec<Result<Response>>>> {
135        Box::pin(async move {
136            let mut c = self.take().await?;
137            let r = crate::execute_batch(&mut c, tenant, space, programs).await;
138            self.give(c);
139            r
140        })
141    }
142
143    fn sweep<'a>(
144        &'a self,
145        tenant: &'a str,
146        space: &'a str,
147        batch: u32,
148    ) -> BoxFuture<'a, Result<Swept>> {
149        Box::pin(async move {
150            let mut c = self.take().await?;
151            let r = crate::sweep(&mut c, tenant, space, batch).await;
152            self.give(c);
153            r
154        })
155    }
156}