Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 34 additions & 13 deletions crates/database/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PgConnection, DatabaseError> {
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
Expand Down Expand Up @@ -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)
Expand Down
29 changes: 29 additions & 0 deletions crates/database/src/exclusive/mod.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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<ExclusiveConnection, DatabaseError> {
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 {
Expand Down
16 changes: 7 additions & 9 deletions crates/database/src/exclusive/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

Expand Down
20 changes: 13 additions & 7 deletions crates/database/src/repositories/deliveries/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,15 @@ async fn finish<C: Channel>(
.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 {
Expand Down Expand Up @@ -228,10 +237,8 @@ async fn an_expired_lease_is_claimed_again_and_the_stale_outcome_discarded() {
clear::<Leased>(&pool).await;
let id = insert::<Leased>(&pool).await;

let stale = claim::<Leased>(&pool, Duration::from_millis(1))
.await
.expect("first claim");
tokio::time::sleep(Duration::from_millis(20)).await;
let stale = claim::<Leased>(&pool, LEASE).await.expect("first claim");
expire_lease(&pool, id).await;
let current = claim::<Leased>(&pool, LEASE)
.await
.expect("the expired lease is claimed again");
Expand Down Expand Up @@ -315,8 +322,7 @@ async fn operators_retry_and_cancel_deliveries() {
let pool = Database::test_pool().await;
clear::<Operated>(&pool).await;
let id = insert::<Operated>(&pool).await;
let lease = Duration::from_millis(300);
let next = async || claim::<Operated>(&pool, lease).await;
let next = async || claim::<Operated>(&pool, LEASE).await;
let repository = || DeliveryRepository::from_pool(&pool);

let attempt = next().await.expect("first attempt");
Expand All @@ -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!(
Expand Down
16 changes: 7 additions & 9 deletions crates/database/src/repositories/tokens/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions crates/database/tests/recoveries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,15 +272,15 @@ 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()
.find_active_by_id_for_update(user)
.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)
Expand Down