1
//! Bringing every tenant database to the current schema.
2
//!
3
//! `boot()` migrates only the global database, and provisioning migrates a
4
//! tenant once, at creation. Nothing else ever touched an existing tenant — so
5
//! before this module the first tenant-facing migration after launch reached
6
//! the global database and newly registered users, and no existing user, ever.
7
//! CI stayed green (fresh databases), the deploy stayed green (global
8
//! migrates), and each pre-existing user broke at runtime, one feature at a
9
//! time.
10
//!
11
//! This runs as its own process, never inside a serving one. `boot()` is
12
//! awaited before either binary serves and a boot error exits, so a fan-out
13
//! there would let one unreachable tenant crash-loop web and sshd for every
14
//! user.
15
//!
16
//! Reconciliation is against each tenant's own `_sqlx_migrations`, via the
17
//! ordinary migrator. There is deliberately no central version table: applied
18
//! state is already recorded per tenant, a mirror can drift, and under the
19
//! shared DDL-only rule its `CREATE TABLE` would land in every tenant database
20
//! anyway.
21

            
22
use crate::db::{DBError, migrate_on};
23
use crate::provision::dsn_for;
24
use sqlx::types::Uuid;
25
use sqlx::{Connection, PgConnection};
26
use std::time::Duration;
27

            
28
mod directory;
29
pub(crate) mod jobs;
30
mod schema;
31

            
32
pub(crate) use directory::inventory;
33
use directory::{database_now, publish};
34
#[cfg(test)]
35
pub(crate) use jobs::run as run_tenant_jobs;
36
use schema::assert_global_schema_current;
37
#[cfg(test)]
38
use schema::schema_drift;
39
#[cfg(test)]
40
mod tests;
41

            
42
// Tenants are migrated ONE AT A TIME, deliberately.
43
//
44
// Every concurrent worker costs a tenant connection on top of the admin pool,
45
// and ADR 0032 reserves five connections for this whole process; four workers
46
// spent about thirteen. Sequential also keeps the migration on the very
47
// connection that holds the claim, which a spawned worker cannot do — sqlx's
48
// migrator future is not `Send` while it borrows a connection.
49
//
50
// The cost is wall-clock on a large fleet. Revisit by giving the migrator its
51
// own capped pool and a `Send`-safe worker, not by adding threads here.
52

            
53
/// Ceiling on one tenant's migration. Without it a single tenant holding a lock
54
/// stalls the whole run.
55
const TENANT_DEADLINE: Duration = Duration::from_secs(120);
56

            
57
/// Bound on reaching a tenant at all, so connect cannot eat the outer budget.
58
const CONNECT_DEADLINE: Duration = Duration::from_secs(10);
59

            
60
/// Backstop around connect, claim and migration together. Looser than
61
/// [`TENANT_DEADLINE`] so the inner deadline normally fires first and gets to
62
/// close the connection.
63
const VISIT_DEADLINE: Duration = Duration::from_secs(200);
64

            
65
/// Connection attempts before a tenant is quarantined.
66
const CONNECT_ATTEMPTS: u32 = 2;
67

            
68
/// Pause between those attempts.
69
const CONNECT_RETRY_DELAY: Duration = Duration::from_secs(3);
70

            
71
/// Advisory-lock key, so two migrator processes cannot work one tenant at once.
72
///
73
/// Taken inside the *tenant's own* database rather than a shared table: there
74
/// is no central state to drift, and a lock dies with the connection holding
75
/// it, so a killed worker frees its claim without a lease to expire.
76
const CLAIM_LOCK: i64 = 0x6e6f_6d69_0001;
77

            
78
/// How often to re-attempt a claim another worker currently holds.
79
const CLAIM_POLL: Duration = Duration::from_secs(2);
80

            
81
/// How many times the directory is re-read looking for tenants that appeared
82
/// mid-run. Bounded so a steady stream of registrations cannot keep the Job
83
/// alive forever; anything still missed is caught by the next release's run.
84
const INVENTORY_ROUNDS: usize = 3;
85

            
86
/// How long to wait out a peer's claim before giving up on this tenant.
87
/// Bounded well inside [`TENANT_DEADLINE`] so the migration itself still has
88
/// room once the claim is won.
89
const CLAIM_DEADLINE: Duration = Duration::from_secs(45);
90

            
91
/// What became of one tenant.
92
#[derive(Debug, Clone, PartialEq, Eq)]
93
pub enum Outcome {
94
    /// Verified at the current schema by *this* run.
95
    Migrated,
96
    /// Another worker held the claim for the whole deadline, so this run never
97
    /// saw the tenant's schema. Not a success: the holder may since have timed
98
    /// out, panicked or been killed, and nothing would say so.
99
    Unresolved,
100
    /// Failed, and recorded in the global directory.
101
    Quarantined(String),
102
    /// The schema is current but a data job failed. Not a quarantine: the
103
    /// tenant is served normally and the job is retried by the next run.
104
    JobFailed(String),
105
}
106

            
107
#[derive(Debug, Default)]
108
pub struct FleetReport {
109
    pub migrated: usize,
110
    /// Tenants this run could not verify because another worker held the claim.
111
    pub unresolved: Vec<Uuid>,
112
    pub quarantined: Vec<(Uuid, String)>,
113
    /// Tenants at the current schema whose data job failed.
114
    pub job_failed: Vec<(Uuid, String)>,
115
    /// Tenants whose verdict could not be written to the directory. The
116
    /// dangerous case: a tenant that failed but whose quarantine did not stick
117
    /// is still being served.
118
    pub unpublished: Vec<(Uuid, String)>,
119
}
120

            
121
impl FleetReport {
122
    /// Whether every tenant was accounted for.
123
    ///
124
    /// A quarantined tenant does not stop the *fleet* — that is the whole point
125
    /// of quarantine — but it does mean this run left work undone, and the exit
126
    /// code is what a deployment gate reads. Unresolved and unpublished tenants
127
    /// count too: in both cases the run finished without knowing, or without
128
    /// recording, the state of a customer's database.
129
    #[must_use]
130
1806
    pub const fn is_healthy(&self) -> bool {
131
1806
        self.quarantined.is_empty()
132
1445
            && self.job_failed.is_empty()
133
1264
            && self.unresolved.is_empty()
134
903
            && self.unpublished.is_empty()
135
1806
    }
136

            
137
    #[must_use]
138
1
    pub fn summary(&self) -> String {
139
1
        format!(
140
            "migrated {}, quarantined {}, job failed {}, unresolved {}, unpublished {}",
141
1
            self.migrated,
142
1
            self.quarantined.len(),
143
1
            self.job_failed.len(),
144
1
            self.unresolved.len(),
145
1
            self.unpublished.len()
146
        )
147
1
    }
148
}
149

            
150
/// Migrates one tenant, holding a claim for the duration.
151
///
152
/// Waits for a claim another worker holds rather than declaring victory over a
153
/// tenant it never looked at. Once the claim is won the migrator runs
154
/// regardless of what the previous holder did: it is idempotent, so running it
155
/// after a peer's success costs a no-op, and running it after a peer *died*
156
/// mid-way is exactly the repair that is needed.
157
8820
async fn migrate_tenant(database_name: &str) -> Result<Outcome, DBError> {
158
8820
    let dsn = dsn_for(database_name)?;
159
8820
    let mut conn = connect(&dsn).await?;
160

            
161
7740
    if !claim(&mut conn, CLAIM_DEADLINE).await? {
162
        let _ = conn.close().await;
163
        return Ok(Outcome::Unresolved);
164
7380
    }
165

            
166
    // Migrated on the claim connection itself. A second connection per worker
167
    // would put the run at roughly thirteen against the five ADR 0032 reserves
168
    // for it — a budget breach during exactly the operation that must not fail.
169
    //
170
    // The deadline is applied HERE rather than around the whole call: cancelling
171
    // this future from outside would drop the connection without closing it.
172
7380
    let migrated = tokio::time::timeout(TENANT_DEADLINE, migrate_on(&mut conn)).await;
173
7380
    let outcome = match migrated {
174
7380
        Ok(Ok(())) => Ok(run_jobs(&mut conn).await),
175
        Ok(Err(e)) => Err(e),
176
        Err(_) => Ok(Outcome::Quarantined(format!(
177
            "migration exceeded {}s",
178
            TENANT_DEADLINE.as_secs()
179
        ))),
180
    };
181

            
182
    // Closing the connection drops the lock; do it whether or not we succeeded,
183
    // and whether or not we ran out of time.
184
7380
    let _ = conn.close().await;
185
7380
    outcome
186
8820
}
187

            
188
/// The data jobs of a tenant whose schema is already verified: a failure here
189
/// leaves the schema intact, so it must not quarantine.
190
7381
async fn run_jobs(conn: &mut PgConnection) -> Outcome {
191
7381
    match tokio::time::timeout(TENANT_DEADLINE, jobs::run(conn)).await {
192
7201
        Ok(Ok(())) => Outcome::Migrated,
193
180
        Ok(Err(e)) => Outcome::JobFailed(e.to_string()),
194
        Err(_) => Outcome::JobFailed(format!("data jobs exceeded {}s", TENANT_DEADLINE.as_secs())),
195
    }
196
7381
}
197

            
198
/// Connects to a tenant, retrying a refused or slow connection once.
199
///
200
/// The only retry in a visit, and deliberately before any claim is taken: a
201
/// migration that failed may still hold its advisory lock, so retrying one
202
/// would find its own claim and learn nothing.
203
8821
async fn connect(dsn: &str) -> Result<PgConnection, DBError> {
204
8821
    let mut attempt = 1;
205
    loop {
206
9902
        match tokio::time::timeout(CONNECT_DEADLINE, PgConnection::connect(dsn)).await {
207
7740
            Ok(Ok(conn)) => return Ok(conn),
208
2162
            _ if attempt < CONNECT_ATTEMPTS => {
209
1081
                tokio::time::sleep(CONNECT_RETRY_DELAY).await;
210
1081
                attempt += 1;
211
            }
212
1080
            Ok(Err(e)) => return Err(DBError::Sqlx(e)),
213
1
            Err(_) => return Err(DBError::ConnectTimedOut),
214
        }
215
    }
216
8821
}
217

            
218
/// Takes the tenant's claim, waiting out a peer that already holds it.
219
///
220
/// Polls rather than using the blocking `pg_advisory_lock`, so the surrounding
221
/// timeout can actually interrupt it — a blocked lock wait inside Postgres
222
/// would ignore a cancelled future and hold the connection open.
223
7740
async fn claim(conn: &mut PgConnection, deadline: Duration) -> Result<bool, DBError> {
224
7740
    let give_up_at = tokio::time::Instant::now() + deadline;
225

            
226
    loop {
227
8280
        let taken: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
228
8280
            .bind(CLAIM_LOCK)
229
8280
            .fetch_one(&mut *conn)
230
8280
            .await
231
8280
            .map_err(DBError::Sqlx)?;
232

            
233
7920
        if taken {
234
7380
            return Ok(true);
235
540
        }
236

            
237
540
        if tokio::time::Instant::now() >= give_up_at {
238
            return Ok(false);
239
540
        }
240

            
241
540
        tokio::time::sleep(CLAIM_POLL).await;
242
    }
243
7740
}
244

            
245
/// Runs one tenant to a verdict, converting any failure into a quarantine
246
/// reason rather than propagating it — one sick tenant must not end the run.
247
///
248
/// A timeout quarantines rather than passing: the migration was cancelled
249
/// mid-flight, so its transaction rolled back and the tenant is on whatever
250
/// schema it had before. Unknown is not the same as fine.
251
8820
async fn visit(database_name: &str) -> Outcome {
252
    // The backstop around connect, claim and migration together; looser than
253
    // `TENANT_DEADLINE` so the inner deadline normally fires first.
254
8820
    match tokio::time::timeout(VISIT_DEADLINE, migrate_tenant(database_name)).await {
255
7380
        Ok(Ok(outcome)) => outcome,
256
1440
        Ok(Err(e)) => Outcome::Quarantined(e.to_string()),
257
        Err(_) => Outcome::Quarantined(format!("tenant exceeded {}s", VISIT_DEADLINE.as_secs())),
258
    }
259
8820
}
260

            
261
/// Migrates every tenant in the directory.
262
///
263
/// Skips `admin_user_id`, whose row points at the global database that the
264
/// ordinary boot migration already handled. Quarantined tenants are retried:
265
/// quarantine records a failure, it is not a tombstone.
266
///
267
/// Never seeds. `server/seed.sql` must not run against a per-user database —
268
/// an implementer reusing boot-shaped logic here would insert the admin user
269
/// and global config into every tenant.
270
///
271
/// # Errors
272
/// Only for failures that prevent the run itself: an unreachable *global*
273
/// directory, or a missing `DATABASE_URL`. A tenant that cannot be migrated is
274
/// quarantined and reported, not raised.
275
1800
pub async fn migrate_fleet(admin_user_id: Uuid) -> Result<FleetReport, DBError> {
276
    // Before anything: never fan out from a directory older than this binary.
277
1800
    assert_global_schema_current().await?;
278

            
279
    // The database's clock, not this host's. The fence compares against
280
    // `quarantined_at`, written by `now()` inside Postgres; comparing that to a
281
    // migrator host's clock makes correctness a function of clock skew between
282
    // two machines.
283
1800
    let started = database_now().await?;
284
1800
    let mut report = FleetReport::default();
285
1800
    let mut seen: Vec<Uuid> = Vec::new();
286

            
287
    // Re-inventoried until it stops growing. A single snapshot would miss a
288
    // tenant registered while the run was in progress — by an old pod still
289
    // serving, whose provisioning carries *its* migration set — and the run
290
    // would still exit 0 over a tenant nobody brought current.
291
    //
292
    // This NARROWS the window; it does not close it. A tenant registered after
293
    // the last read is still missed, and the run still exits 0. Closing it needs
294
    // a barrier between provisioning and this run — a shared lock, or a schema
295
    // generation that provisioning stamps and this reconciles against. Until
296
    // then the guarantee rests where ADR 0032 puts it: expand/contract, so the
297
    // serving code works on both schemas across a release.
298
1800
    for round in 1..=INVENTORY_ROUNDS {
299
4500
        let pending: Vec<(Uuid, String)> = inventory(admin_user_id)
300
4500
            .await?
301
            .into_iter()
302
16920
            .filter(|(id, _)| !seen.contains(id))
303
            .collect();
304

            
305
4500
        if pending.is_empty() {
306
1260
            break;
307
3240
        }
308

            
309
3240
        tracing::info!(
310
            "fleet migration round {round}: {} tenant(s) to visit",
311
            pending.len()
312
        );
313

            
314
3240
        for (id, database_name) in pending {
315
8820
            seen.push(id);
316
8820
            let outcome = visit(&database_name).await;
317

            
318
            // Published as each tenant lands. Collecting verdicts first would
319
            // leave a tenant that failed early still being served for as long
320
            // as the rest of the fleet takes.
321
8820
            if let Err(e) = publish(id, &outcome, started).await {
322
                tracing::error!("could not record the verdict for {database_name}: {e}");
323
                report.unpublished.push((id, e.to_string()));
324
8820
            }
325

            
326
8820
            match outcome {
327
7200
                Outcome::Migrated => report.migrated += 1,
328
                Outcome::Unresolved => {
329
                    tracing::warn!(
330
                        "{database_name} stayed claimed by another worker; this run did not verify it"
331
                    );
332
                    report.unresolved.push(id);
333
                }
334
                Outcome::JobFailed(reason) => {
335
180
                    tracing::error!("data job failed on {database_name}: {reason}");
336
180
                    report.migrated += 1;
337
180
                    report.job_failed.push((id, reason));
338
                }
339
                Outcome::Quarantined(reason) => {
340
1440
                    tracing::error!("quarantining {database_name}: {reason}");
341
1440
                    report.quarantined.push((id, reason));
342
                }
343
            }
344
        }
345
    }
346

            
347
1800
    tracing::info!("fleet migration finished: {}", report.summary());
348
1800
    Ok(report)
349
1800
}