use std::sync::{Arc, LazyLock, Mutex, OnceLock};
use std::time::Duration;
use futures::FutureExt as _;
use futures::future::{BoxFuture, Shared};
use sqlx::postgres::PgPoolOptions;
pub type Pool = sqlx::PgPool;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(
"no database: OBJECTIVEAI_POSTGRES_URL is unset, which means this process is not running as a plugin container"
)]
NoDatabase,
#[error("connect to the plugin database")]
Connect(#[source] sqlx::Error),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub max_connections: u32,
pub min_connections: u32,
pub acquire_timeout: Duration,
}
impl Default for Config {
fn default() -> Self {
Self {
max_connections: 1024,
min_connections: 0,
acquire_timeout: Duration::from_secs(30),
}
}
}
static POOL: OnceLock<Pool> = OnceLock::new();
static ATTEMPT: LazyLock<Mutex<Attempt>> = LazyLock::new(|| {
Mutex::new(Attempt {
current: None,
generation: 0,
})
});
struct Attempt {
current: Option<(u64, Shared<BoxFuture<'static, Result<Pool, Arc<Error>>>>)>,
generation: u64,
}
pub async fn connect(config: Config) -> Result<Pool, Arc<Error>> {
coalesce(|| connect_once(config).boxed()).await
}
async fn coalesce(
start: impl FnOnce() -> BoxFuture<'static, Result<Pool, Arc<Error>>>,
) -> Result<Pool, Arc<Error>> {
if let Some(pool) = POOL.get() {
return Ok(pool.clone());
}
let (generation, attempt) = {
let mut state = ATTEMPT.lock().unwrap_or_else(|e| e.into_inner());
let finished = state.current.as_ref().and_then(|(_, a)| a.peek().cloned());
match finished {
Some(Ok(pool)) => {
state.current = None;
drop(state);
let _ = POOL.set(pool.clone());
return Ok(pool);
}
Some(Err(_)) => state.current = None,
None => {}
}
match &state.current {
Some((generation, attempt)) => (*generation, attempt.clone()),
None => {
state.generation += 1;
let generation = state.generation;
let attempt = start().shared();
state.current = Some((generation, attempt.clone()));
(generation, attempt)
}
}
};
match attempt.await {
Ok(pool) => {
let _ = POOL.set(pool.clone());
let mut state = ATTEMPT.lock().unwrap_or_else(|e| e.into_inner());
if state.current.as_ref().is_some_and(|(g, _)| *g == generation) {
state.current = None;
}
Ok(pool)
}
Err(error) => {
let mut state = ATTEMPT.lock().unwrap_or_else(|e| e.into_inner());
if state.current.as_ref().is_some_and(|(g, _)| *g == generation) {
state.current = None;
}
Err(error)
}
}
}
async fn connect_once(config: Config) -> Result<Pool, Arc<Error>> {
let url = crate::environment::postgres_url()
.ok_or_else(|| Arc::new(Error::NoDatabase))?;
PgPoolOptions::new()
.max_connections(config.max_connections)
.min_connections(config.min_connections)
.acquire_timeout(config.acquire_timeout)
.connect(url)
.await
.map_err(|e| Arc::new(Error::Connect(e)))
}
#[cfg(test)]
mod tests {
use super::*;
fn outside_a_plugin_container() -> bool {
crate::environment::postgres_url().is_none()
}
static SERIAL: Mutex<()> = Mutex::new(());
fn exclusive() -> std::sync::MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|e| e.into_inner())
}
#[test]
fn default_config_is_generous_but_bounded() {
let config = Config::default();
assert_eq!(config.max_connections, 1024);
assert_eq!(config.min_connections, 0);
assert_eq!(config.acquire_timeout, Duration::from_secs(30));
}
#[tokio::test]
async fn no_url_is_its_own_error() {
let _serial = exclusive();
if !outside_a_plugin_container() {
return;
}
let error = connect(Config::default()).await.expect_err("no database");
assert!(matches!(*error, Error::NoDatabase));
}
#[tokio::test]
async fn a_failed_attempt_leaves_no_trace() {
let _serial = exclusive();
if !outside_a_plugin_container() {
return;
}
let before = ATTEMPT.lock().unwrap().generation;
for _ in 0..3 {
assert!(connect(Config::default()).await.is_err());
}
let state = ATTEMPT.lock().unwrap();
assert!(
state.current.is_none(),
"the slot is empty, so the next caller starts fresh",
);
assert_eq!(
state.generation - before,
3,
"and each sequential call really did start its own attempt",
);
}
#[tokio::test]
async fn overlapping_callers_share_one_attempt() {
let _serial = exclusive();
let before = ATTEMPT.lock().unwrap().generation;
let results = futures::future::join_all((0..8).map(|_| {
coalesce(|| {
async {
tokio::time::sleep(Duration::from_millis(50)).await;
Err(Arc::new(Error::NoDatabase))
}
.boxed()
})
}))
.await;
let after = ATTEMPT.lock().unwrap().generation;
assert_eq!(results.len(), 8);
assert!(results.iter().all(|r| r.is_err()), "all eight see the failure");
assert_eq!(
after - before,
1,
"eight concurrent callers, one attempt between them",
);
}
#[tokio::test]
async fn a_finished_failure_is_retired_not_joined() {
let _serial = exclusive();
let stale: Shared<BoxFuture<'static, Result<Pool, Arc<Error>>>> =
async { Err(Arc::new(Error::NoDatabase)) }.boxed().shared();
assert!(
stale.clone().now_or_never().is_some(),
"resolved, so it is what the slot holds after a failure",
);
let before = {
let mut state = ATTEMPT.lock().unwrap();
state.generation += 1;
state.current = Some((state.generation, stale));
state.generation
};
let outcome = coalesce(|| {
async { Err(Arc::new(Error::Connect(sqlx::Error::PoolClosed))) }.boxed()
})
.await;
let error = outcome.expect_err("still no database");
assert!(
matches!(*error, Error::Connect(_)),
"the FRESH attempt answered, not the retired one",
);
assert_eq!(
ATTEMPT.lock().unwrap().generation - before,
1,
"and it really was a new attempt",
);
assert!(
ATTEMPT.lock().unwrap().current.is_none(),
"which then retired itself in turn",
);
}
#[tokio::test]
async fn a_shared_failure_still_clears_the_slot() {
let _serial = exclusive();
let _ = coalesce(|| {
async {
tokio::time::sleep(Duration::from_millis(10)).await;
Err(Arc::new(Error::NoDatabase))
}
.boxed()
})
.await;
assert!(ATTEMPT.lock().unwrap().current.is_none());
}
}