Skip to content
Draft
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
3 changes: 2 additions & 1 deletion apps/auth-service/src/oidc/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ impl OAuthError {
| DatabaseError::Cancelled(_)
| DatabaseError::LockUnavailable(_)
| DatabaseError::InvalidStoredData { .. }
| DatabaseError::Operation(_) => Self::Database(error),
| DatabaseError::Operation(_)
| DatabaseError::OutsideTransaction => Self::Database(error),
}
}

Expand Down
3 changes: 2 additions & 1 deletion apps/auth-service/src/passkey/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,8 @@ impl PasskeyApplication {
| DatabaseError::Cancelled(_)
| DatabaseError::LockUnavailable(_)
| DatabaseError::InvalidStoredData { .. }
| DatabaseError::Operation(_) => error.into(),
| DatabaseError::Operation(_)
| DatabaseError::OutsideTransaction => error.into(),
})?;
tx.record(
context,
Expand Down
3 changes: 2 additions & 1 deletion apps/auth-service/src/security/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ impl From<DatabaseError> for ApiError {
| DatabaseError::Cancelled(_)
| DatabaseError::LockUnavailable(_)
| DatabaseError::InvalidStoredData { .. }
| DatabaseError::Operation(_)) => Self::internal(error),
| DatabaseError::Operation(_)
| DatabaseError::OutsideTransaction) => Self::internal(error),
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions crates/database/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ pub enum DatabaseError {
/// Any other driver, query, migration or event serialization failure.
#[error("database operation failed")]
Operation(#[source] Source),
/// An operation whose locks must last until its transaction ends, such as a
/// transaction-scoped advisory lock, ran outside a transaction, where they would
/// end with their statement. It is refused before any query runs.
#[error("the operation's locks need a transaction, and none is open")]
OutsideTransaction,
}

/// Why a stored value did not decode, without the value: a decoder's message can
Expand Down
4 changes: 4 additions & 0 deletions crates/database/src/exclusive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ pub enum LockKey {
/// expects its key free; no release takes it.
#[cfg(any(test, feature = "test-util"))]
TransactionTest = -4,
/// The test that transaction-scoped locks refuse an exclusive connection;
/// no release takes it.
#[cfg(any(test, feature = "test-util"))]
GuardTest = -5,
}

impl LockKey {
Expand Down
9 changes: 3 additions & 6 deletions crates/database/src/repositories/alerts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,10 @@ impl AlertRepository<'_> {
///
/// # Errors
///
/// Returns [`DatabaseError`] if a query fails or its payload does not decode.
/// Returns [`DatabaseError::OutsideTransaction`] outside a transaction, or
/// another [`DatabaseError`] if a query fails or its payload does not decode.
pub async fn current(&mut self, kind: AlertKind) -> Result<Option<StoredAlert>, DatabaseError> {
run!(
self,
execute,
sqlx::query!("SELECT pg_advisory_xact_lock($1)", LockKey::Alerts.id())
)?;
self.executor.lock(LockKey::Alerts).await?;
run!(
self,
fetch_optional,
Expand Down
2 changes: 1 addition & 1 deletion crates/database/src/repositories/emails/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use sourceorigin_common::{EmailId, UserId};
async fn verified_email_updates_preserve_and_release_ownership() {
let pool = Database::test_pool().await;
let mut tx = pool.begin().await.expect("transaction");
let mut accounts = UserRepository::from_connection(&mut tx);
let mut accounts = UserRepository::from_transaction(&mut tx);
let users = [
accounts.insert_named("email").await,
accounts.insert_named("email").await,
Expand Down
105 changes: 81 additions & 24 deletions crates/database/src/repositories/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,28 @@
//! that checked queries decode into. Each submodule owns one repository together with the
//! records it accepts and returns.

use crate::{Database, DatabaseTransaction, ExclusiveConnection};
use crate::{Database, DatabaseError, DatabaseTransaction, ExclusiveConnection, LockKey};
use serde::de::DeserializeOwned;
use serde_json::Value;
use sourceorigin_common::events::DomainEvent;
use sqlx::{
Decode, PgConnection, PgPool, Postgres, Type,
Decode, PgConnection, PgPool, Postgres, Transaction, Type,
error::BoxDynError,
postgres::{PgTypeInfo, PgValueRef},
types::Json,
};

/// Where a repository runs its queries: directly on the pool, or on the
/// connection of an open transaction.
/// Where a repository runs its queries: directly on the pool, on the connection of
/// an open transaction, or on an [`ExclusiveConnection`]. Only a transaction keeps
/// locks past the statement that takes them, so [`Self::lock`] tells them apart.
pub(crate) enum RepositoryExecutor<'a> {
/// Each operation borrows a connection from the shared pool.
Pool(&'a PgPool),
/// Every operation participates in one caller-owned transaction.
Connection(&'a mut PgConnection),
Transaction(&'a mut PgConnection),
/// Every operation runs on a locked [`ExclusiveConnection`], each statement in
/// a transaction of its own.
Exclusive(&'a mut PgConnection),
}

/// Declares each repository handle and its accessor on [`Database`],
Expand All @@ -47,9 +51,14 @@ macro_rules! repositories {
Self { executor: RepositoryExecutor::Pool(pool) }
}

/// Binds this handle to a transaction connection for atomic operations.
pub(crate) fn from_connection(connection: &'a mut PgConnection) -> Self {
Self { executor: RepositoryExecutor::Connection(connection) }
/// Binds this handle to a transaction for atomic operations.
pub(crate) fn from_transaction(transaction: &'a mut Transaction<'_, Postgres>) -> Self {
Self { executor: RepositoryExecutor::Transaction(&mut **transaction) }
}

/// Binds this handle to a locked [`ExclusiveConnection`]'s connection.
pub(crate) fn from_exclusive(connection: &'a mut PgConnection) -> Self {
Self { executor: RepositoryExecutor::Exclusive(connection) }
}
}
)*
Expand All @@ -69,7 +78,7 @@ macro_rules! repositories {
$(
#[doc = concat!("Returns a [`", stringify!($name), "`] bound to this transaction.")]
pub fn $accessor(&mut self) -> $name<'_> {
$name::from_connection(&mut self.inner)
$name::from_transaction(&mut self.inner)
}
)*
}
Expand All @@ -80,7 +89,7 @@ macro_rules! repositories {
"Returns a [`", stringify!($name), "`] bound to the locked connection."
)]
pub fn $accessor(&mut self) -> $name<'_> {
$name::from_connection(&mut self.connection)
$name::from_exclusive(&mut self.connection)
}
)*
}
Expand Down Expand Up @@ -212,25 +221,17 @@ impl KindProbe {
/// whether it changed exactly one row, and `required` returns `()`, or
/// [`DatabaseError::NotFound`](crate::DatabaseError::NotFound) if it changed none. A macro
/// rather than a method because `&PgPool` and `&mut PgConnection` are different
/// executor types.
/// executor types. `run!(@on executor, ...)` runs on a [`RepositoryExecutor`] itself.
macro_rules! run {
($self:expr, changed_one, $query:expr) => {
run!($self, execute, $query).map(|done| done.rows_affected() == 1)
};
($self:expr, required, $query:expr) => {
run!($self, execute, $query).and_then(|done| match done.rows_affected() {
0 => Err(crate::DatabaseError::NotFound),
_ => Ok(()),
})
};
($self:expr, $method:ident, $query:expr) => {{
(@on $executor:expr, $method:ident, $query:expr) => {{
let query = $query;
let span = RepositoryExecutor::span(sqlx::Execute::sql(&query));
let result = tracing::Instrument::instrument(
async {
match &mut $self.executor {
match &mut $executor {
RepositoryExecutor::Pool(pool) => query.$method(*pool).await,
RepositoryExecutor::Connection(connection) => {
RepositoryExecutor::Transaction(connection)
| RepositoryExecutor::Exclusive(connection) => {
query.$method(&mut **connection).await
}
}
Expand All @@ -241,6 +242,18 @@ macro_rules! run {
.map_err(Into::<DatabaseError>::into);
RepositoryExecutor::finish(&span, result)
}};
($self:expr, changed_one, $query:expr) => {
run!($self, execute, $query).map(|done| done.rows_affected() == 1)
};
($self:expr, required, $query:expr) => {
run!($self, execute, $query).and_then(|done| match done.rows_affected() {
0 => Err(crate::DatabaseError::NotFound),
_ => Ok(()),
})
};
($self:expr, $method:ident, $query:expr) => {
run!(@on $self.executor, $method, $query)
};
}

/// A checked `sqlx::query_as!` returning `$record`s, with their `$columns`
Expand Down Expand Up @@ -286,6 +299,50 @@ macro_rules! in_safe_order {
}

impl RepositoryExecutor<'_> {
/// Waits for `key`'s transaction-scoped advisory lock, held until the
/// transaction ends.
///
/// # Errors
///
/// Returns [`DatabaseError::OutsideTransaction`] outside a transaction, where
/// the lock would end with its statement, or another [`DatabaseError`] if the
/// query fails.
async fn lock(&mut self, key: LockKey) -> Result<(), DatabaseError> {
self.require_transaction()?;
run!(@on *self, execute, sqlx::query!("SELECT pg_advisory_xact_lock($1)", key.id()))?;
Ok(())
}

/// Takes the lock of [`Self::lock`] if no other transaction holds it, and
/// returns whether it did.
///
/// # Errors
///
/// As [`Self::lock`].
async fn try_lock(&mut self, key: LockKey) -> Result<bool, DatabaseError> {
self.require_transaction()?;
run!(
@on *self,
fetch_one,
sqlx::query_scalar!(r#"SELECT pg_try_advisory_xact_lock($1) AS "locked!""#, key.id())
)
}

/// Refuses work whose locks must last until its transaction ends, such as a
/// transaction-scoped advisory lock or `FOR UPDATE`, outside a transaction,
/// where they would end with the statement that takes them.
///
/// # Errors
///
/// Returns [`DatabaseError::OutsideTransaction`] on the pool or an
/// [`ExclusiveConnection`].
fn require_transaction(&self) -> Result<(), DatabaseError> {
match self {
Self::Transaction(_) => Ok(()),
Self::Pool(_) | Self::Exclusive(_) => Err(DatabaseError::OutsideTransaction),
}
}

/// A client span for one query, recording its parameterized `sql` as
/// `db.query.text`, never its bind values. A query outside any trace, such as an
/// idle delivery worker's poll, gets none: each would be a trace of its own.
Expand Down Expand Up @@ -459,7 +516,7 @@ pub(crate) mod security;
pub(crate) mod sessions;
/// Signing keys, their lifecycle and its lock.
pub(crate) mod signing_keys;
/// Focused tests for the column types shared by every repository.
/// Focused tests for the column types and the lock guard shared by every repository.
#[cfg(test)]
mod tests;
/// Refresh-token grants, their redemption and replay revocation.
Expand Down
13 changes: 3 additions & 10 deletions crates/database/src/repositories/oidc/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -777,17 +777,10 @@ impl OidcRepository<'_> {
///
/// # Errors
///
/// Returns [`DatabaseError`] if the query fails.
/// Returns [`DatabaseError::OutsideTransaction`] outside a transaction, or
/// another [`DatabaseError`] if the query fails.
pub async fn lock_related_origins(&mut self) -> Result<(), DatabaseError> {
run!(
self,
execute,
sqlx::query!(
"SELECT pg_advisory_xact_lock($1)",
LockKey::RelatedOrigins.id()
)
)?;
Ok(())
self.executor.lock(LockKey::RelatedOrigins).await
}

/// Every approved related origin, by origin.
Expand Down
39 changes: 7 additions & 32 deletions crates/database/src/repositories/signing_keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,23 +74,17 @@ impl SigningKeyRepository<'_> {
///
/// # Errors
///
/// Returns [`DatabaseError`] if the query fails, or this repository is not
/// bound to a transaction, where the lock would end at once.
/// Returns [`DatabaseError::OutsideTransaction`] if this repository is not
/// bound to a transaction, where the lock would end at once, or another
/// [`DatabaseError`] if a query fails.
pub async fn lock(&mut self) -> Result<(), DatabaseError> {
Self::require_transaction(&self.executor)?;
self.executor.require_transaction()?;
run!(
self,
fetch_one,
Limit::LOCK.at(Duration::ZERO).set(Scope::Transaction)
)?;
run!(
self,
execute,
sqlx::query!(
"SELECT pg_advisory_xact_lock($1)",
LockKey::SigningKeys.id()
)
)?;
self.executor.lock(LockKey::SigningKeys).await?;
run!(self, fetch_one, Limit::LOCK.set(Scope::Transaction))?;
Ok(())
}
Expand All @@ -99,28 +93,9 @@ impl SigningKeyRepository<'_> {
///
/// # Errors
///
/// Returns [`DatabaseError`] if the query fails, or this repository is not
/// bound to a transaction.
/// As [`Self::lock`].
pub async fn try_lock(&mut self) -> Result<bool, DatabaseError> {
Self::require_transaction(&self.executor)?;
run!(
self,
fetch_one,
sqlx::query_scalar!(
r#"SELECT pg_try_advisory_xact_lock($1) AS "locked!""#,
LockKey::SigningKeys.id()
)
)
}

/// Refuses to take a transaction-level lock outside a transaction.
fn require_transaction(executor: &RepositoryExecutor<'_>) -> Result<(), DatabaseError> {
match executor {
RepositoryExecutor::Pool(_) => Err(DatabaseError::Operation(
"the signing key lock requires a transaction".into(),
)),
RepositoryExecutor::Connection(_) => Ok(()),
}
self.executor.try_lock(LockKey::SigningKeys).await
}

/// Lists every key, oldest first.
Expand Down
5 changes: 4 additions & 1 deletion crates/database/src/repositories/signing_keys/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ async fn the_lock_excludes_and_one_key_per_type_signs() {
assert!(!other.signing_keys().try_lock().await.expect("try lock"));
other.rollback().await.expect("rollback");
assert!(
database.signing_keys().lock().await.is_err(),
matches!(
database.signing_keys().lock().await,
Err(DatabaseError::OutsideTransaction)
),
"the pool has no transaction"
);

Expand Down
33 changes: 31 additions & 2 deletions crates/database/src/repositories/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Stored values that their Rust types reject surface as invalid data.
//! Stored values that their Rust types reject surface as invalid data, and
//! transaction-scoped locks refuse to run outside a transaction.
use crate::{
Database, DatabaseError,
Database, DatabaseError, LockKey,
repositories::{SessionRepository, UserRepository},
};
use sourceorigin_common::{Handle, SessionId, UserId};
Expand Down Expand Up @@ -53,3 +54,31 @@ async fn undecodable_columns_are_invalid_stored_data() {
Err(DatabaseError::InvalidStoredData { .. })
));
}

/// A transaction-scoped advisory lock taken on the pool or an exclusive connection
/// would end with its statement, so both refuse it before running any query; a
/// transaction takes it.
#[tokio::test]
#[ignore = "requires a disposable TEST_DATABASE_URL"]
async fn transaction_scoped_locks_need_a_transaction() {
let database = Database::test().await;
assert!(matches!(
database.oidc().lock_related_origins().await,
Err(DatabaseError::OutsideTransaction)
));

let mut tx = database.begin().await.expect("transaction");
tx.oidc().lock_related_origins().await.expect("lock");
tx.rollback().await.expect("rollback");

let mut exclusive = database
.try_exclusive(LockKey::GuardTest)
.await
.expect("lock")
.expect("a free lock");
assert!(matches!(
exclusive.oidc().lock_related_origins().await,
Err(DatabaseError::OutsideTransaction)
));
exclusive.release().await.expect("release");
}
Loading