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,
>;
pub struct PgExecutor {
connect: Connect,
idle: Mutex<Vec<Client>>,
max_idle: usize,
}
impl PgExecutor {
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)
}
})
}
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,
}
}
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
})
}
}