#![allow(clippy::unwrap_used, clippy::panic)]
mod pool_test;
use std::sync::Arc;
use arc_swap::ArcSwap;
use halephant_core::config::Config;
use halephant_core::pool::PoolManager;
use halephant_core::pool::types::{CheckoutError, classify_checkout_error};
use halephant_core::topology::{ClusterTopology, TopologyManager};
use halephant_core::clients::{ClientGuard, ClientRegistry};
pub(crate) fn test_client_guard() -> ClientGuard {
let registry = Arc::new(ClientRegistry::new());
registry.register("127.0.0.1:0".parse().unwrap())
}
fn make_pool_with_seeded_primary(toml: &str) -> Arc<PoolManager> {
let config = Arc::new(ArcSwap::from_pointee(Config::parse(toml).unwrap()));
let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
let topology = Arc::new(TopologyManager::new(
Arc::clone(&config),
Arc::clone(&pgpass),
));
for (name, cluster) in &config.load().cluster {
topology.set(
name,
ClusterTopology {
primary: cluster.nodes.first().cloned(),
replicas: Vec::new(),
unreachable: Vec::new(),
},
);
}
Arc::new(PoolManager::new(config, topology, pgpass))
}
fn make_pool(toml: &str) -> Arc<PoolManager> {
let config = Arc::new(ArcSwap::from_pointee(Config::parse(toml).unwrap()));
let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
let topology = Arc::new(TopologyManager::new(
Arc::clone(&config),
Arc::clone(&pgpass),
));
Arc::new(PoolManager::new(config, topology, pgpass))
}
fn pool_with_max(max_connections: u32) -> Arc<PoolManager> {
make_pool_with_seeded_primary(&format!(
r#"
[cluster.test]
nodes = ["127.0.0.1:59999"]
[cluster.test.pool.testdb]
max_connections = {{ primary = {max_connections} }}
[cluster.test.pool.testdb.user.user]
[cluster.test.pool.testdb.user.alice]
[cluster.test.pool.testdb.user.bob]
"#
))
}
async fn checkout_err(pool: &Arc<PoolManager>, db: &str, user: &str) -> String {
let client = test_client_guard();
match pool.checkout(&client, db, user, false).await {
Err(e) => e.to_string(),
Ok(_) => panic!("expected checkout to fail for {db}/{user}"),
}
}
#[tokio::test]
async fn checkout_unreachable_upstream() {
let pool = pool_with_max(10);
let client = test_client_guard();
let err = pool
.checkout(&client, "testdb", "user", false)
.await
.err()
.expect("expected checkout to fail for testdb/user");
let msg = err.to_string();
assert!(
msg.contains("connect") || msg.contains("refused"),
"error should mention connection failure: {msg}"
);
assert!(err.downcast_ref::<CheckoutError>().is_none());
assert_eq!(classify_checkout_error(&err), "connect_failed");
}
#[tokio::test]
async fn checkout_unknown_database_rejected() {
let pool = pool_with_max(10);
let msg = checkout_err(&pool, "unknown_db", "user").await;
assert!(
msg.contains("not configured"),
"unknown database should fail: {msg}"
);
}
#[tokio::test]
async fn checkout_no_clusters_configured() {
let pool = make_pool("");
let msg = checkout_err(&pool, "db", "user").await;
assert!(
msg.contains("not configured"),
"should report database not configured: {msg}"
);
}
#[tokio::test]
async fn checkout_no_primary_discovered() {
let pool = make_pool(
r#"
[cluster.test]
nodes = ["127.0.0.1:59999"]
[cluster.test.pool.testdb.user.user]
"#,
);
let msg = checkout_err(&pool, "testdb", "user").await;
assert!(
msg.contains("no primary discovered"),
"missing topology should fail with NoPrimary: {msg}"
);
}
#[tokio::test]
async fn checkout_unconfigured_user_refused() {
let pool = pool_with_max(10);
let client = test_client_guard();
let err = pool
.checkout(&client, "testdb", "mallory", false)
.await
.err()
.expect("expected checkout to refuse the unconfigured user");
assert!(
matches!(
err.downcast_ref::<CheckoutError>(),
Some(CheckoutError::UserNotConfigured { .. })
),
"refusal should downcast to CheckoutError::UserNotConfigured, got: {err}"
);
assert!(
err.to_string().contains("not configured"),
"refusal should say the user is not configured: {err}"
);
assert_eq!(classify_checkout_error(&err), "user_not_configured");
}
#[tokio::test]
async fn failed_connect_does_not_exhaust_pool() {
let pool = pool_with_max(1);
let msg1 = checkout_err(&pool, "testdb", "user").await;
assert!(!msg1.contains("exhausted"), "first attempt: {msg1}");
let msg2 = checkout_err(&pool, "testdb", "user").await;
assert!(!msg2.contains("exhausted"), "second attempt: {msg2}");
let msg3 = checkout_err(&pool, "testdb", "user").await;
assert!(!msg3.contains("exhausted"), "third attempt: {msg3}");
}
#[tokio::test]
async fn resolves_correct_cluster() {
let pool = make_pool_with_seeded_primary(
r#"
[cluster.cluster_a]
nodes = ["127.0.0.1:59998"]
[cluster.cluster_a.pool.db_a.user.user]
[cluster.cluster_b]
nodes = ["127.0.0.1:59997"]
[cluster.cluster_b.pool.db_b.user.user]
"#,
);
let err_a = checkout_err(&pool, "db_a", "user").await;
assert!(
err_a.contains("59998"),
"db_a should route to 59998: {err_a}"
);
let err_b = checkout_err(&pool, "db_b", "user").await;
assert!(
err_b.contains("59997"),
"db_b should route to 59997: {err_b}"
);
}
#[tokio::test]
async fn separate_pools_per_user() {
let pool = pool_with_max(10);
let _ = checkout_err(&pool, "testdb", "alice").await;
let _ = checkout_err(&pool, "testdb", "bob").await;
}
#[tokio::test]
async fn pool_observes_config_swap() {
let pool = make_pool_with_seeded_primary(
r#"
[cluster.test]
nodes = ["127.0.0.1:59999"]
[cluster.test.pool.mydb]
max_connections = { primary = 10 }
[cluster.test.pool.mydb.user.myuser]
"#,
);
let initial = pool
.pool_limits()
.into_iter()
.find(|l| l.database == "mydb")
.expect("mydb pool exists");
assert_eq!(initial.max_primary, 10);
let new_cfg = Config::parse(
r#"
[cluster.test]
nodes = ["127.0.0.1:59999"]
[cluster.test.pool.mydb]
max_connections = { primary = 42 }
[cluster.test.pool.mydb.user.myuser]
"#,
)
.unwrap();
pool.config().store(Arc::new(new_cfg));
let after = pool
.pool_limits()
.into_iter()
.find(|l| l.database == "mydb")
.expect("mydb pool still exists after reload");
assert_eq!(after.max_primary, 42);
}
#[tokio::test]
async fn pool_observes_added_database_after_swap() {
let pool = make_pool_with_seeded_primary(
r#"
[cluster.test]
nodes = ["127.0.0.1:59999"]
[cluster.test.pool.existing.user.alice]
"#,
);
let err = checkout_err(&pool, "newdb", "bob").await;
assert!(
err.contains("not configured"),
"newdb should be unknown pre-reload: {err}"
);
let new_cfg = Config::parse(
r#"
[cluster.test]
nodes = ["127.0.0.1:59999"]
[cluster.test.pool.existing.user.alice]
[cluster.test.pool.newdb.user.bob]
"#,
)
.unwrap();
pool.config().store(Arc::new(new_cfg));
let err = checkout_err(&pool, "newdb", "bob").await;
assert!(
!err.contains("not configured"),
"newdb should be recognized after reload: {err}"
);
}