From 5c83f4350c8e54abfe2d73e511103e327b0fb3c6 Mon Sep 17 00:00:00 2001 From: Rogier Reerink Date: Fri, 9 Oct 2026 14:22:25 +0200 Subject: [PATCH] Move domain logic out of the database layer, to the user app route. --- ...5d7ddc4e266cbbc7695f796990f78c07e61d.json} | 17 +++- ...096ec1f7279f90d37c3c11f6b4dc71708db9.json} | 13 +++- server/src/database/dtos/results.rs | 21 ++--- server/src/database/user_apps.rs | 56 +++++++------ server/src/error.rs | 18 ++--- server/src/repository.rs | 6 +- server/src/repository/dtos/results.rs | 14 ++++ server/src/repository/user_apps.rs | 78 ++++--------------- server/src/routes/user_apps.rs | 41 +++++++--- 9 files changed, 130 insertions(+), 134 deletions(-) rename server/.sqlx/{query-38166013a2b30661d0666a7b6629904cf9c5e71ca6a8dee4ed3ebe7afec9383e.json => query-40214db76bbef12fdb3acb184b115d7ddc4e266cbbc7695f796990f78c07e61d.json} (50%) rename server/.sqlx/{query-977a6afaf7511915973fd20ab3a3fb03aeda84d0d460c9db1b5b1e7025493879.json => query-bf2a5b137b07bc056060d1e2d55f096ec1f7279f90d37c3c11f6b4dc71708db9.json} (65%) diff --git a/server/.sqlx/query-38166013a2b30661d0666a7b6629904cf9c5e71ca6a8dee4ed3ebe7afec9383e.json b/server/.sqlx/query-40214db76bbef12fdb3acb184b115d7ddc4e266cbbc7695f796990f78c07e61d.json similarity index 50% rename from server/.sqlx/query-38166013a2b30661d0666a7b6629904cf9c5e71ca6a8dee4ed3ebe7afec9383e.json rename to server/.sqlx/query-40214db76bbef12fdb3acb184b115d7ddc4e266cbbc7695f796990f78c07e61d.json index d0b574c..5992e87 100644 --- a/server/.sqlx/query-38166013a2b30661d0666a7b6629904cf9c5e71ca6a8dee4ed3ebe7afec9383e.json +++ b/server/.sqlx/query-40214db76bbef12fdb3acb184b115d7ddc4e266cbbc7695f796990f78c07e61d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM user_apps WHERE user_id = $1 AND id = $2 RETURNING id", + "query": "DELETE FROM user_apps WHERE id = $1 RETURNING id, user_id", "describe": { "columns": [ { @@ -13,17 +13,28 @@ "name": "id" } } + }, + { + "ordinal": 1, + "name": "user_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "user_apps", + "name": "user_id" + } + } } ], "parameters": { "Left": [ - "Uuid", "Uuid" ] }, "nullable": [ + false, false ] }, - "hash": "38166013a2b30661d0666a7b6629904cf9c5e71ca6a8dee4ed3ebe7afec9383e" + "hash": "40214db76bbef12fdb3acb184b115d7ddc4e266cbbc7695f796990f78c07e61d" } diff --git a/server/.sqlx/query-977a6afaf7511915973fd20ab3a3fb03aeda84d0d460c9db1b5b1e7025493879.json b/server/.sqlx/query-bf2a5b137b07bc056060d1e2d55f096ec1f7279f90d37c3c11f6b4dc71708db9.json similarity index 65% rename from server/.sqlx/query-977a6afaf7511915973fd20ab3a3fb03aeda84d0d460c9db1b5b1e7025493879.json rename to server/.sqlx/query-bf2a5b137b07bc056060d1e2d55f096ec1f7279f90d37c3c11f6b4dc71708db9.json index 6bc3d55..3f5f79b 100644 --- a/server/.sqlx/query-977a6afaf7511915973fd20ab3a3fb03aeda84d0d460c9db1b5b1e7025493879.json +++ b/server/.sqlx/query-bf2a5b137b07bc056060d1e2d55f096ec1f7279f90d37c3c11f6b4dc71708db9.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n INSERT INTO user_apps (id, user_id)\n VALUES ($1, $2)\n ON CONFLICT (id) DO UPDATE SET\n id = EXCLUDED.id\n WHERE user_apps.user_id = $2\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n new_row.id AS \"id!\",\n new_row.user_id AS \"user_id!\"\n ", + "query": "\n INSERT INTO user_apps (id, user_id)\n VALUES ($1, $2)\n ON CONFLICT (id) DO UPDATE SET\n user_id = user_apps.user_id\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n COALESCE(old_row.user_id, new_row.user_id) AS \"old_user_id!\",\n new_row.id AS \"id!\",\n new_row.user_id AS \"user_id!\"\n ", "describe": { "columns": [ { @@ -16,6 +16,12 @@ }, { "ordinal": 1, + "name": "old_user_id!", + "type_info": "Uuid", + "origin": "Expression" + }, + { + "ordinal": 2, "name": "id!", "type_info": "Uuid", "origin": { @@ -26,7 +32,7 @@ } }, { - "ordinal": 2, + "ordinal": 3, "name": "user_id!", "type_info": "Uuid", "origin": { @@ -45,9 +51,10 @@ }, "nullable": [ false, + null, false, false ] }, - "hash": "977a6afaf7511915973fd20ab3a3fb03aeda84d0d460c9db1b5b1e7025493879" + "hash": "bf2a5b137b07bc056060d1e2d55f096ec1f7279f90d37c3c11f6b4dc71708db9" } diff --git a/server/src/database/dtos/results.rs b/server/src/database/dtos/results.rs index 244c318..0a2800d 100644 --- a/server/src/database/dtos/results.rs +++ b/server/src/database/dtos/results.rs @@ -12,18 +12,19 @@ impl Upsert { } } -pub enum GuardedUpsert { - Created(T), - Updated(T), - Rejected, +pub struct Upserted { + pub current: T, + pub previous: Option, } -impl GuardedUpsert { - pub fn try_map(self, f: impl FnOnce(T) -> Result) -> Result, E> { - Ok(match self { - Self::Created(value) => GuardedUpsert::Created(f(value)?), - Self::Updated(value) => GuardedUpsert::Updated(f(value)?), - Self::Rejected => GuardedUpsert::Rejected, +impl Upserted { + pub fn try_map(self, mut f: impl FnMut(T) -> Result) -> Result, E> { + Ok(Upserted { + current: f(self.current)?, + previous: match self.previous { + Some(value) => Some(f(value)?), + None => None, + }, }) } } diff --git a/server/src/database/user_apps.rs b/server/src/database/user_apps.rs index 80286d5..2bbc2f3 100644 --- a/server/src/database/user_apps.rs +++ b/server/src/database/user_apps.rs @@ -2,7 +2,7 @@ use uuid::Uuid; use super::{ DatabaseError, - dtos::{Delete, GuardedUpsert, UserAppRow}, + dtos::{Upserted, UserAppRow}, }; pub struct Query { @@ -76,7 +76,7 @@ where pub async fn upsert<'e, E>( executor: E, app: UserAppRow, -) -> Result, DatabaseError> +) -> Result, DatabaseError> where E: sqlx::Executor<'e, Database = sqlx::Postgres>, { @@ -85,56 +85,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 +pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result, 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, + })) } diff --git a/server/src/error.rs b/server/src/error.rs index 086eac7..af02b34 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -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, diff --git a/server/src/repository.rs b/server/src/repository.rs index 760dd33..7c56399 100644 --- a/server/src/repository.rs +++ b/server/src/repository.rs @@ -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, diff --git a/server/src/repository/dtos/results.rs b/server/src/repository/dtos/results.rs index 907519a..b949d03 100644 --- a/server/src/repository/dtos/results.rs +++ b/server/src/repository/dtos/results.rs @@ -14,6 +14,20 @@ impl From> for Upsert { } } +pub struct Upserted { + pub current: T, + pub previous: Option, +} + +impl From> for Upserted { + fn from(value: database::dtos::Upserted) -> Self { + Self { + current: value.current, + previous: value.previous, + } + } +} + pub enum Delete { Deleted, NotFound, diff --git a/server/src/repository/user_apps.rs b/server/src/repository/user_apps.rs index 0ad3391..ed1774e 100644 --- a/server/src/repository/user_apps.rs +++ b/server/src/repository/user_apps.rs @@ -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, }; @@ -70,27 +66,17 @@ where Ok(owner) } -pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result, RepositoryError> +pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result, 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) -> Result, 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 +93,16 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError { } } -pub async fn delete_by_id<'e, E>( - executor: E, - user_id: Uuid, - id: Uuid, -) -> Result +pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result, 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 { @@ -164,41 +149,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(), diff --git a/server/src/routes/user_apps.rs b/server/src/routes/user_apps.rs index 214cc45..eb2e29a 100644 --- a/server/src/routes/user_apps.rs +++ b/server/src/routes/user_apps.rs @@ -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 { @@ -75,14 +72,28 @@ async fn upsert_user_app( Json(request): Json, ) -> Result<(StatusCode, Json), 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 +102,14 @@ async fn delete_user_app( State(pool): State, Path((user_id, app_id)): Path<(Uuid, Uuid)>, ) -> Result { - 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) }