Moved domain logic out of the database layer, to the user app route.

This commit is contained in:
2026-10-09 14:50:39 +02:00
parent 0517ddd02e
commit 4a84c8330a
11 changed files with 141 additions and 161 deletions
+11 -10
View File
@@ -12,18 +12,19 @@ impl<T> Upsert<T> {
}
}
pub enum GuardedUpsert<T> {
Created(T),
Updated(T),
Rejected,
pub struct Upserted<T> {
pub current: T,
pub previous: Option<T>,
}
impl<T> GuardedUpsert<T> {
pub fn try_map<U, E>(self, f: impl FnOnce(T) -> Result<U, E>) -> Result<GuardedUpsert<U>, E> {
Ok(match self {
Self::Created(value) => GuardedUpsert::Created(f(value)?),
Self::Updated(value) => GuardedUpsert::Updated(f(value)?),
Self::Rejected => GuardedUpsert::Rejected,
impl<T> Upserted<T> {
pub fn try_map<U, E>(self, mut f: impl FnMut(T) -> Result<U, E>) -> Result<Upserted<U>, E> {
Ok(Upserted {
current: f(self.current)?,
previous: match self.previous {
Some(value) => Some(f(value)?),
None => None,
},
})
}
}
+29 -42
View File
@@ -2,7 +2,7 @@ use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, GuardedUpsert, UserAppRow},
dtos::{Upserted, UserAppRow},
};
pub struct Query {
@@ -34,22 +34,13 @@ where
.map_err(DatabaseError::from)
}
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppRow>, DatabaseError>
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
UserAppRow,
r#"
SELECT id, user_id
FROM user_apps
WHERE user_id = $1 AND id = $2
"#,
user_id,
"SELECT id, user_id FROM user_apps WHERE id = $1",
id,
)
.fetch_optional(executor)
@@ -65,7 +56,7 @@ where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_scalar!(
"SELECT user_id FROM user_apps WHERE id = $1 FOR SHARE",
"SELECT user_id FROM user_apps WHERE id = $1 FOR KEY SHARE",
app_id,
)
.fetch_optional(executor)
@@ -76,7 +67,7 @@ where
pub async fn upsert<'e, E>(
executor: E,
app: UserAppRow,
) -> Result<GuardedUpsert<UserAppRow>, DatabaseError>
) -> Result<Upserted<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -85,56 +76,52 @@ where
INSERT INTO user_apps (id, user_id)
VALUES ($1, $2)
ON CONFLICT (id) DO UPDATE SET
id = EXCLUDED.id
WHERE user_apps.user_id = $2
user_id = user_apps.user_id
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.user_id, new_row.user_id) AS "old_user_id!",
new_row.id AS "id!",
new_row.user_id AS "user_id!"
"#,
app.id,
app.user_id,
)
.fetch_optional(executor)
.fetch_one(executor)
.await
.map_err(DatabaseError::from)?;
let Some(row) = row else {
return Ok(GuardedUpsert::Rejected);
};
// `old_id` indicates whether there was a previous row before the upsert, other old fields are
// coalesced with the new row's values in case there was no previous row. This enables static
// typing for the previous row instead of having to check nullability for each old field
// individually.
let previous = row.old_id.map(|id| UserAppRow {
id,
user_id: row.old_user_id,
});
let app = UserAppRow {
id: row.id,
user_id: row.user_id,
};
Ok(if row.old_id.is_some() {
GuardedUpsert::Updated(app)
} else {
GuardedUpsert::Created(app)
Ok(Upserted {
previous,
current: UserAppRow {
id: row.id,
user_id: row.user_id,
},
})
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Delete, DatabaseError>
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!(
"DELETE FROM user_apps WHERE user_id = $1 AND id = $2 RETURNING id",
user_id,
let row = sqlx::query!(
"DELETE FROM user_apps WHERE id = $1 RETURNING id, user_id",
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
Ok(row.map(|row| UserAppRow {
id: row.id,
user_id: row.user_id,
}))
}
+9 -9
View File
@@ -54,12 +54,6 @@ impl IntoResponse for AppError {
Self::Repository(RepositoryError::Decode(error)) => {
tracing::error!(%error, "invalid stored data");
}
Self::Repository(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}) => {
tracing::warn!("user app ownership conflict");
return error_response(StatusCode::CONFLICT, "User app belongs to another user");
}
Self::Repository(RepositoryError::NotFound {
relation: ReferenceRelation::User,
}) => {
@@ -72,12 +66,18 @@ impl IntoResponse for AppError {
tracing::debug!("user app not found");
return error_response(StatusCode::NOT_FOUND, "User app cannot be found");
}
Self::Repository(RepositoryError::OwnershipConflict { relation }) => {
tracing::error!(%relation, "unhandled ownership conflict");
}
Self::Repository(RepositoryError::NotFound { relation }) => {
tracing::error!(%relation, "unhandled not found");
}
Self::Repository(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}) => {
tracing::warn!("user app ownership conflict");
return error_response(StatusCode::CONFLICT, "User app ID is already in use");
}
Self::Repository(RepositoryError::OwnershipConflict { relation }) => {
tracing::error!(%relation, "unhandled ownership conflict");
}
Self::Repository(RepositoryError::ReferenceViolation {
relation: ReferenceRelation::User,
kind: ReferenceViolationKind::Missing,
+3 -3
View File
@@ -21,12 +21,12 @@ pub enum RepositoryError {
#[error(transparent)]
Decode(#[from] DecodeError),
#[error("{relation} is owned by another user")]
OwnershipConflict { relation: ReferenceRelation },
#[error("{relation} cannot be found")]
NotFound { relation: ReferenceRelation },
#[error("{relation} is owned by another user")]
OwnershipConflict { relation: ReferenceRelation },
#[error("reference violation ({kind}: {relation})")]
ReferenceViolation {
relation: ReferenceRelation,
+14
View File
@@ -14,6 +14,20 @@ impl<T> From<database::dtos::Upsert<T>> for Upsert<T> {
}
}
pub struct Upserted<T> {
pub current: T,
pub previous: Option<T>,
}
impl<T> From<database::dtos::Upserted<T>> for Upserted<T> {
fn from(value: database::dtos::Upserted<T>) -> Self {
Self {
current: value.current,
previous: value.previous,
}
}
}
pub enum Delete {
Deleted,
NotFound,
+16 -73
View File
@@ -1,12 +1,8 @@
use uuid::Uuid;
use super::{QueryConversionError, ReferenceRelation, RepositoryError, dtos::Upsert};
use super::{QueryConversionError, RepositoryError, dtos::Upserted};
use crate::{
database::{
Constraint, DatabaseError,
dtos::{GuardedUpsert, UserAppRow},
user_apps as db,
},
database::{Constraint, DatabaseError, dtos::UserAppRow, user_apps as db},
domain::UserApp,
repository::DecodeError,
};
@@ -42,18 +38,11 @@ where
Ok(apps)
}
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserApp>, RepositoryError>
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let app = db::get_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
let app = db::get_by_id(executor, id).await?.map(decode).transpose()?;
Ok(app)
}
@@ -70,27 +59,17 @@ where
Ok(owner)
}
pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result<Upsert<UserApp>, RepositoryError>
pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result<Upserted<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let outcome = db::upsert(executor, encode(app))
let app = db::upsert(executor, encode(app))
.await
.map_err(classify_upsert_error)?;
.map_err(classify_upsert_error)?
.try_map(decode)?
.into();
map_upsert(outcome)
}
fn map_upsert(outcome: GuardedUpsert<UserAppRow>) -> Result<Upsert<UserApp>, RepositoryError> {
Ok(match outcome.try_map(decode)? {
GuardedUpsert::Created(app) => Upsert::Created(app),
GuardedUpsert::Updated(app) => Upsert::Updated(app),
GuardedUpsert::Rejected => {
return Err(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
});
}
})
Ok(app)
}
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
@@ -107,17 +86,16 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
}
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<super::dtos::Delete, RepositoryError>
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let result = db::delete_by_id(executor, user_id, id).await?.into();
let app = db::delete_by_id(executor, id)
.await?
.map(decode)
.transpose()?;
Ok(result)
Ok(app)
}
fn decode(row: UserAppRow) -> Result<UserApp, DecodeError> {
@@ -164,41 +142,6 @@ mod tests {
assert!(matches!(error, RepositoryError::Database(_)));
}
#[test]
fn maps_created_upsert() {
let row = row();
let id = row.id;
let Ok(Upsert::Created(app)) = map_upsert(GuardedUpsert::Created(row)) else {
panic!("expected created upsert");
};
assert_eq!(app.id, id);
}
#[test]
fn maps_updated_upsert() {
let row = row();
let id = row.id;
let Ok(Upsert::Updated(app)) = map_upsert(GuardedUpsert::Updated(row)) else {
panic!("expected updated upsert");
};
assert_eq!(app.id, id);
}
#[test]
fn maps_rejected_upsert_to_ownership_conflict() {
let Err(error) = map_upsert(GuardedUpsert::Rejected) else {
panic!("expected ownership conflict");
};
assert!(matches!(
error,
RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}
));
}
fn row() -> UserAppRow {
UserAppRow {
id: Uuid::new_v4(),
+31 -13
View File
@@ -9,10 +9,7 @@ use super::{
};
use crate::{
error::AppError,
repository::{
self,
dtos::{Delete, Upsert},
},
repository::{self, ReferenceRelation, RepositoryError},
};
pub fn create_router() -> axum::Router<PgPool> {
@@ -60,8 +57,9 @@ async fn get_user_app(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
) -> Result<Json<UserAppResponse>, AppError> {
let app = repository::user_apps::get_by_id(&pool, user_id, app_id)
let app = repository::user_apps::get_by_id(&pool, app_id)
.await?
.filter(|app| app.user_id == user_id)
.ok_or(AppError::NotFound)?;
Ok(Json(app.into()))
@@ -75,14 +73,28 @@ async fn upsert_user_app(
Json(request): Json<UserAppRequest>,
) -> Result<(StatusCode, Json<UserAppResponse>), AppError> {
let app = request.into_domain(user_id, app_id);
let upsert = repository::user_apps::upsert(&pool, app).await?;
let (status, app) = match upsert {
Upsert::Created(app) => (StatusCode::CREATED, app),
Upsert::Updated(app) => (StatusCode::OK, app),
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let upserted = repository::user_apps::upsert(&mut *tx, app).await?;
if upserted
.previous
.as_ref()
.is_some_and(|previous| previous.user_id != user_id)
{
return Err(RepositoryError::OwnershipConflict {
relation: ReferenceRelation::UserApp,
}
.into());
}
tx.commit().await.map_err(RepositoryError::from)?;
let status = if upserted.previous.is_some() {
StatusCode::OK
} else {
StatusCode::CREATED
};
Ok((status, Json(app.into())))
Ok((status, Json(upserted.current.into())))
}
#[axum::debug_handler]
@@ -91,8 +103,14 @@ async fn delete_user_app(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
) -> Result<StatusCode, AppError> {
match repository::user_apps::delete_by_id(&pool, user_id, app_id).await? {
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
Delete::NotFound => Err(AppError::NotFound),
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
if repository::user_apps::delete_by_id(&mut *tx, app_id)
.await?
.is_none_or(|user_app| user_app.user_id != user_id)
{
return Err(AppError::NotFound);
}
tx.commit().await.map_err(RepositoryError::from)?;
Ok(StatusCode::NO_CONTENT)
}