use testcontainers::core::IntoContainerPort;
use testcontainers::runners::AsyncRunner;
use testcontainers::ImageExt;
use testcontainers_modules::postgres::Postgres;
pub async fn docker_available() -> bool {
tokio::process::Command::new("docker")
.arg("info")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.await
.map(|s| s.success())
.unwrap_or(false)
}
pub struct PgHandle {
pub url: String,
_container: Option<testcontainers::ContainerAsync<Postgres>>,
}
impl PgHandle {
pub async fn start() -> anyhow::Result<Self> {
let image = Postgres::default();
let container = image
.with_tag("16-alpine")
.start()
.await
.map_err(|e| anyhow::anyhow!("failed to start postgres container: {e}"))?;
let port = container
.get_host_port_ipv4(5432.tcp())
.await
.map_err(|e| anyhow::anyhow!("failed to get postgres port: {e}"))?;
let url = format!("postgres://postgres:postgres@127.0.0.1:{port}/postgres");
Ok(Self {
url,
_container: Some(container),
})
}
}
pub struct DbHandle {
pub pg: PgHandle,
}
impl DbHandle {
pub async fn start() -> anyhow::Result<Self> {
let pg = PgHandle::start().await?;
Ok(Self { pg })
}
}
pub fn database_settings(url: &str) -> crate::config::DatabaseSettings {
crate::config::DatabaseSettings {
url: url.to_string(),
max_connections: Some(5),
min_connections: Some(1),
connect_timeout: Some(30),
idle_timeout: Some(300),
max_lifetime: Some(1800),
connection_keepalive: Some(30),
health_check_interval: Some(60),
prepare_cache_capacity: None,
auto_migrate: false,
}
}
pub fn settings_with_urls(db_url: &str) -> anyhow::Result<crate::config::Settings> {
let mut settings = crate::bootstrap::config::load_settings()?;
settings.database = database_settings(db_url);
#[cfg(feature = "auth")]
{
const TEST_JWT_SECRET_ENV: &str = "CRAWLRS_TEST_JWT_SECRET";
const FALLBACK_TEST_SECRET: &str = "test-jwt-secret-32-bytes-or-more!!";
settings.auth.jwt_secret =
std::env::var(TEST_JWT_SECRET_ENV).unwrap_or_else(|_| FALLBACK_TEST_SECRET.to_string());
}
Ok(settings)
}