1
//! Shared fixtures for the fleet-migration suites.
2
//!
3
//! Each suite is its own test binary, and that is deliberate: `server::db`'s
4
//! admin pool is a process-static `OnceCell` bound to the first runtime that
5
//! touches it, so scenarios sharing a process must also share one `#[tokio::test]`
6
//! — which hides them behind a single name in the coverage output. Separate
7
//! binaries give each scenario its own process, its own pool, and its own
8
//! reportable name.
9
//!
10
//! Because the binaries run concurrently against ONE global directory, every
11
//! assertion here is per-tenant-id. Never assert on fleet-wide counts or on
12
//! `FleetReport::is_healthy`: another suite's deliberately-broken tenant is
13
//! visible to this one's run.
14
//!
15
//! It lives in the lib rather than `tests/fleet_support/mod.rs` because that
16
//! module would be compiled into every suite, and each suite uses only part of
17
//! it — producing dead-code warnings in the binaries that use the rest.
18

            
19
use crate::tenant_guard::TestTenant;
20
use sqlx::postgres::PgPoolOptions;
21
use sqlx::{Executor, Row};
22
use uuid::Uuid;
23

            
24
216
pub fn admin_id() -> Uuid {
25
216
    server::bootstrap::ADMIN_USER_ID
26
216
        .parse()
27
216
        .expect("admin id is a uuid")
28
216
}
29

            
30
396
fn database_url() -> String {
31
396
    std::env::var("DATABASE_URL").expect("DATABASE_URL must be set for fleet tests")
32
396
}
33

            
34
216
pub fn dsn_for(database_name: &str) -> String {
35
216
    let url = database_url();
36
216
    let (prefix, rest) = url.split_once("://").expect("scheme");
37
216
    let authority = rest.split('/').next().expect("authority");
38
216
    format!("{prefix}://{authority}/{database_name}")
39
216
}
40

            
41
180
pub async fn admin_connect() -> sqlx::PgPool {
42
180
    PgPoolOptions::new()
43
180
        .max_connections(2)
44
180
        .connect(&database_url())
45
180
        .await
46
180
        .expect("connect to admin DB")
47
180
}
48

            
49
144
pub async fn create_database(admin: &sqlx::PgPool, database_name: &str) {
50
144
    admin
51
144
        .execute(sqlx::query(sqlx::AssertSqlSafe(format!(
52
144
            "CREATE DATABASE \"{database_name}\""
53
144
        ))))
54
144
        .await
55
144
        .expect("create tenant database");
56
144
}
57

            
58
/// Registers a tenant in the directory, optionally creating its database.
59
///
60
/// A tenant whose database is never created is the "unreachable" case: the
61
/// directory says where it lives and nothing is there.
62
///
63
/// The returned guard removes the database and the directory row when dropped.
64
180
pub async fn register_tenant(
65
180
    admin: &sqlx::PgPool,
66
180
    label: &str,
67
180
    create: bool,
68
180
) -> (Uuid, String, TestTenant) {
69
180
    let (id, database_name, guard) = new_tenant();
70
180
    if create {
71
90
        create_database(admin, &database_name).await;
72
90
    }
73
180
    enter_directory(admin, label, id, &database_name).await;
74
180
    (id, database_name, guard)
75
180
}
76

            
77
/// A fresh tenant id and its database name, not yet in the directory, with the
78
/// guard that removes both when dropped.
79
216
pub fn new_tenant() -> (Uuid, String, TestTenant) {
80
216
    let id = Uuid::new_v4();
81
216
    let database_name = format!("nomi_fleet_{}", id.simple());
82
216
    let guard = TestTenant::tenant(id, database_name.clone());
83
216
    (id, database_name, guard)
84
216
}
85

            
86
/// Lists a tenant in the directory, where every fleet run will find it.
87
///
88
/// Fleet runs from other suites run concurrently, so a tenant whose database
89
/// must start in a particular state is prepared BEFORE it is listed here.
90
216
pub async fn enter_directory(admin: &sqlx::PgPool, label: &str, id: Uuid, database_name: &str) {
91
216
    admin
92
216
        .execute(
93
216
            sqlx::query(
94
216
                "INSERT INTO users (id, user_name, email, user_password, database_name) \
95
216
                 VALUES ($1, $2, $3, 'x', $4)",
96
216
            )
97
216
            .bind(id)
98
216
            .bind(label)
99
216
            .bind(format!("{label}-{id}@example.test"))
100
216
            .bind(database_name),
101
216
        )
102
216
        .await
103
216
        .expect("register tenant");
104
216
}
105

            
106
/// The quarantine reason recorded for a user, if any.
107
///
108
/// A row that does not exist reads the same as one carrying no quarantine. The
109
/// seeded admin only exists after `boot()` has run, and these suites migrate
110
/// without seeding, so requiring the row would make them depend on whatever a
111
/// previous run happened to leave behind.
112
180
pub async fn quarantine_of(admin: &sqlx::PgPool, id: Uuid) -> Option<String> {
113
180
    sqlx::query("SELECT quarantine_reason FROM users WHERE id = $1")
114
180
        .bind(id)
115
180
        .fetch_optional(admin)
116
180
        .await
117
180
        .expect("read quarantine")
118
180
        .and_then(|row| row.get::<Option<String>, _>(0))
119
180
}
120

            
121
/// How many migrations a tenant has applied.
122
162
pub async fn applied_migrations(database_name: &str) -> i64 {
123
162
    let Ok(pool) = PgPoolOptions::new()
124
162
        .max_connections(1)
125
162
        .connect(&dsn_for(database_name))
126
162
        .await
127
    else {
128
        return -1;
129
    };
130

            
131
162
    let applied = sqlx::query_scalar("SELECT count(*) FROM _sqlx_migrations WHERE success")
132
162
        .fetch_one(&pool)
133
162
        .await
134
162
        .unwrap_or(0);
135

            
136
162
    pool.close().await;
137
162
    applied
138
162
}
139

            
140
/// The whole embedded set, not merely "some". Counting "at least one" would pass
141
/// a tenant stuck on 0001 with every later migration skipped — exactly the
142
/// failure the fleet migrator exists to prevent.
143
162
pub fn expected_migrations() -> i64 {
144
162
    i64::try_from(server::db::MIGRATOR.iter().count()).expect("migration count")
145
162
}
146

            
147
144
pub async fn is_fully_migrated(database_name: &str) -> bool {
148
144
    applied_migrations(database_name).await == expected_migrations()
149
144
}
150

            
151
/// Did this run account for *our* tenant? Per-id, because other suites run
152
/// concurrently against the same directory.
153
144
pub fn accounted_for(report: &server::fleet::FleetReport, id: Uuid) -> bool {
154
144
    !report.quarantined.iter().any(|(q, _)| *q == id) && !report.unresolved.contains(&id)
155
144
}
156

            
157
18
pub fn quarantine_reason_in(report: &server::fleet::FleetReport, id: Uuid) -> Option<String> {
158
18
    report
159
18
        .quarantined
160
18
        .iter()
161
18
        .find(|(q, _)| *q == id)
162
18
        .map(|(_, reason)| reason.clone())
163
18
}
164

            
165
/// Brings a tenant up to only the FIRST `count` migrations, leaving it on a
166
/// genuinely older schema.
167
///
168
/// Built by copying that many migration files into a scratch directory and
169
/// pointing a fresh `Migrator` at it: sqlx's embedded migrator has no
170
/// run-to-version API, and slicing by array index would be wrong here anyway —
171
/// the set has a deliberate version gap (1, 2, 3, 5, 6), so index N and version
172
/// N are different things.
173
18
pub async fn migrate_to_first(database_name: &str, count: usize) {
174
18
    let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
175
18
        .parent()
176
18
        .expect("workspace root")
177
18
        .join("migrations");
178

            
179
18
    let mut files: Vec<_> = std::fs::read_dir(&source)
180
18
        .expect("read migrations")
181
18
        .filter_map(Result::ok)
182
162
        .map(|e| e.file_name().to_string_lossy().into_owned())
183
162
        .filter(|n| n.ends_with(".sql"))
184
        .collect();
185
18
    files.sort();
186

            
187
18
    let scratch = std::env::temp_dir().join(format!("nomi-partial-{}", Uuid::new_v4().simple()));
188
18
    std::fs::create_dir_all(&scratch).expect("scratch dir");
189
18
    for name in files.iter().take(count) {
190
54
        std::fs::copy(source.join(name), scratch.join(name)).expect("copy migration");
191
    }
192

            
193
18
    let partial = sqlx::migrate::Migrator::new(scratch.as_path())
194
18
        .await
195
18
        .expect("build partial migrator");
196

            
197
18
    let pool = PgPoolOptions::new()
198
18
        .max_connections(1)
199
18
        .connect(&dsn_for(database_name))
200
18
        .await
201
18
        .expect("connect to tenant");
202
18
    partial.run(&pool).await.expect("apply partial migrations");
203
18
    pool.close().await;
204

            
205
18
    std::fs::remove_dir_all(&scratch).ok();
206
18
}