diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index 2f6d1bf67..272a912a6 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -234,6 +234,38 @@ impl Database { .map_err(Into::into) } + /// Opens a dedicated connection with the pool's settings and takes `key`'s + /// session lock, waiting with no lock limit for as long as `statement` lets + /// one statement run. The connection keeps `statement` as its statement + /// limit and gets the pool's lock limit back. + /// + /// # Errors + /// + /// Returns [`DatabaseError::Timeout`] if connecting takes too long, + /// [`DatabaseError::Cancelled`] if the lock is still held when `statement` + /// ends the wait, or another [`DatabaseError`] if a query fails. + pub(crate) async fn lock_dedicated( + &self, + key: LockKey, + statement: Duration, + ) -> Result { + let mut connection = self.connect_dedicated(&self.pool.connect_options()).await?; + for limit in [ + Limit::STATEMENT.at(statement), + Limit::LOCK.at(Duration::ZERO), + ] { + limit.set(Scope::Session).fetch_one(&mut connection).await?; + } + sqlx::query!("SELECT pg_advisory_lock($1)", key.id()) + .fetch_one(&mut connection) + .await?; + Limit::LOCK + .set(Scope::Session) + .fetch_one(&mut connection) + .await?; + Ok(connection) + } + /// Checks availability with a bounded, non-sensitive query. /// /// # Errors @@ -298,19 +330,8 @@ impl Database { /// wait past its limit, or the applied history differs from the embedded /// migrations. pub async fn run_migrations(&self) -> Result<(), DatabaseError> { - let mut connection = self.connect_dedicated(&self.pool.connect_options()).await?; - for limit in [ - Limit::STATEMENT.at(MIGRATION_STATEMENT_TIMEOUT), - Limit::LOCK.at(Duration::ZERO), - ] { - limit.set(Scope::Session).fetch_one(&mut connection).await?; - } - sqlx::query!("SELECT pg_advisory_lock($1)", LockKey::Migrations.id()) - .fetch_one(&mut connection) - .await?; - Limit::LOCK - .set(Scope::Session) - .fetch_one(&mut connection) + let mut connection = self + .lock_dedicated(LockKey::Migrations, MIGRATION_STATEMENT_TIMEOUT) .await?; MIGRATOR .run(&mut connection) diff --git a/crates/database/src/exclusive/mod.rs b/crates/database/src/exclusive/mod.rs index 31da764ed..82d76cee2 100644 --- a/crates/database/src/exclusive/mod.rs +++ b/crates/database/src/exclusive/mod.rs @@ -1,7 +1,15 @@ //! Advisory locks that let one replica at a time run a job. +#[cfg(any(test, feature = "test-util"))] +use crate::connection::{Limit, Scope}; use crate::{Database, DatabaseError, DatabaseTransaction}; use sqlx::{Connection, PgConnection}; +#[cfg(any(test, feature = "test-util"))] +use std::time::Duration; + +/// Longest [`Database::exclusive`] waits for a lock another session holds. +#[cfg(any(test, feature = "test-util"))] +const EXCLUSIVE_WAIT: Duration = Duration::from_secs(30); /// Advisory lock keys: session-level ones, one per exclusive job, and /// transaction-level ones that serialize a kind of change. The values are stable @@ -93,6 +101,27 @@ impl Database { Ok(None) } } + + /// Opens a connection with the pool's settings and takes `key`'s lock, + /// waiting up to 30 seconds while another session holds it, so a + /// test takes its turn with the job or test that holds it. The connection + /// then has the pool's limits again. + /// + /// # Errors + /// + /// Returns [`DatabaseError::Timeout`] if connecting takes longer than the + /// pool's acquire timeout, [`DatabaseError::Cancelled`] if the lock is + /// still held after 30 seconds, or another [`DatabaseError`] if a query + /// fails. + #[cfg(any(test, feature = "test-util"))] + pub async fn exclusive(&self, key: LockKey) -> Result { + let mut connection = self.lock_dedicated(key, EXCLUSIVE_WAIT).await?; + Limit::STATEMENT + .set(Scope::Session) + .fetch_one(&mut connection) + .await?; + Ok(ExclusiveConnection { connection, key }) + } } impl ExclusiveConnection { diff --git a/crates/database/src/exclusive/tests.rs b/crates/database/src/exclusive/tests.rs index eefd506ec..6075da16d 100644 --- a/crates/database/src/exclusive/tests.rs +++ b/crates/database/src/exclusive/tests.rs @@ -22,16 +22,14 @@ async fn locks_exclude_other_sessions_until_their_connection_ends() { }); job.abort(); assert!(job.await.expect_err("cancelled job").is_cancelled()); - let freed = tokio::time::timeout(Duration::from_secs(5), async { - loop { - if let Some(holder) = lock().await.expect("lock") { - break holder; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) + // PostgreSQL grants the waiting lock once the dropped holder's session ends. + let freed = tokio::time::timeout( + Duration::from_secs(5), + database.exclusive(LockKey::LockTest), + ) .await - .expect("dropping the holder frees the lock"); + .expect("dropping the holder frees the lock") + .expect("lock"); freed.release().await.expect("release"); } diff --git a/crates/database/src/repositories/deliveries/tests.rs b/crates/database/src/repositories/deliveries/tests.rs index b12fcfb93..67afd89f7 100644 --- a/crates/database/src/repositories/deliveries/tests.rs +++ b/crates/database/src/repositories/deliveries/tests.rs @@ -126,6 +126,15 @@ async fn finish( .await } +/// Ends the lease of delivery `id`'s attempt now, as if it ran out. +async fn expire_lease(pool: &PgPool, id: DeliveryId) { + sqlx::query("UPDATE deliveries SET leased_until = clock_timestamp() WHERE id = $1") + .bind(id.as_uuid()) + .execute(pool) + .await + .expect("expire the lease"); +} + /// A permanent failure. fn failed() -> DeliveryOutcome { DeliveryOutcome::Failed { @@ -228,10 +237,8 @@ async fn an_expired_lease_is_claimed_again_and_the_stale_outcome_discarded() { clear::(&pool).await; let id = insert::(&pool).await; - let stale = claim::(&pool, Duration::from_millis(1)) - .await - .expect("first claim"); - tokio::time::sleep(Duration::from_millis(20)).await; + let stale = claim::(&pool, LEASE).await.expect("first claim"); + expire_lease(&pool, id).await; let current = claim::(&pool, LEASE) .await .expect("the expired lease is claimed again"); @@ -315,8 +322,7 @@ async fn operators_retry_and_cancel_deliveries() { let pool = Database::test_pool().await; clear::(&pool).await; let id = insert::(&pool).await; - let lease = Duration::from_millis(300); - let next = async || claim::(&pool, lease).await; + let next = async || claim::(&pool, LEASE).await; let repository = || DeliveryRepository::from_pool(&pool); let attempt = next().await.expect("first attempt"); @@ -336,7 +342,7 @@ async fn operators_retry_and_cancel_deliveries() { next().await.is_none(), "the cancelled attempt's lease holds" ); - tokio::time::sleep(lease).await; + expire_lease(&pool, id).await; let retried = next().await.expect("retried"); assert_eq!((retried.id, retried.attempts), (id, 2)); assert!( diff --git a/crates/database/src/repositories/tokens/tests.rs b/crates/database/src/repositories/tokens/tests.rs index c65bb2d71..beb5411ff 100644 --- a/crates/database/src/repositories/tokens/tests.rs +++ b/crates/database/src/repositories/tokens/tests.rs @@ -700,16 +700,14 @@ async fn removal_expires_codes_an_earlier_exchange_still_sees_live() { let pool = Database::test_pool().await; let client = client(&pool).await; let grant = Grant::new(&pool, &client).await; - sqlx::query( - "UPDATE authorization_codes SET expires_at = now() + interval '1 second' WHERE id = $1", - ) - .bind(grant.code.as_uuid()) - .execute(&pool) - .await - .expect("expire soon"); - // `now()` is fixed when a transaction begins. + // `now()` is fixed when a transaction begins, so the code expires after the + // exchange began and before the removal does. let mut exchange = DatabaseTransaction::new(pool.begin().await.expect("exchange")); - tokio::time::sleep(Wait::from_millis(1200)).await; + sqlx::query("UPDATE authorization_codes SET expires_at = clock_timestamp() WHERE id = $1") + .bind(grant.code.as_uuid()) + .execute(&pool) + .await + .expect("expire"); let mut removal = DatabaseTransaction::new(pool.begin().await.expect("removal")); removal .oidc() diff --git a/crates/database/tests/recoveries.rs b/crates/database/tests/recoveries.rs index df9ab0cc7..f3d22e7a1 100644 --- a/crates/database/tests/recoveries.rs +++ b/crates/database/tests/recoveries.rs @@ -272,7 +272,7 @@ async fn a_link_that_expires_while_finishing_does_not_complete() { let owner = Owner::new().await; let db = &owner.db; let user = db.users().insert_named("recover").await; - let id = start(db, user, Duration::milliseconds(500)).await; + let id = start(db, user, Duration::hours(1)).await; let mut tx = db.begin().await.expect("transaction"); tx.users() @@ -280,7 +280,7 @@ async fn a_link_that_expires_while_finishing_does_not_complete() { .await .expect("lock") .expect("user"); - tokio::time::sleep(std::time::Duration::from_millis(700)).await; + owner.expire(id).await; let completed = tx .recoveries() .complete(user, id, PasskeyId::new(), PROBATION)