mas_storage_pg/lib.rs
1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8//! An implementation of the storage traits for a PostgreSQL database
9//!
10//! This backend uses [`sqlx`] to interact with the database. Most queries are
11//! type-checked, using introspection data recorded in the `sqlx-data.json`
12//! file. This file is generated by the `sqlx` CLI tool, and should be updated
13//! whenever the database schema changes, or new queries are added.
14//!
15//! # Implementing a new repository
16//!
17//! When a new repository is defined in [`mas_storage`], it should be
18//! implemented here, with the PostgreSQL backend.
19//!
20//! A typical implementation will look like this:
21//!
22//! ```rust
23//! # use async_trait::async_trait;
24//! # use ulid::Ulid;
25//! # use rand::RngCore;
26//! # use mas_data_model::Clock;
27//! # use mas_storage_pg::{DatabaseError, ExecuteExt};
28//! # use sqlx::PgConnection;
29//! # use uuid::Uuid;
30//! #
31//! # // A fake data structure, usually defined in mas-data-model
32//! # #[derive(sqlx::FromRow)]
33//! # struct FakeData {
34//! # id: Ulid,
35//! # }
36//! #
37//! # // A fake repository trait, usually defined in mas-storage
38//! # #[async_trait]
39//! # pub trait FakeDataRepository: Send + Sync {
40//! # type Error;
41//! # async fn lookup(&mut self, id: Ulid) -> Result<Option<FakeData>, Self::Error>;
42//! # async fn add(
43//! # &mut self,
44//! # rng: &mut (dyn RngCore + Send),
45//! # clock: &dyn Clock,
46//! # ) -> Result<FakeData, Self::Error>;
47//! # }
48//! #
49//! /// An implementation of [`FakeDataRepository`] for a PostgreSQL connection
50//! pub struct PgFakeDataRepository<'c> {
51//! conn: &'c mut PgConnection,
52//! }
53//!
54//! impl<'c> PgFakeDataRepository<'c> {
55//! /// Create a new [`FakeDataRepository`] from an active PostgreSQL connection
56//! pub fn new(conn: &'c mut PgConnection) -> Self {
57//! Self { conn }
58//! }
59//! }
60//!
61//! #[derive(sqlx::FromRow)]
62//! struct FakeDataLookup {
63//! fake_data_id: Uuid,
64//! }
65//!
66//! impl From<FakeDataLookup> for FakeData {
67//! fn from(value: FakeDataLookup) -> Self {
68//! Self {
69//! id: value.fake_data_id.into(),
70//! }
71//! }
72//! }
73//!
74//! #[async_trait]
75//! impl<'c> FakeDataRepository for PgFakeDataRepository<'c> {
76//! type Error = DatabaseError;
77//!
78//! #[tracing::instrument(
79//! name = "db.fake_data.lookup",
80//! skip_all,
81//! fields(
82//! db.query.text,
83//! fake_data.id = %id,
84//! ),
85//! err,
86//! )]
87//! async fn lookup(&mut self, id: Ulid) -> Result<Option<FakeData>, Self::Error> {
88//! // Note: here we would use the macro version instead, but it's not possible here in
89//! // this documentation example
90//! let res: Option<FakeDataLookup> = sqlx::query_as(
91//! r#"
92//! SELECT fake_data_id
93//! FROM fake_data
94//! WHERE fake_data_id = $1
95//! "#,
96//! )
97//! .bind(Uuid::from(id))
98//! .traced()
99//! .fetch_optional(&mut *self.conn)
100//! .await?;
101//!
102//! let Some(res) = res else { return Ok(None) };
103//!
104//! Ok(Some(res.into()))
105//! }
106//!
107//! #[tracing::instrument(
108//! name = "db.fake_data.add",
109//! skip_all,
110//! fields(
111//! db.query.text,
112//! fake_data.id,
113//! ),
114//! err,
115//! )]
116//! async fn add(
117//! &mut self,
118//! rng: &mut (dyn RngCore + Send),
119//! clock: &dyn Clock,
120//! ) -> Result<FakeData, Self::Error> {
121//! let created_at = clock.now();
122//! let id = Ulid::from_datetime_with_source(created_at.into(), rng);
123//! tracing::Span::current().record("fake_data.id", tracing::field::display(id));
124//!
125//! // Note: here we would use the macro version instead, but it's not possible here in
126//! // this documentation example
127//! sqlx::query(
128//! r#"
129//! INSERT INTO fake_data (id)
130//! VALUES ($1)
131//! "#,
132//! )
133//! .bind(Uuid::from(id))
134//! .traced()
135//! .execute(&mut *self.conn)
136//! .await?;
137//!
138//! Ok(FakeData {
139//! id,
140//! })
141//! }
142//! }
143//! ```
144//!
145//! A few things to note with the implementation:
146//!
147//! - All methods are traced, with an explicit, somewhat consistent name.
148//! - The SQL statement is included as attribute, by declaring a
149//! `db.query.text` attribute on the tracing span, and then calling
150//! [`ExecuteExt::traced`].
151//! - The IDs are all [`Ulid`], and generated from the clock and the random
152//! number generated passed as parameters. The generated IDs are recorded in
153//! the span.
154//! - The IDs are stored as [`Uuid`] in PostgreSQL, so conversions are required
155//! - "Not found" errors are handled by returning `Ok(None)` instead of an
156//! error.
157//!
158//! [`Ulid`]: ulid::Ulid
159//! [`Uuid`]: uuid::Uuid
160
161#![deny(clippy::future_not_send, missing_docs)]
162#![allow(clippy::module_name_repetitions, clippy::blocks_in_conditions)]
163
164use std::collections::{BTreeMap, BTreeSet, HashSet};
165
166use ::tracing::{Instrument, debug, info, info_span, warn};
167use opentelemetry_semantic_conventions::trace::DB_QUERY_TEXT;
168use sqlx::{
169 Either, PgConnection,
170 migrate::{AppliedMigration, Migrate, MigrateError, Migration, Migrator},
171 postgres::{PgAdvisoryLock, PgAdvisoryLockKey},
172};
173
174pub mod app_session;
175pub mod compat;
176pub mod oauth2;
177pub mod personal;
178pub mod queue;
179pub mod upstream_oauth2;
180pub mod user;
181
182mod errors;
183pub(crate) mod filter;
184pub(crate) mod iden;
185pub(crate) mod pagination;
186pub(crate) mod policy_data;
187pub(crate) mod repository;
188pub(crate) mod telemetry;
189pub(crate) mod tracing;
190pub(crate) mod ulid_at;
191
192pub(crate) use self::errors::DatabaseInconsistencyError;
193pub use self::{
194 errors::DatabaseError,
195 repository::{PgRepository, PgRepositoryFactory},
196 tracing::ExecuteExt,
197};
198
199/// Embedded migrations in the binary
200pub static MIGRATOR: Migrator = sqlx::migrate!();
201
202fn available_migrations() -> BTreeMap<i64, &'static Migration> {
203 MIGRATOR.iter().map(|m| (m.version, m)).collect()
204}
205
206/// This is the list of migrations we've removed from the migration history but
207/// might have been applied in the past
208#[expect(clippy::inconsistent_digit_grouping)]
209const ALLOWED_MISSING_MIGRATIONS: &[i64] = &[
210 // https://github.com/matrix-org/matrix-authentication-service/pull/1585
211 20220709_210445,
212 20230330_210841,
213 20230408_110421,
214];
215
216fn allowed_missing_migrations() -> BTreeSet<i64> {
217 ALLOWED_MISSING_MIGRATIONS.iter().copied().collect()
218}
219
220/// This is a list of possible additional checksums from previous versions of
221/// migrations. The checksum we store in the database is 48 bytes long. We're
222/// not really concerned with partial hash collisions, and to avoid this file to
223/// be completely unreadable, we only store the upper 16 bytes of that hash.
224#[expect(clippy::inconsistent_digit_grouping)]
225const ALLOWED_ALTERNATE_CHECKSUMS: &[(i64, u128)] = &[
226 // https://github.com/element-hq/matrix-authentication-service/pull/5300
227 (20250410_000000, 0x8811_c3ef_dbee_8c00_5b49_25da_5d55_9c3f),
228 (20250410_000001, 0x7990_37b3_2193_8a5d_c72f_bccd_95fd_82e5),
229 (20250410_000002, 0xf2b8_f120_deae_27e7_60d0_79a3_0b77_eea3),
230 (20250410_000003, 0x06be_fc2b_cedc_acf4_b981_02c7_b40c_c469),
231 (20250410_000004, 0x0a90_9c6a_dba7_545c_10d9_60eb_6d30_2f50),
232 (20250410_000006, 0xcc7f_5152_6497_5729_d94b_be0d_9c95_8316),
233 (20250410_000007, 0x12e7_cfab_a017_a5a5_4f2c_18fa_541c_ce62),
234 (20250410_000008, 0x171d_62e5_ee1a_f0d9_3639_6c5a_277c_54cd),
235 (20250410_000009, 0xb1a0_93c7_6645_92ad_df45_b395_57bb_a281),
236 (20250410_000010, 0x8089_86ac_7cff_8d86_2850_d287_cdb1_2b57),
237 (20250410_000011, 0x8d9d_3fae_02c9_3d3f_81e4_6242_2b39_b5b8),
238 (20250410_000012, 0x9805_1372_41aa_d5b0_ebe1_ba9d_28c7_faf6),
239 (20250410_000013, 0x7291_9a97_e4d1_0d45_1791_6e8c_3f2d_e34d),
240 (20250410_000014, 0x811d_f965_8127_e168_4aa2_f177_a4e6_f077),
241 (20250410_000015, 0xa639_0780_aab7_d60d_5fcb_771d_13ed_73ee),
242 (20250410_000016, 0x22b6_e909_6de4_39e3_b2b9_c684_7417_fe07),
243 (20250410_000017, 0x9dfe_b6d3_89e4_e509_651b_2793_8d8d_cd32),
244 (20250410_000018, 0x638f_bdbc_2276_5094_020b_cec1_ab95_c07f),
245 (20250410_000019, 0xa283_84bc_5fd5_7cbd_b5fb_b5fe_0255_6845),
246 (20250410_000020, 0x17d1_54b1_7c6e_fc48_61dd_da3d_f8a5_9546),
247 (20250410_000022, 0xbc36_af82_994a_6f93_8aca_a46b_fc3c_ffde),
248 (20250410_000023, 0x54ec_3b07_ac79_443b_9e18_a2b3_2d17_5ab9),
249 (20250410_000024, 0x8ab4_4f80_00b6_58b2_d757_c40f_bc72_3d87),
250 (20250410_000025, 0x5dc4_2ff3_3042_2f45_046d_10af_ab3a_b583),
251 (20250410_000026, 0x5263_c547_0b64_6425_5729_48b2_ce84_7cad),
252 (20250410_000027, 0x0aad_cb50_1d6a_7794_9017_d24d_55e7_1b9d),
253 (20250410_000028, 0x8fc1_92f8_68df_ca4e_3e2b_cddf_bc12_cffe),
254 (20250410_000029, 0x416c_9446_b6a3_1b49_2940_a8ac_c1c2_665a),
255 (20250410_000030, 0x83a5_e51e_25a6_77fb_2b79_6ea5_db1e_364f),
256 (20250410_000031, 0xfa18_a707_9438_dbc7_2cde_b5f1_ee21_5c7e),
257 (20250410_000032, 0xd669_662e_8930_838a_b142_c3fa_7b39_d2a0),
258 (20250410_000033, 0x4019_1053_cabc_191c_c02e_9aa9_407c_0de5),
259 (20250410_000034, 0xdd59_e595_24e6_4dad_c5f7_fef2_90b8_df57),
260 (20250410_000035, 0x09b4_ea53_2da4_9c39_eb10_db33_6a6d_608b),
261 (20250410_000036, 0x3ca5_9c78_8480_e342_d729_907c_d293_2049),
262 (20250410_000037, 0xc857_2a10_450b_0612_822c_2b86_535a_ea7d),
263 (20250410_000038, 0x1642_39da_9c3b_d9fd_b1e1_72b1_db78_b978),
264 (20250410_000039, 0xdd70_b211_6016_bb84_0d84_f04e_eb8a_59d9),
265 (20250410_000040, 0xe435_ead6_c363_a0b6_e048_dd85_0ecb_9499),
266 (20250410_000041, 0xe9f3_122f_70d4_9839_c818_4b18_0192_ae26),
267 (20250410_000043, 0xec5e_1400_483d_c4bf_6014_aba4_ffc3_6236),
268 (20250410_000044, 0x4750_5eba_4095_6664_78d0_27f9_64bf_64f4),
269 (20250410_000045, 0x9a53_bd70_4cad_2bf1_61d4_f143_0c82_681d),
270 (20250410_121612, 0x25f0_9d20_a897_df18_162d_1c47_b68e_81bd),
271 (20250602_212101, 0xd1a8_782c_b3f0_5045_3f46_49a0_bab0_822b),
272 (20250708_155857, 0xb78e_6957_a588_c16a_d292_a0c7_cae9_f290),
273 (20250915_092635, 0x6854_d58b_99d7_3ac5_82f8_25e5_b1c3_cc0b),
274 (20251127_145951, 0x3bcd_d92e_8391_2a2c_8a18_1d76_354f_96c6),
275];
276
277fn alternate_checksums_map() -> BTreeMap<i64, HashSet<u128>> {
278 let mut map = BTreeMap::new();
279 for (version, checksum) in ALLOWED_ALTERNATE_CHECKSUMS {
280 map.entry(*version)
281 .or_insert_with(HashSet::new)
282 .insert(*checksum);
283 }
284 map
285}
286
287/// Load the list of applied migrations into a map.
288///
289/// It's important to use a [`BTreeMap`] so that the migrations are naturally
290/// ordered by version.
291async fn applied_migrations_map(
292 conn: &mut PgConnection,
293) -> Result<BTreeMap<i64, AppliedMigration>, MigrateError> {
294 let applied_migrations = conn
295 .list_applied_migrations()
296 .await?
297 .into_iter()
298 .map(|m| (m.version, m))
299 .collect();
300
301 Ok(applied_migrations)
302}
303
304/// Checks if the migration table exists
305async fn migration_table_exists(conn: &mut PgConnection) -> Result<bool, sqlx::Error> {
306 sqlx::query_scalar!(
307 r#"
308 SELECT EXISTS (
309 SELECT 1
310 FROM information_schema.tables
311 WHERE table_name = '_sqlx_migrations'
312 ) AS "exists!"
313 "#,
314 )
315 .fetch_one(conn)
316 .await
317}
318
319/// Run the migrations on the given connection
320///
321/// This function acquires an advisory lock on the database to ensure that only
322/// one migrator is running at a time.
323///
324/// # Errors
325///
326/// This function returns an error if the migration fails.
327#[::tracing::instrument(name = "db.migrate", skip_all, err)]
328pub async fn migrate(conn: &mut PgConnection) -> Result<(), MigrateError> {
329 // Get the database name and use it to derive an advisory lock key. This
330 // is the same lock key used by SQLx default migrator, so that it works even
331 // with older versions of MAS, and when running through `cargo sqlx migrate run`
332 let database_name = sqlx::query_scalar!(r#"SELECT current_database() as "current_database!""#)
333 .fetch_one(&mut *conn)
334 .await
335 .map_err(MigrateError::from)?;
336
337 let lock =
338 PgAdvisoryLock::with_key(PgAdvisoryLockKey::BigInt(generate_lock_id(&database_name)));
339
340 // Try to acquire the migration lock in a loop.
341 //
342 // The reason we do that with a `try_acquire` is because in Postgres, `CREATE
343 // INDEX CONCURRENTLY` will *not* complete whilst an advisory lock is being
344 // acquired on another connection. This then means that if we run two
345 // migration process at the same time, one of them will go through and block
346 // on concurrent index creations, because the other will get stuck trying to
347 // acquire this lock.
348 //
349 // To avoid this, we use `try_acquire`/`pg_advisory_lock_try` in a loop, which
350 // will fail immediately if the lock is held by another connection, allowing
351 // potential 'CREATE INDEX CONCURRENTLY' statements to complete.
352 let mut backoff = std::time::Duration::from_millis(250);
353 let mut conn = conn;
354 let mut locked_connection = loop {
355 match lock.try_acquire(conn).await? {
356 Either::Left(guard) => break guard,
357 Either::Right(conn_) => {
358 warn!(
359 "Another process is already running migrations on the database, waiting {duration}s and trying again…",
360 duration = backoff.as_secs_f32()
361 );
362 tokio::time::sleep(backoff).await;
363 backoff = std::cmp::min(backoff * 2, std::time::Duration::from_secs(5));
364 conn = conn_;
365 }
366 }
367 };
368
369 // Creates the migration table if missing
370 // We check if the table exists before calling `ensure_migrations_table` to
371 // avoid the pesky 'relation "_sqlx_migrations" already exists, skipping' notice
372 if !migration_table_exists(locked_connection.as_mut()).await? {
373 locked_connection.as_mut().ensure_migrations_table().await?;
374 }
375
376 for migration in pending_migrations(locked_connection.as_mut()).await? {
377 info!(
378 "Applying migration {version}: {description}",
379 version = migration.version,
380 description = migration.description
381 );
382 locked_connection
383 .as_mut()
384 .apply(migration)
385 .instrument(info_span!(
386 "db.migrate.run_migration",
387 db.migration.version = migration.version,
388 db.migration.description = &*migration.description,
389 { DB_QUERY_TEXT } = &*migration.sql,
390 ))
391 .await?;
392 }
393
394 locked_connection.release_now().await?;
395
396 Ok(())
397}
398
399/// Get the list of pending migrations
400///
401/// # Errors
402///
403/// This function returns an error if there is a problem checking the applied
404/// migrations
405pub async fn pending_migrations(
406 conn: &mut PgConnection,
407) -> Result<Vec<&'static Migration>, MigrateError> {
408 // Load the maps of available migrations, applied migrations, migrations that
409 // are allowed to be missing, alternate checksums for migrations that changed
410 let available_migrations = available_migrations();
411 let allowed_missing = allowed_missing_migrations();
412 let alternate_checksums = alternate_checksums_map();
413 let applied_migrations = if migration_table_exists(&mut *conn).await? {
414 applied_migrations_map(&mut *conn).await?
415 } else {
416 BTreeMap::new()
417 };
418
419 // Check that all applied migrations are still valid
420 for applied_migration in applied_migrations.values() {
421 // Check that we know about the applied migration
422 if let Some(migration) = available_migrations.get(&applied_migration.version) {
423 // Check the migration checksum
424 if applied_migration.checksum != migration.checksum {
425 // The checksum we have in the database doesn't match the one we
426 // have embedded. This might be because a migration was
427 // intentionally changed, so we check the alternate checksums
428 if let Some(alternates) = alternate_checksums.get(&applied_migration.version) {
429 // This converts the first 16 bytes of the checksum into a u128
430 let Some(applied_checksum_prefix) = applied_migration
431 .checksum
432 .get(..16)
433 .and_then(|bytes| bytes.try_into().ok())
434 .map(u128::from_be_bytes)
435 else {
436 return Err(MigrateError::ExecuteMigration(
437 sqlx::Error::InvalidArgument(
438 "checksum stored in database is invalid".to_owned(),
439 ),
440 applied_migration.version,
441 ));
442 };
443
444 if !alternates.contains(&applied_checksum_prefix) {
445 warn!(
446 "The database has a migration applied ({version}) which has known alternative checksums {alternates:x?}, but none of them matched {applied_checksum_prefix:x}",
447 version = applied_migration.version,
448 );
449 return Err(MigrateError::VersionMismatch(applied_migration.version));
450 }
451 } else {
452 return Err(MigrateError::VersionMismatch(applied_migration.version));
453 }
454 }
455 } else if allowed_missing.contains(&applied_migration.version) {
456 // The migration is missing, but allowed to be missing
457 debug!(
458 "The database has a migration applied ({version}) that doesn't exist anymore, but it was intentionally removed",
459 version = applied_migration.version
460 );
461 } else {
462 // The migration is missing, warn about it
463 warn!(
464 "The database has a migration applied ({version}) that doesn't exist anymore! This should not happen, unless rolling back to an older version of MAS.",
465 version = applied_migration.version
466 );
467 }
468 }
469
470 Ok(available_migrations
471 .values()
472 .copied()
473 .filter(|migration| {
474 !migration.migration_type.is_down_migration()
475 && !applied_migrations.contains_key(&migration.version)
476 })
477 .collect())
478}
479
480// Copied from the sqlx source code, so that we generate the same lock ID
481fn generate_lock_id(database_name: &str) -> i64 {
482 const CRC_IEEE: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
483 // 0x3d32ad9e chosen by fair dice roll
484 0x3d32_ad9e * i64::from(CRC_IEEE.checksum(database_name.as_bytes()))
485}