use std::env::VarError;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use sqlx::postgres::PgPoolOptions;
use sqlx::{Executor, PgPool};
use testcontainers::core::{IntoContainerPort, WaitFor};
use testcontainers::runners::AsyncRunner;
use testcontainers::{ContainerAsync, GenericImage, ImageExt, ReuseDirective};
use tokio::sync::OnceCell;
use crate::migration;
const URL_VARIABLE: &str = "HAPPENSTANCE_POSTGRES_URL";
const POSTGRES_IMAGE: &str = "postgres";
const POSTGRES_TAG: &str = "17.10";
const CONTAINER_NAME: &str = "happenstance-postgres-conformance";
const POSTGRES_PORT: u16 = 5432;
const POSTGRES_USER: &str = "postgres";
const POSTGRES_PASSWORD: &str = "postgres";
const POSTGRES_DB: &str = "postgres";
static SERVER: OnceCell<Server> = OnceCell::const_new();
struct Server {
_container: Option<ContainerAsync<GenericImage>>,
url: String,
}
pub(super) async fn server_url() -> &'static str {
&SERVER.get_or_init(find_or_start).await.url
}
async fn find_or_start() -> Server {
match std::env::var(URL_VARIABLE) {
Ok(url) => Server {
_container: None,
url,
},
Err(VarError::NotPresent) => start_container().await,
Err(VarError::NotUnicode(raw)) => {
panic!("a broken test environment: {URL_VARIABLE} is not Unicode ({raw:?})")
}
}
}
async fn start_container() -> Server {
let container = GenericImage::new(POSTGRES_IMAGE, POSTGRES_TAG)
.with_exposed_port(POSTGRES_PORT.tcp())
.with_wait_for(WaitFor::message_on_stderr(
"database system is ready to accept connections",
))
.with_env_var("POSTGRES_PASSWORD", POSTGRES_PASSWORD)
.with_env_var("POSTGRES_USER", POSTGRES_USER)
.with_env_var("POSTGRES_DB", POSTGRES_DB)
.with_container_name(CONTAINER_NAME)
.with_reuse(ReuseDirective::Always)
.with_cmd(["postgres", "-c", "max_connections=200"])
.start()
.await
.unwrap_or_else(|error| {
panic!(
"a broken test environment, not a non-conformant adapter: could not start \
`{POSTGRES_IMAGE}:{POSTGRES_TAG}` ({error}). Is the Docker daemon running? \
Or set {URL_VARIABLE} to a server's URL."
)
});
let host = container
.get_host()
.await
.expect("a broken test environment: the container has no reachable host");
let port = container
.get_host_port_ipv4(POSTGRES_PORT.tcp())
.await
.expect("a broken test environment: the container mapped no host port");
Server {
_container: Some(container),
url: format!("postgres://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{host}:{port}/{POSTGRES_DB}"),
}
}
pub(super) async fn fresh_pool() -> PgPool {
let pool = empty_pool().await;
migration::apply(&pool).await.unwrap_or_else(|error| {
panic!("a broken test environment: the event log's migrations failed ({error})")
});
pool
}
pub(super) async fn empty_pool() -> PgPool {
static NEXT: AtomicU64 = AtomicU64::new(1);
let schema = format!(
"hsi_{}_{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
);
let url = server_url().await;
let search_path = schema.clone();
let pool = PgPoolOptions::new()
.max_connections(6)
.min_connections(0)
.idle_timeout(Duration::from_secs(5))
.acquire_timeout(Duration::from_secs(5))
.after_connect(move |connection, _meta| {
let schema = search_path.clone();
Box::pin(async move {
connection
.execute(format!(r#"SET search_path TO "{schema}""#).as_str())
.await?;
Ok(())
})
})
.connect(url)
.await
.unwrap_or_else(|error| {
panic!("a broken test environment: could not open a pool at {url} ({error})")
});
pool.execute(format!(r#"CREATE SCHEMA IF NOT EXISTS "{schema}""#).as_str())
.await
.unwrap_or_else(|error| {
panic!("a broken test environment: could not create schema `{schema}` ({error})")
});
pool
}