Lines
75 %
Functions
78.57 %
Branches
100 %
//! Whether the global directory carries this binary's migration set.
use crate::db::DBError;
/// How a database's applied migrations differ from this binary's.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct SchemaDrift {
/// Embedded here, not applied there: the directory is behind this binary.
pub(crate) missing: Vec<i64>,
/// Applied there, unknown here: the directory is AHEAD, so this binary is
/// the stale one — a rolled-back image, or one whose migration files were
/// edited in place after being applied.
pub(crate) unknown: Vec<i64>,
}
impl SchemaDrift {
pub(super) fn is_aligned(&self) -> bool {
self.missing.is_empty() && self.unknown.is_empty()
/// Compares two migration sets by version, in BOTH directions.
///
/// Versions rather than counts, because the set has a deliberate gap
/// (1, 2, 3, 5, 6) and "five applied" is not "the right five applied".
/// Both directions, because a one-way check is only half a gate. A binary older
/// than the directory passes `embedded ⊆ applied` and then fails on every single
/// tenant — sqlx refuses a version it does not know — turning a deployment
/// mistake into a fleet-wide quarantine whose verdicts outrank the correct
/// run's, because they were written later.
pub(super) fn schema_drift(embedded: &[i64], applied: &[i64]) -> SchemaDrift {
SchemaDrift {
missing: embedded
.iter()
.filter(|version| !applied.contains(version))
.copied()
.collect(),
unknown: applied
.filter(|version| !embedded.contains(version))
/// Refuses to run unless the GLOBAL database already carries this binary's
/// migration set.
/// The Job and the app are applied by different Flux Kustomizations, and
/// `dependsOn` waits for the app to be *Ready* — which it can be on a previous
/// revision. So the Job can start before the release it belongs to has migrated
/// the global directory, read a `users` table shaped by the older schema, and
/// carry that misunderstanding into every tenant.
/// Checking the precondition directly is better than trusting the ordering:
/// it holds however the Job came to be scheduled.
pub(super) async fn assert_global_schema_current() -> Result<(), DBError> {
let mut conn = crate::db::get_connection().await?;
let applied: Vec<i64> =
sqlx::query_scalar!(r#"SELECT version as "version!" FROM _sqlx_migrations WHERE success"#)
.fetch_all(&mut *conn)
.await
.map_err(DBError::Sqlx)?;
let embedded: Vec<i64> = sqlx::migrate!("../migrations")
.map(|m| m.version)
.collect();
let drift = schema_drift(&embedded, &applied);
if drift.is_aligned() {
return Ok(());
Err(DBError::GlobalSchemaStale(format!(
"this binary and the global directory disagree: missing {:?}, unknown {:?}. \
Missing means the directory is behind this release; unknown means this \
binary is behind the directory. Either way, migrating tenants from here \
would quarantine them on a disagreement that is not theirs",
drift.missing, drift.unknown
)))