1
//! Whether the global directory carries this binary's migration set.
2

            
3
use crate::db::DBError;
4

            
5
/// How a database's applied migrations differ from this binary's.
6
#[derive(Debug, PartialEq, Eq)]
7
pub(crate) struct SchemaDrift {
8
    /// Embedded here, not applied there: the directory is behind this binary.
9
    pub(crate) missing: Vec<i64>,
10
    /// Applied there, unknown here: the directory is AHEAD, so this binary is
11
    /// the stale one — a rolled-back image, or one whose migration files were
12
    /// edited in place after being applied.
13
    pub(crate) unknown: Vec<i64>,
14
}
15

            
16
impl SchemaDrift {
17
1803
    pub(super) fn is_aligned(&self) -> bool {
18
1803
        self.missing.is_empty() && self.unknown.is_empty()
19
1803
    }
20
}
21

            
22
/// Compares two migration sets by version, in BOTH directions.
23
///
24
/// Versions rather than counts, because the set has a deliberate gap
25
/// (1, 2, 3, 5, 6) and "five applied" is not "the right five applied".
26
///
27
/// Both directions, because a one-way check is only half a gate. A binary older
28
/// than the directory passes `embedded ⊆ applied` and then fails on every single
29
/// tenant — sqlx refuses a version it does not know — turning a deployment
30
/// mistake into a fleet-wide quarantine whose verdicts outrank the correct
31
/// run's, because they were written later.
32
1804
pub(super) fn schema_drift(embedded: &[i64], applied: &[i64]) -> SchemaDrift {
33
    SchemaDrift {
34
1804
        missing: embedded
35
1804
            .iter()
36
14418
            .filter(|version| !applied.contains(version))
37
            .copied()
38
            .collect(),
39
1804
        unknown: applied
40
1804
            .iter()
41
14418
            .filter(|version| !embedded.contains(version))
42
            .copied()
43
            .collect(),
44
    }
45
1804
}
46

            
47
/// Refuses to run unless the GLOBAL database already carries this binary's
48
/// migration set.
49
///
50
/// The Job and the app are applied by different Flux Kustomizations, and
51
/// `dependsOn` waits for the app to be *Ready* — which it can be on a previous
52
/// revision. So the Job can start before the release it belongs to has migrated
53
/// the global directory, read a `users` table shaped by the older schema, and
54
/// carry that misunderstanding into every tenant.
55
///
56
/// Checking the precondition directly is better than trusting the ordering:
57
/// it holds however the Job came to be scheduled.
58
1800
pub(super) async fn assert_global_schema_current() -> Result<(), DBError> {
59
1800
    let mut conn = crate::db::get_connection().await?;
60

            
61
    let applied: Vec<i64> =
62
1800
        sqlx::query_scalar!(r#"SELECT version as "version!" FROM _sqlx_migrations WHERE success"#)
63
1800
            .fetch_all(&mut *conn)
64
1800
            .await
65
1800
            .map_err(DBError::Sqlx)?;
66

            
67
1800
    let embedded: Vec<i64> = sqlx::migrate!("../migrations")
68
1800
        .iter()
69
14400
        .map(|m| m.version)
70
        .collect();
71

            
72
1800
    let drift = schema_drift(&embedded, &applied);
73
1800
    if drift.is_aligned() {
74
1800
        return Ok(());
75
    }
76

            
77
    Err(DBError::GlobalSchemaStale(format!(
78
        "this binary and the global directory disagree: missing {:?}, unknown {:?}. \
79
         Missing means the directory is behind this release; unknown means this \
80
         binary is behind the directory. Either way, migrating tenants from here \
81
         would quarantine them on a disagreement that is not theirs",
82
        drift.missing, drift.unknown
83
    )))
84
1800
}