Skip to main content

haste_migrations/
lib.rs

1//! Haste Health's database migrations, with the Rust code some of them have,
2//! and what runs them.
3//!
4//! A migration is a `.sql` file in a folder of `sql/`, one folder for each set
5//! of tables: `sql/repository`, `sql/search` (the PG search index) and
6//! `sql/document-storage`. sqlx applies the files of a folder in version order
7//! and records each in the folder's migrations table. The crates that read and
8//! write the tables hold no migrations of their own.
9//!
10//! Some work is more than SQL can do: putting a stored secret under another
11//! key takes the server's keys. A migration with such work is still a `.sql`
12//! file in its folder, and its code is a step: a module named after the
13//! migration, with an `m` in front since a module name cannot start with a
14//! digit, in the module of its folder.
15//!
16//! ```text
17//! sql/repository/20270101120000_reencrypt_values.sql
18//! src/repository/m20270101120000_reencrypt_values.rs
19//! ```
20//!
21//! [`run`] runs a step when it comes to the step's migration: after every
22//! earlier migration, in the transaction that then applies the migration's SQL
23//! and records it. The step's work, the SQL and the record commit together or
24//! not at all, so a step runs once for a database, and a step that fails
25//! leaves nothing behind but its migration, still to run.
26//!
27//! This crate depends on whatever the steps need, the server included, so
28//! nothing depends on it but the `haste-health` binary, whose `admin migrate`
29//! runs the migrations: [`repository`], [`search`] and [`document_storage`].
30//!
31//! When writing a step:
32//!
33//! - Use SQL and row types of the step's own, not the repository's. A step
34//!   runs against the schema as the earlier migrations leave it, which on a
35//!   new database is not the schema of today.
36//! - Keep it to what one transaction can do. Rewriting many rows is a job,
37//!   between a migration that adds the new shape and one that drops the old.
38//! - A step stays for as long as its migration does, since a new database runs
39//!   every migration.
40//! - Its migration can be applied without it, by sqlx's CLI or
41//!   `#[sqlx::test(migrations = ...)]`, and is then recorded without the step's
42//!   work. That is harmless on an empty database only.
43
44use std::{collections::HashSet, fmt::Display, future::Future, pin::Pin};
45
46use haste_fhir_model::r4::generated::terminology::IssueType;
47use haste_fhir_operation_error::OperationOutcomeError;
48use sqlx::{
49    PgConnection, PgPool,
50    migrate::{Migrate as _, Migration, Migrator},
51};
52
53pub mod document_storage;
54pub mod repository;
55pub mod search;
56
57/// What the code of a step returns.
58pub type StepFuture<'c> =
59    Pin<Box<dyn Future<Output = Result<(), OperationOutcomeError>> + Send + 'c>>;
60
61/// The Rust code of a migration.
62pub struct Step<Context> {
63    /// The version of the migration the code is part of.
64    pub version: i64,
65    /// Runs the code, on the transaction its migration is applied in, with
66    /// what the steps of the migrator are given.
67    pub run: for<'c> fn(&'c mut PgConnection, &'c Context) -> StepFuture<'c>,
68}
69
70/// The connections [`run`] needs its pool to allow.
71pub const CONNECTIONS: u32 = 2;
72
73fn failed(what: impl Display, error: impl Display) -> OperationOutcomeError {
74    OperationOutcomeError::fatal(IssueType::exception(), format!("{what}: {error}"))
75}
76
77/// Applies the migrations of `migrator` that the database of `pool` lacks, in
78/// version order, each with its step if it has one. `context` is what the
79/// steps are given.
80///
81/// The run holds sqlx's migration lock for the database from start to end, so
82/// runs that start together take turns, steps included. It holds the lock on
83/// one connection and applies on another, so `pool` has to allow
84/// [`CONNECTIONS`].
85///
86/// # Errors
87///
88/// Returns an error, before applying anything, if a step is given for a
89/// version that has no migration, for a version twice, or for a migration
90/// that runs outside of a transaction (`-- no-transaction`). Returns an error
91/// if a migration or a step fails, after applying what came before it.
92pub async fn run<Context: Sync>(
93    mut migrator: Migrator,
94    pool: &PgPool,
95    steps: &[Step<Context>],
96    context: &Context,
97) -> Result<(), OperationOutcomeError> {
98    let steps = with_migrations(&migrator, steps)?;
99
100    let mut connection = pool
101        .acquire()
102        .await
103        .map_err(|e| failed("Failed to connect to migrate", e))?;
104    // A run that fails gives up the lock with the connection.
105    connection.close_on_drop();
106    connection
107        .lock()
108        .await
109        .map_err(|e| failed("Failed to take the migration lock", e))?;
110    migrator.set_locking(false);
111
112    for (step, migration) in steps {
113        migrator
114            .run_to(migration.version - 1, pool)
115            .await
116            .map_err(|e| failed("Failed to migrate", e))?;
117        if !is_applied(&mut connection, &migrator, migration.version).await? {
118            apply_with_step(pool, &migrator, step, &migration, context).await?;
119        }
120    }
121
122    migrator
123        .run(pool)
124        .await
125        .map_err(|e| failed("Failed to migrate", e))?;
126    connection
127        .unlock()
128        .await
129        .map_err(|e| failed("Failed to release the migration lock", e))?;
130    Ok(())
131}
132
133/// Each step with its migration, in version order.
134fn with_migrations<'s, Context>(
135    migrator: &Migrator,
136    steps: &'s [Step<Context>],
137) -> Result<Vec<(&'s Step<Context>, Migration)>, OperationOutcomeError> {
138    let mut versions = HashSet::new();
139    let mut with_migrations = steps
140        .iter()
141        .map(|step| {
142            if !versions.insert(step.version) {
143                return Err(failed(
144                    "Cannot migrate",
145                    format!("migration {} is given two steps", step.version),
146                ));
147            }
148            let migration = migrator
149                .iter()
150                .find(|m| m.version == step.version && !m.migration_type.is_down_migration())
151                .ok_or_else(|| {
152                    failed(
153                        "Cannot migrate",
154                        format!("a step is given for migration {}, which does not exist", step.version),
155                    )
156                })?;
157            if migration.no_tx {
158                return Err(failed(
159                    "Cannot migrate",
160                    format!(
161                        "migration {} has a step, so it runs in a transaction, but is marked `-- no-transaction`",
162                        step.version
163                    ),
164                ));
165            }
166            Ok((step, migration.clone()))
167        })
168        .collect::<Result<Vec<_>, _>>()?;
169    with_migrations.sort_by_key(|(step, _)| step.version);
170    Ok(with_migrations)
171}
172
173async fn is_applied(
174    connection: &mut PgConnection,
175    migrator: &Migrator,
176    version: i64,
177) -> Result<bool, OperationOutcomeError> {
178    let applied = connection
179        .list_applied_migrations(&migrator.table_name)
180        .await
181        .map_err(|e| failed("Failed to read the applied migrations", e))?;
182    Ok(applied.iter().any(|applied| applied.version == version))
183}
184
185/// Runs `step`, then applies its migration's SQL and records the migration,
186/// all in one transaction.
187async fn apply_with_step<Context: Sync>(
188    pool: &PgPool,
189    migrator: &Migrator,
190    step: &Step<Context>,
191    migration: &Migration,
192    context: &Context,
193) -> Result<(), OperationOutcomeError> {
194    let name = format!(
195        "migration {} ({})",
196        migration.version, migration.description
197    );
198    let database = |e: sqlx::Error| failed(format!("Failed to apply {name}"), e);
199
200    let mut transaction = pool.begin().await.map_err(database)?;
201    (step.run)(&mut transaction, context)
202        .await
203        .map_err(|e| failed(format!("The step of {name} failed"), e))?;
204    sqlx::raw_sql(migration.sql.clone())
205        .execute(&mut *transaction)
206        .await
207        .map_err(database)?;
208    // Records the migration without applying its SQL again.
209    transaction
210        .skip(&migrator.table_name, migration)
211        .await
212        .map_err(|e| failed(format!("Failed to record {name}"), e))?;
213    transaction.commit().await.map_err(database)?;
214
215    tracing::info!("Applied {name} with its step.");
216    Ok(())
217}