server/fleet.rs
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
22use crate::db::{DBError, migrate_on};
23use crate::provision::dsn_for;
24use sqlx::types::Uuid;
25use sqlx::{Connection, PgConnection};
26use std::time::Duration;
27
28mod directory;
29pub(crate) mod jobs;
30mod schema;
31
32pub(crate) use directory::inventory;
33use directory::{database_now, publish};
34#[cfg(test)]
35pub(crate) use jobs::run as run_tenant_jobs;
36use schema::assert_global_schema_current;
37#[cfg(test)]
38use schema::schema_drift;
39#[cfg(test)]
40mod 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.
55const TENANT_DEADLINE: Duration = Duration::from_secs(120);
56
57/// Bound on reaching a tenant at all, so connect cannot eat the outer budget.
58const 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.
63const VISIT_DEADLINE: Duration = Duration::from_secs(200);
64
65/// Connection attempts before a tenant is quarantined.
66const CONNECT_ATTEMPTS: u32 = 2;
67
68/// Pause between those attempts.
69const 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.
76const CLAIM_LOCK: i64 = 0x6e6f_6d69_0001;
77
78/// How often to re-attempt a claim another worker currently holds.
79const 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.
84const 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.
89const CLAIM_DEADLINE: Duration = Duration::from_secs(45);
90
91/// What became of one tenant.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub 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)]
108pub 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
121impl 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 pub const fn is_healthy(&self) -> bool {
131 self.quarantined.is_empty()
132 && self.job_failed.is_empty()
133 && self.unresolved.is_empty()
134 && self.unpublished.is_empty()
135 }
136
137 #[must_use]
138 pub fn summary(&self) -> String {
139 format!(
140 "migrated {}, quarantined {}, job failed {}, unresolved {}, unpublished {}",
141 self.migrated,
142 self.quarantined.len(),
143 self.job_failed.len(),
144 self.unresolved.len(),
145 self.unpublished.len()
146 )
147 }
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.
157async fn migrate_tenant(database_name: &str) -> Result<Outcome, DBError> {
158 let dsn = dsn_for(database_name)?;
159 let mut conn = connect(&dsn).await?;
160
161 if !claim(&mut conn, CLAIM_DEADLINE).await? {
162 let _ = conn.close().await;
163 return Ok(Outcome::Unresolved);
164 }
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 let migrated = tokio::time::timeout(TENANT_DEADLINE, migrate_on(&mut conn)).await;
173 let outcome = match migrated {
174 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 let _ = conn.close().await;
185 outcome
186}
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.
190async fn run_jobs(conn: &mut PgConnection) -> Outcome {
191 match tokio::time::timeout(TENANT_DEADLINE, jobs::run(conn)).await {
192 Ok(Ok(())) => Outcome::Migrated,
193 Ok(Err(e)) => Outcome::JobFailed(e.to_string()),
194 Err(_) => Outcome::JobFailed(format!("data jobs exceeded {}s", TENANT_DEADLINE.as_secs())),
195 }
196}
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.
203async fn connect(dsn: &str) -> Result<PgConnection, DBError> {
204 let mut attempt = 1;
205 loop {
206 match tokio::time::timeout(CONNECT_DEADLINE, PgConnection::connect(dsn)).await {
207 Ok(Ok(conn)) => return Ok(conn),
208 _ if attempt < CONNECT_ATTEMPTS => {
209 tokio::time::sleep(CONNECT_RETRY_DELAY).await;
210 attempt += 1;
211 }
212 Ok(Err(e)) => return Err(DBError::Sqlx(e)),
213 Err(_) => return Err(DBError::ConnectTimedOut),
214 }
215 }
216}
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.
223async fn claim(conn: &mut PgConnection, deadline: Duration) -> Result<bool, DBError> {
224 let give_up_at = tokio::time::Instant::now() + deadline;
225
226 loop {
227 let taken: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
228 .bind(CLAIM_LOCK)
229 .fetch_one(&mut *conn)
230 .await
231 .map_err(DBError::Sqlx)?;
232
233 if taken {
234 return Ok(true);
235 }
236
237 if tokio::time::Instant::now() >= give_up_at {
238 return Ok(false);
239 }
240
241 tokio::time::sleep(CLAIM_POLL).await;
242 }
243}
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.
251async 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 match tokio::time::timeout(VISIT_DEADLINE, migrate_tenant(database_name)).await {
255 Ok(Ok(outcome)) => outcome,
256 Ok(Err(e)) => Outcome::Quarantined(e.to_string()),
257 Err(_) => Outcome::Quarantined(format!("tenant exceeded {}s", VISIT_DEADLINE.as_secs())),
258 }
259}
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.
275pub 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 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 let started = database_now().await?;
284 let mut report = FleetReport::default();
285 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 for round in 1..=INVENTORY_ROUNDS {
299 let pending: Vec<(Uuid, String)> = inventory(admin_user_id)
300 .await?
301 .into_iter()
302 .filter(|(id, _)| !seen.contains(id))
303 .collect();
304
305 if pending.is_empty() {
306 break;
307 }
308
309 tracing::info!(
310 "fleet migration round {round}: {} tenant(s) to visit",
311 pending.len()
312 );
313
314 for (id, database_name) in pending {
315 seen.push(id);
316 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 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 }
325
326 match outcome {
327 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 tracing::error!("data job failed on {database_name}: {reason}");
336 report.migrated += 1;
337 report.job_failed.push((id, reason));
338 }
339 Outcome::Quarantined(reason) => {
340 tracing::error!("quarantining {database_name}: {reason}");
341 report.quarantined.push((id, reason));
342 }
343 }
344 }
345 }
346
347 tracing::info!("fleet migration finished: {}", report.summary());
348 Ok(report)
349}