Lines
92.86 %
Functions
47.37 %
Branches
100 %
//! A test's tenant database and directory row, removed when the guard drops.
//!
//! Hand-paired provision/drop calls leak both whenever the test panics or
//! returns early in between; a guard cleans up on every exit path. A failed
//! cleanup fails the test, unless the test is already panicking.
use sqlx::{Connection, PgConnection};
use uuid::Uuid;
type Failure = Box<dyn std::error::Error + Send + Sync>;
const DROP_ATTEMPTS: u32 = 5;
const IN_USE: &str = "55006";
const PREFIXES: [&str; 3] = ["nomi_user_", "nomi_fleet_", "nomisync_e2e_"];
/// What a guard removes. A registered email is resolved to its user id when the
/// guard drops, so the guard can exist before the user does.
enum Target {
Database(String),
Tenant(Uuid, String),
Row(Uuid),
Registered(String),
}
pub struct TestTenant {
target: Option<Target>,
impl TestTenant {
/// A database with no directory row.
pub fn database(name: impl Into<String>) -> Self {
Self::of(Target::Database(name.into()))
/// A database together with the directory row `user`.
pub fn tenant(user: Uuid, database: impl Into<String>) -> Self {
Self::of(Target::Tenant(user, database.into()))
/// The database provisioning gives `user`, with its directory row.
pub fn provisioned(user: Uuid) -> Self {
Self::tenant(user, tenant_database(user))
/// A directory row alone, for a user with no tenant database.
pub fn directory_row(user: Uuid) -> Self {
Self::of(Target::Row(user))
/// The tenant that registers under `email`, whether or not it exists yet.
pub fn registered(email: impl Into<String>) -> Self {
Self::of(Target::Registered(email.into()))
pub fn user(&self) -> Option<Uuid> {
match self.target {
Some(Target::Tenant(user, _) | Target::Row(user)) => Some(user),
_ => None,
/// Removes the tenant now and reports why it could not.
pub fn remove(mut self) -> Result<(), String> {
self.take_and_remove()
fn of(target: Target) -> Self {
Self {
target: Some(target),
fn take_and_remove(&mut self) -> Result<(), String> {
let Some(target) = self.target.take() else {
return Ok(());
};
std::thread::Builder::new()
.name("test-tenant-cleanup".to_owned())
.spawn(move || remove(target))
.map_err(|error| format!("cleanup thread not started: {error}"))?
.join()
.map_err(|_| "cleanup thread panicked".to_owned())?
.map_err(|error| format!("cleanup failed: {error}"))
impl Drop for TestTenant {
fn drop(&mut self) {
let Err(error) = self.take_and_remove() else {
return;
if std::thread::panicking() {
eprintln!("test tenant {error}");
} else {
panic!("test tenant {error}");
pub fn tenant_database(user: Uuid) -> String {
format!("nomi_user_{}", user.simple())
/// Only databases a test creates may be dropped: a prefix and a 32-digit id.
fn is_test_database(name: &str) -> bool {
PREFIXES
.iter()
.filter_map(|prefix| name.strip_prefix(prefix))
.any(|id| id.len() == 32 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
fn remove(target: Target) -> Result<(), Failure> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(remove_target(target))
/// The database goes first: a failed drop must leave the row that names it.
async fn remove_target(target: Target) -> Result<(), Failure> {
let mut conn = PgConnection::connect(&std::env::var("DATABASE_URL")?).await?;
let (user, database) = resolve(&mut conn, target).await?;
if let Some(database) = &database
&& !is_test_database(database)
{
return Err(format!("refusing to drop `{database}`, not a test database").into());
if let Some(database) = database {
drop_database(&mut conn, &database).await?;
if let Some(user) = user {
sqlx::query("DELETE FROM users WHERE id = $1")
.bind(user)
.execute(&mut conn)
.await?;
conn.close().await?;
Ok(())
/// Closes our own sessions, then a plain `DROP`, which waits out autovacuum.
/// Only a reconnecting pool (SQLSTATE 55006) is retried, a bounded number of times.
async fn drop_database(conn: &mut PgConnection, database: &str) -> Result<(), sqlx::Error> {
let statement = format!("DROP DATABASE IF EXISTS \"{database}\"");
let mut attempt = 1;
loop {
sqlx::query(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 \
AND backend_type = 'client backend' AND usename = current_user \
AND pid <> pg_backend_pid()",
)
.bind(database)
.execute(&mut *conn)
match sqlx::query(sqlx::AssertSqlSafe(statement.clone()))
.await
Err(sqlx::Error::Database(error))
if error.code().as_deref() == Some(IN_USE) && attempt < DROP_ATTEMPTS =>
attempt += 1;
outcome => return outcome.map(drop),
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
async fn resolve(
conn: &mut PgConnection,
target: Target,
) -> Result<(Option<Uuid>, Option<String>), Failure> {
Ok(match target {
Target::Database(database) => (None, Some(database)),
Target::Tenant(user, database) => (Some(user), Some(database)),
Target::Row(user) => (Some(user), None),
Target::Registered(email) => {
let user: Option<Uuid> = sqlx::query_scalar("SELECT id FROM users WHERE email = $1")
.bind(server::command::user::fold_email(&email))
.fetch_optional(&mut *conn)
(user, user.map(tenant_database))
})