| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
use sqlx::postgres::PgPoolOptions; |
| 8 |
use sqlx::{Connection, Executor, PgConnection, PgPool}; |
| 9 |
use std::panic::AssertUnwindSafe; |
| 10 |
use std::sync::OnceLock; |
| 11 |
use std::time::Duration; |
| 12 |
use uuid::Uuid; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
const TEMPLATE_DB_BASE: &str = "mnw_test_template"; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
static TEMPLATE_NAME: OnceLock<String> = OnceLock::new(); |
| 25 |
|
| 26 |
fn template_name() -> &'static str { |
| 27 |
TEMPLATE_NAME.get().map_or(TEMPLATE_DB_BASE, String::as_str) |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
fn sanitize_role(role: &str) -> String { |
| 32 |
role.chars() |
| 33 |
.map(|c| { |
| 34 |
if c.is_ascii_alphanumeric() || c == '_' { |
| 35 |
c.to_ascii_lowercase() |
| 36 |
} else { |
| 37 |
'_' |
| 38 |
} |
| 39 |
}) |
| 40 |
.collect() |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
const SHARED_ROLE: &str = "mnw_test"; |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
async fn assume_shared_role(conn: &mut PgConnection) { |
| 54 |
let _ = conn |
| 55 |
.execute(format!("SET ROLE \"{SHARED_ROLE}\"").as_str()) |
| 56 |
.await; |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
static TEMPLATE_INIT: OnceLock<Result<(), String>> = OnceLock::new(); |
| 69 |
|
| 70 |
|
| 71 |
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String { |
| 72 |
payload.downcast_ref::<&str>().map_or_else( |
| 73 |
|| { |
| 74 |
payload |
| 75 |
.downcast_ref::<String>() |
| 76 |
.cloned() |
| 77 |
.unwrap_or_else(|| "template setup panicked".to_string()) |
| 78 |
}, |
| 79 |
|s| (*s).to_string(), |
| 80 |
) |
| 81 |
} |
| 82 |
|
| 83 |
fn admin_url() -> String { |
| 84 |
std::env::var("TEST_DATABASE_URL") |
| 85 |
.unwrap_or_else(|_| "postgres://localhost/postgres".to_string()) |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
const TEMPLATE_LOCK_KEY: i64 = 0x6D6E_775F_7470_6C00; |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
#[allow( |
| 100 |
clippy::large_stack_arrays, |
| 101 |
reason = "sqlx::migrate! embeds the whole directory" |
| 102 |
)] |
| 103 |
fn latest_migration_version() -> i64 { |
| 104 |
sqlx::migrate!("./migrations") |
| 105 |
.iter() |
| 106 |
.map(|m| m.version) |
| 107 |
.max() |
| 108 |
.unwrap_or(0) |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
async fn template_is_current(admin_url: &str, template: &str) -> bool { |
| 116 |
let Ok(mut conn) = PgConnection::connect(admin_url).await else { |
| 117 |
return false; |
| 118 |
}; |
| 119 |
let exists = sqlx::query_as::<_, (i32,)>("SELECT 1 FROM pg_database WHERE datname = $1") |
| 120 |
.bind(template) |
| 121 |
.fetch_optional(&mut conn) |
| 122 |
.await |
| 123 |
.ok() |
| 124 |
.flatten() |
| 125 |
.is_some(); |
| 126 |
if !exists { |
| 127 |
return false; |
| 128 |
} |
| 129 |
let tpl_url = replace_db_name(admin_url, template); |
| 130 |
let Ok(mut tconn) = PgConnection::connect(&tpl_url).await else { |
| 131 |
return false; |
| 132 |
}; |
| 133 |
matches!( |
| 134 |
sqlx::query_as::<_, (Option<i64>,)>("SELECT MAX(version) FROM _sqlx_migrations") |
| 135 |
.fetch_one(&mut tconn) |
| 136 |
.await, |
| 137 |
Ok((Some(v),)) if v == latest_migration_version() |
| 138 |
) |
| 139 |
} |
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
fn ensure_template() -> Result<(), String> { |
| 145 |
TEMPLATE_INIT |
| 146 |
.get_or_init(|| { |
| 147 |
std::panic::catch_unwind(AssertUnwindSafe(template_setup)) |
| 148 |
.map_err(|payload| panic_message(payload.as_ref())) |
| 149 |
}) |
| 150 |
.clone() |
| 151 |
} |
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
fn template_setup() { |
| 156 |
let rt = tokio::runtime::Builder::new_current_thread() |
| 157 |
.enable_all() |
| 158 |
.build() |
| 159 |
.expect("build template setup runtime"); |
| 160 |
|
| 161 |
rt.block_on(async { |
| 162 |
let t0 = std::time::Instant::now(); |
| 163 |
let admin = admin_url(); |
| 164 |
let mut conn = PgConnection::connect(&admin) |
| 165 |
.await |
| 166 |
.expect("connect to admin DB for template setup"); |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
assume_shared_role(&mut conn).await; |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
let (role,): (String,) = sqlx::query_as("SELECT current_user") |
| 178 |
.fetch_one(&mut conn) |
| 179 |
.await |
| 180 |
.expect("query current_user for template namespacing"); |
| 181 |
let template = format!("{TEMPLATE_DB_BASE}_{}", sanitize_role(&role)); |
| 182 |
let _ = TEMPLATE_NAME.set(template.clone()); |
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
sqlx::query("SELECT pg_advisory_lock($1)") |
| 191 |
.bind(TEMPLATE_LOCK_KEY) |
| 192 |
.execute(&mut conn) |
| 193 |
.await |
| 194 |
.expect("acquire template advisory lock"); |
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
if template_is_current(&admin, &template).await { |
| 202 |
eprintln!("[test-harness] Reusing current template DB {template}"); |
| 203 |
} else { |
| 204 |
|
| 205 |
conn.execute(format!("DROP DATABASE IF EXISTS \"{template}\" WITH (FORCE)").as_str()) |
| 206 |
.await |
| 207 |
.unwrap_or_else(|e| { |
| 208 |
panic!( |
| 209 |
"drop stale template {template}: {e} \ |
| 210 |
(if owned by a different role, drop it as the postgres superuser)" |
| 211 |
) |
| 212 |
}); |
| 213 |
|
| 214 |
conn.execute(format!("CREATE DATABASE \"{template}\"").as_str()) |
| 215 |
.await |
| 216 |
.expect("create template database"); |
| 217 |
|
| 218 |
|
| 219 |
let tpl_url = replace_db_name(&admin, &template); |
| 220 |
let tpl_pool = PgPoolOptions::new() |
| 221 |
.max_connections(2) |
| 222 |
.acquire_timeout(Duration::from_secs(10)) |
| 223 |
.connect(&tpl_url) |
| 224 |
.await |
| 225 |
.expect("connect to template database"); |
| 226 |
|
| 227 |
let t_migrate = std::time::Instant::now(); |
| 228 |
#[allow( |
| 229 |
clippy::large_stack_arrays, |
| 230 |
reason = "sqlx::migrate! embeds the whole directory" |
| 231 |
)] |
| 232 |
sqlx::migrate!("./migrations") |
| 233 |
.run(&tpl_pool) |
| 234 |
.await |
| 235 |
.expect("run migrations on template"); |
| 236 |
let migrate_ms = t_migrate.elapsed().as_millis(); |
| 237 |
|
| 238 |
|
| 239 |
let session_store = tower_sessions_sqlx_store::PostgresStore::new(tpl_pool.clone()); |
| 240 |
session_store |
| 241 |
.migrate() |
| 242 |
.await |
| 243 |
.expect("session store migration on template"); |
| 244 |
|
| 245 |
tpl_pool.close().await; |
| 246 |
|
| 247 |
let total_ms = t0.elapsed().as_millis(); |
| 248 |
eprintln!( |
| 249 |
"[test-harness] Template DB created in {total_ms}ms (migrations: {migrate_ms}ms)" |
| 250 |
); |
| 251 |
} |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
let _ = sqlx::query("SELECT pg_advisory_unlock($1)") |
| 256 |
.bind(TEMPLATE_LOCK_KEY) |
| 257 |
.execute(&mut conn) |
| 258 |
.await; |
| 259 |
}); |
| 260 |
} |
| 261 |
|
| 262 |
|
| 263 |
pub(crate) struct TestDb { |
| 264 |
pub pool: PgPool, |
| 265 |
db_name: String, |
| 266 |
admin_url: String, |
| 267 |
#[allow(dead_code)] |
| 268 |
test_url: String, |
| 269 |
|
| 270 |
pub session_migrated: bool, |
| 271 |
} |
| 272 |
|
| 273 |
impl TestDb { |
| 274 |
|
| 275 |
pub(crate) async fn new() -> Self { |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
match tokio::task::spawn_blocking(ensure_template).await { |
| 282 |
Ok(Ok(())) => {} |
| 283 |
Ok(Err(e)) => panic!("test database setup failed: {e}"), |
| 284 |
Err(e) => panic!("test database setup task failed: {e}"), |
| 285 |
} |
| 286 |
|
| 287 |
let t0 = std::time::Instant::now(); |
| 288 |
let admin = admin_url(); |
| 289 |
let db_name = format!("mnw_test_{}", Uuid::new_v4().simple()); |
| 290 |
|
| 291 |
let mut admin_conn = PgConnection::connect(&admin) |
| 292 |
.await |
| 293 |
.expect("Failed to connect to admin database"); |
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
assume_shared_role(&mut admin_conn).await; |
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
let create_sql = format!( |
| 305 |
"CREATE DATABASE \"{db_name}\" TEMPLATE \"{}\"", |
| 306 |
template_name() |
| 307 |
); |
| 308 |
let mut attempt = 0u32; |
| 309 |
loop { |
| 310 |
match admin_conn.execute(create_sql.as_str()).await { |
| 311 |
Ok(_) => break, |
| 312 |
Err(_) if attempt < 8 => { |
| 313 |
attempt += 1; |
| 314 |
tokio::time::sleep(Duration::from_millis(100 * attempt as u64)).await; |
| 315 |
} |
| 316 |
Err(e) => panic!( |
| 317 |
"Failed to create test database from template after {attempt} retries: {e}" |
| 318 |
), |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
let test_url = replace_db_name(&admin, &db_name); |
| 323 |
|
| 324 |
let pool = PgPoolOptions::new() |
| 325 |
.max_connections(5) |
| 326 |
.acquire_timeout(Duration::from_secs(5)) |
| 327 |
.connect(&test_url) |
| 328 |
.await |
| 329 |
.expect("Failed to connect to test database"); |
| 330 |
|
| 331 |
let clone_ms = t0.elapsed().as_millis(); |
| 332 |
if clone_ms > 500 { |
| 333 |
eprintln!("[test-harness] SLOW DB clone: {clone_ms}ms for {db_name}"); |
| 334 |
} |
| 335 |
|
| 336 |
TestDb { |
| 337 |
pool, |
| 338 |
db_name, |
| 339 |
admin_url: admin, |
| 340 |
test_url, |
| 341 |
session_migrated: true, |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
|
| 346 |
#[allow(dead_code)] |
| 347 |
pub(crate) fn url(&self) -> &str { |
| 348 |
&self.test_url |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
impl Drop for TestDb { |
| 353 |
fn drop(&mut self) { |
| 354 |
let admin_url = self.admin_url.clone(); |
| 355 |
let db_name = self.db_name.clone(); |
| 356 |
let pool = self.pool.clone(); |
| 357 |
|
| 358 |
std::thread::spawn(move || { |
| 359 |
let rt = tokio::runtime::Builder::new_current_thread() |
| 360 |
.enable_all() |
| 361 |
.build() |
| 362 |
.expect("Failed to build cleanup runtime"); |
| 363 |
|
| 364 |
rt.block_on(async { |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
if tokio::time::timeout(Duration::from_secs(5), pool.close()) |
| 373 |
.await |
| 374 |
.is_err() |
| 375 |
{ |
| 376 |
eprintln!( |
| 377 |
"[test-harness] pool for {db_name} did not close in 5s; forcing" |
| 378 |
); |
| 379 |
} |
| 380 |
|
| 381 |
let Ok(mut conn) = PgConnection::connect(&admin_url).await else { |
| 382 |
eprintln!("[test-harness] LEAKED {db_name}: admin connect failed"); |
| 383 |
return; |
| 384 |
}; |
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
let _ = conn |
| 396 |
.execute( |
| 397 |
format!( |
| 398 |
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '{db_name}'" |
| 399 |
) |
| 400 |
.as_str(), |
| 401 |
) |
| 402 |
.await; |
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
let drop_sql = format!("DROP DATABASE IF EXISTS \"{db_name}\" WITH (FORCE)"); |
| 410 |
for attempt in 0..4u32 { |
| 411 |
match conn.execute(drop_sql.as_str()).await { |
| 412 |
Ok(_) => return, |
| 413 |
Err(e) if attempt == 3 => { |
| 414 |
|
| 415 |
|
| 416 |
eprintln!("[test-harness] LEAKED {db_name}: drop failed: {e}"); |
| 417 |
} |
| 418 |
Err(_) => { |
| 419 |
tokio::time::sleep(Duration::from_millis(50 * (attempt + 1) as u64)) |
| 420 |
.await; |
| 421 |
} |
| 422 |
} |
| 423 |
} |
| 424 |
}); |
| 425 |
}) |
| 426 |
.join() |
| 427 |
.ok(); |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
|
| 432 |
fn replace_db_name(url: &str, new_db: &str) -> String { |
| 433 |
if let Some(pos) = url.rfind('/') { |
| 434 |
let base = &url[..pos]; |
| 435 |
let query = url[pos + 1..].find('?').map_or("", |q| &url[pos + 1 + q..]); |
| 436 |
if query.is_empty() { |
| 437 |
format!("{base}/{new_db}") |
| 438 |
} else { |
| 439 |
format!("{base}/{new_db}{query}") |
| 440 |
} |
| 441 |
} else { |
| 442 |
panic!("Invalid database URL: no '/' found"); |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
#[cfg(test)] |
| 447 |
pub(crate) mod tests { |
| 448 |
use super::*; |
| 449 |
|
| 450 |
#[test] |
| 451 |
fn replace_db_name_simple() { |
| 452 |
let result = replace_db_name("postgres://localhost/postgres", "test_db"); |
| 453 |
assert_eq!(result, "postgres://localhost/test_db"); |
| 454 |
} |
| 455 |
|
| 456 |
#[test] |
| 457 |
fn replace_db_name_with_auth() { |
| 458 |
let result = replace_db_name("postgres://user:pass@localhost:5432/mydb", "test_db"); |
| 459 |
assert_eq!(result, "postgres://user:pass@localhost:5432/test_db"); |
| 460 |
} |
| 461 |
|
| 462 |
#[test] |
| 463 |
fn replace_db_name_with_query() { |
| 464 |
let result = replace_db_name("postgres://localhost/postgres?sslmode=disable", "test_db"); |
| 465 |
assert_eq!(result, "postgres://localhost/test_db?sslmode=disable"); |
| 466 |
} |
| 467 |
} |
| 468 |
|