1
//! A test's tenant database and directory row, removed when the guard drops.
2
//!
3
//! Hand-paired provision/drop calls leak both whenever the test panics or
4
//! returns early in between; a guard cleans up on every exit path. A failed
5
//! cleanup fails the test, unless the test is already panicking.
6

            
7
use sqlx::{Connection, PgConnection};
8
use uuid::Uuid;
9

            
10
type Failure = Box<dyn std::error::Error + Send + Sync>;
11

            
12
const DROP_ATTEMPTS: u32 = 5;
13
const IN_USE: &str = "55006";
14
const PREFIXES: [&str; 3] = ["nomi_user_", "nomi_fleet_", "nomisync_e2e_"];
15

            
16
/// What a guard removes. A registered email is resolved to its user id when the
17
/// guard drops, so the guard can exist before the user does.
18
enum Target {
19
    Database(String),
20
    Tenant(Uuid, String),
21
    Row(Uuid),
22
    Registered(String),
23
}
24

            
25
pub struct TestTenant {
26
    target: Option<Target>,
27
}
28

            
29
impl TestTenant {
30
    /// A database with no directory row.
31
66
    pub fn database(name: impl Into<String>) -> Self {
32
66
        Self::of(Target::Database(name.into()))
33
66
    }
34

            
35
    /// A database together with the directory row `user`.
36
4158
    pub fn tenant(user: Uuid, database: impl Into<String>) -> Self {
37
4158
        Self::of(Target::Tenant(user, database.into()))
38
4158
    }
39

            
40
    /// The database provisioning gives `user`, with its directory row.
41
3834
    pub fn provisioned(user: Uuid) -> Self {
42
3834
        Self::tenant(user, tenant_database(user))
43
3834
    }
44

            
45
    /// A directory row alone, for a user with no tenant database.
46
18
    pub fn directory_row(user: Uuid) -> Self {
47
18
        Self::of(Target::Row(user))
48
18
    }
49

            
50
    /// The tenant that registers under `email`, whether or not it exists yet.
51
61
    pub fn registered(email: impl Into<String>) -> Self {
52
61
        Self::of(Target::Registered(email.into()))
53
61
    }
54

            
55
18
    pub fn user(&self) -> Option<Uuid> {
56
18
        match self.target {
57
18
            Some(Target::Tenant(user, _) | Target::Row(user)) => Some(user),
58
            _ => None,
59
        }
60
18
    }
61

            
62
    /// Removes the tenant now and reports why it could not.
63
108
    pub fn remove(mut self) -> Result<(), String> {
64
108
        self.take_and_remove()
65
108
    }
66

            
67
6462
    fn of(target: Target) -> Self {
68
6462
        Self {
69
6462
            target: Some(target),
70
6462
        }
71
6462
    }
72

            
73
6570
    fn take_and_remove(&mut self) -> Result<(), String> {
74
6570
        let Some(target) = self.target.take() else {
75
108
            return Ok(());
76
        };
77
6462
        std::thread::Builder::new()
78
6462
            .name("test-tenant-cleanup".to_owned())
79
6462
            .spawn(move || remove(target))
80
            .map_err(|error| format!("cleanup thread not started: {error}"))?
81
            .join()
82
            .map_err(|_| "cleanup thread panicked".to_owned())?
83
54
            .map_err(|error| format!("cleanup failed: {error}"))
84
6570
    }
85
}
86

            
87
impl Drop for TestTenant {
88
6462
    fn drop(&mut self) {
89
6462
        let Err(error) = self.take_and_remove() else {
90
6462
            return;
91
        };
92
        if std::thread::panicking() {
93
            eprintln!("test tenant {error}");
94
        } else {
95
            panic!("test tenant {error}");
96
        }
97
6462
    }
98
}
99

            
100
4968
pub fn tenant_database(user: Uuid) -> String {
101
4968
    format!("nomi_user_{}", user.simple())
102
4968
}
103

            
104
/// Only databases a test creates may be dropped: a prefix and a 32-digit id.
105
6444
fn is_test_database(name: &str) -> bool {
106
6444
    PREFIXES
107
6444
        .iter()
108
8874
        .filter_map(|prefix| name.strip_prefix(prefix))
109
205056
        .any(|id| id.len() == 32 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
110
6444
}
111

            
112
6462
fn remove(target: Target) -> Result<(), Failure> {
113
6462
    tokio::runtime::Builder::new_current_thread()
114
6462
        .enable_all()
115
6462
        .build()?
116
6462
        .block_on(remove_target(target))
117
6462
}
118

            
119
/// The database goes first: a failed drop must leave the row that names it.
120
6462
async fn remove_target(target: Target) -> Result<(), Failure> {
121
6462
    let mut conn = PgConnection::connect(&std::env::var("DATABASE_URL")?).await?;
122
6462
    let (user, database) = resolve(&mut conn, target).await?;
123
6462
    if let Some(database) = &database
124
6444
        && !is_test_database(database)
125
    {
126
36
        return Err(format!("refusing to drop `{database}`, not a test database").into());
127
6426
    }
128
6426
    if let Some(database) = database {
129
6408
        drop_database(&mut conn, &database).await?;
130
18
    }
131
6408
    if let Some(user) = user {
132
5256
        sqlx::query("DELETE FROM users WHERE id = $1")
133
5256
            .bind(user)
134
5256
            .execute(&mut conn)
135
5256
            .await?;
136
1152
    }
137
6408
    conn.close().await?;
138
6408
    Ok(())
139
6462
}
140

            
141
/// Closes our own sessions, then a plain `DROP`, which waits out autovacuum.
142
/// Only a reconnecting pool (SQLSTATE 55006) is retried, a bounded number of times.
143
6408
async fn drop_database(conn: &mut PgConnection, database: &str) -> Result<(), sqlx::Error> {
144
6408
    let statement = format!("DROP DATABASE IF EXISTS \"{database}\"");
145
6408
    let mut attempt = 1;
146
    loop {
147
6408
        sqlx::query(
148
6408
            "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 \
149
6408
             AND backend_type = 'client backend' AND usename = current_user \
150
6408
             AND pid <> pg_backend_pid()",
151
6408
        )
152
6408
        .bind(database)
153
6408
        .execute(&mut *conn)
154
6408
        .await?;
155
6408
        match sqlx::query(sqlx::AssertSqlSafe(statement.clone()))
156
6408
            .execute(&mut *conn)
157
6408
            .await
158
        {
159
            Err(sqlx::Error::Database(error))
160
18
                if error.code().as_deref() == Some(IN_USE) && attempt < DROP_ATTEMPTS =>
161
            {
162
                attempt += 1;
163
            }
164
6408
            outcome => return outcome.map(drop),
165
        }
166
        tokio::time::sleep(std::time::Duration::from_millis(250)).await;
167
    }
168
6408
}
169

            
170
6462
async fn resolve(
171
6462
    conn: &mut PgConnection,
172
6462
    target: Target,
173
6462
) -> Result<(Option<Uuid>, Option<String>), Failure> {
174
6462
    Ok(match target {
175
1188
        Target::Database(database) => (None, Some(database)),
176
4158
        Target::Tenant(user, database) => (Some(user), Some(database)),
177
18
        Target::Row(user) => (Some(user), None),
178
        Target::Registered(email) => {
179
1098
            let user: Option<Uuid> = sqlx::query_scalar("SELECT id FROM users WHERE email = $1")
180
1098
                .bind(server::command::user::fold_email(&email))
181
1098
                .fetch_optional(&mut *conn)
182
1098
                .await?;
183
1098
            (user, user.map(tenant_database))
184
        }
185
    })
186
6462
}