refactor(domain): algebraic NotificationKind — invalid states now unrepresentable

This commit is contained in:
2026-05-15 13:53:53 +02:00
parent 189901b778
commit 5a64dd361c
4 changed files with 170 additions and 98 deletions

View File

@@ -0,0 +1 @@
ALTER TABLE notifications RENAME COLUMN "type" TO notification_type;

View File

@@ -2,33 +2,11 @@ use crate::db_error::IntoDbResult;
use async_trait::async_trait; use async_trait::async_trait;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
fn notif_type_from_str(s: &str) -> domain::models::notification::NotificationType {
use domain::models::notification::NotificationType;
match s {
"like" => NotificationType::Like,
"boost" => NotificationType::Boost,
"follow" => NotificationType::Follow,
"mention" => NotificationType::Mention,
_ => NotificationType::Reply,
}
}
fn notif_type_as_str(t: &domain::models::notification::NotificationType) -> &'static str {
use domain::models::notification::NotificationType;
match t {
NotificationType::Like => "like",
NotificationType::Boost => "boost",
NotificationType::Follow => "follow",
NotificationType::Mention => "mention",
NotificationType::Reply => "reply",
}
}
use domain::{ use domain::{
errors::DomainError, errors::DomainError,
models::{ models::{
feed::{PageParams, Paginated}, feed::{PageParams, Paginated},
notification::Notification, notification::{Notification, NotificationKind},
}, },
ports::NotificationRepository, ports::NotificationRepository,
value_objects::{NotificationId, ThoughtId, UserId}, value_objects::{NotificationId, ThoughtId, UserId},
@@ -44,17 +22,83 @@ impl PgNotificationRepository {
} }
} }
#[derive(sqlx::FromRow)]
struct NotificationRow {
id: uuid::Uuid,
user_id: uuid::Uuid,
notification_type: String,
from_user_id: Option<uuid::Uuid>,
thought_id: Option<uuid::Uuid>,
read: bool,
created_at: DateTime<Utc>,
}
fn row_to_notification(r: NotificationRow) -> Result<Notification, DomainError> {
let from_user_id = r
.from_user_id
.map(UserId::from_uuid)
.ok_or_else(|| DomainError::Internal("notification missing from_user_id".into()))?;
let kind = match r.notification_type.as_str() {
"follow" => NotificationKind::Follow { from_user_id },
other => {
let thought_id = r.thought_id.map(ThoughtId::from_uuid).ok_or_else(|| {
DomainError::Internal(format!("notification type '{other}' missing thought_id"))
})?;
match other {
"like" => NotificationKind::Like {
thought_id,
from_user_id,
},
"boost" => NotificationKind::Boost {
thought_id,
from_user_id,
},
"reply" => NotificationKind::Reply {
thought_id,
from_user_id,
},
"mention" => NotificationKind::Mention {
thought_id,
from_user_id,
},
_ => {
return Err(DomainError::Internal(format!(
"unknown notification type: {other}"
)))
}
}
}
};
Ok(Notification {
id: NotificationId::from_uuid(r.id),
user_id: UserId::from_uuid(r.user_id),
kind,
read: r.read,
created_at: r.created_at,
})
}
#[async_trait] #[async_trait]
impl NotificationRepository for PgNotificationRepository { impl NotificationRepository for PgNotificationRepository {
async fn save(&self, n: &Notification) -> Result<(), DomainError> { async fn save(&self, n: &Notification) -> Result<(), DomainError> {
sqlx::query( sqlx::query(
"INSERT INTO notifications(id,user_id,type,from_user_id,thought_id,read,created_at) VALUES($1,$2,$3,$4,$5,$6,$7)" "INSERT INTO notifications(id,user_id,notification_type,from_user_id,thought_id,read,created_at)
VALUES($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT(id) DO NOTHING"
) )
.bind(n.id.as_uuid()).bind(n.user_id.as_uuid()).bind(notif_type_as_str(&n.notification_type)) .bind(n.id.as_uuid())
.bind(n.from_user_id.as_ref().map(|u| u.as_uuid())) .bind(n.user_id.as_uuid())
.bind(n.thought_id.as_ref().map(|t| t.as_uuid())) .bind(n.kind.kind_str())
.bind(n.read).bind(n.created_at) .bind(n.kind.from_user_id().as_uuid())
.execute(&self.pool).await.into_domain().map(|_| ()) .bind(n.kind.thought_id().map(|t| t.as_uuid()))
.bind(n.read)
.bind(n.created_at)
.execute(&self.pool)
.await
.into_domain()
.map(|_| ())
} }
async fn list_for_user( async fn list_for_user(
@@ -67,32 +111,14 @@ impl NotificationRepository for PgNotificationRepository {
.fetch_one(&self.pool) .fetch_one(&self.pool)
.await .await
.into_domain()?; .into_domain()?;
#[derive(sqlx::FromRow)] let rows = sqlx::query_as::<_, NotificationRow>(
struct Row { "SELECT id,user_id,notification_type,from_user_id,thought_id,read,created_at FROM notifications WHERE user_id=$1 ORDER BY created_at DESC LIMIT $2 OFFSET $3"
id: uuid::Uuid,
user_id: uuid::Uuid,
r#type: String,
from_user_id: Option<uuid::Uuid>,
thought_id: Option<uuid::Uuid>,
read: bool,
created_at: DateTime<Utc>,
}
let rows = sqlx::query_as::<_, Row>(
"SELECT id,user_id,type,from_user_id,thought_id,read,created_at FROM notifications WHERE user_id=$1 ORDER BY created_at DESC LIMIT $2 OFFSET $3"
).bind(user_id.as_uuid()).bind(page.limit()).bind(page.offset()) ).bind(user_id.as_uuid()).bind(page.limit()).bind(page.offset())
.fetch_all(&self.pool).await.into_domain()?; .fetch_all(&self.pool).await.into_domain()?;
let items = rows let items = rows
.into_iter() .into_iter()
.map(|r| Notification { .map(row_to_notification)
id: NotificationId::from_uuid(r.id), .collect::<Result<Vec<_>, _>>()?;
user_id: UserId::from_uuid(r.user_id),
notification_type: notif_type_from_str(&r.r#type),
from_user_id: r.from_user_id.map(UserId::from_uuid),
thought_id: r.thought_id.map(ThoughtId::from_uuid),
read: r.read,
created_at: r.created_at,
})
.collect();
Ok(Paginated { Ok(Paginated {
items, items,
total, total,
@@ -139,7 +165,7 @@ mod tests {
use chrono::Utc; use chrono::Utc;
use domain::ports::UserWriter; use domain::ports::UserWriter;
use domain::{ use domain::{
models::{notification::NotificationType, user::User}, models::{notification::NotificationKind, user::User},
value_objects::*, value_objects::*,
}; };
@@ -158,14 +184,15 @@ mod tests {
#[sqlx::test(migrations = "./migrations")] #[sqlx::test(migrations = "./migrations")]
async fn save_and_list(pool: sqlx::PgPool) { async fn save_and_list(pool: sqlx::PgPool) {
let user = seed_user(&pool).await; let user = seed_user(&pool).await;
let from_user = seed_user(&pool).await;
let repo = PgNotificationRepository::new(pool); let repo = PgNotificationRepository::new(pool);
use domain::models::feed::PageParams; use domain::models::feed::PageParams;
let n = Notification { let n = Notification {
id: NotificationId::new(), id: NotificationId::new(),
user_id: user.id.clone(), user_id: user.id.clone(),
notification_type: NotificationType::Like, kind: NotificationKind::Follow {
from_user_id: None, from_user_id: from_user.id.clone(),
thought_id: None, },
read: false, read: false,
created_at: Utc::now(), created_at: Utc::now(),
}; };
@@ -187,14 +214,15 @@ mod tests {
#[sqlx::test(migrations = "./migrations")] #[sqlx::test(migrations = "./migrations")]
async fn mark_all_read(pool: sqlx::PgPool) { async fn mark_all_read(pool: sqlx::PgPool) {
let user = seed_user(&pool).await; let user = seed_user(&pool).await;
let from_user = seed_user(&pool).await;
let repo = PgNotificationRepository::new(pool); let repo = PgNotificationRepository::new(pool);
use domain::models::feed::PageParams; use domain::models::feed::PageParams;
let n = Notification { let n = Notification {
id: NotificationId::new(), id: NotificationId::new(),
user_id: user.id.clone(), user_id: user.id.clone(),
notification_type: NotificationType::Follow, kind: NotificationKind::Follow {
from_user_id: None, from_user_id: from_user.id.clone(),
thought_id: None, },
read: false, read: false,
created_at: Utc::now(), created_at: Utc::now(),
}; };

View File

@@ -2,9 +2,9 @@ use chrono::Utc;
use domain::{ use domain::{
errors::DomainError, errors::DomainError,
events::DomainEvent, events::DomainEvent,
models::notification::{Notification, NotificationType}, models::notification::{Notification, NotificationKind},
ports::{NotificationRepository, ThoughtRepository}, ports::{NotificationRepository, ThoughtRepository},
value_objects::{NotificationId, UserId}, value_objects::NotificationId,
}; };
use std::sync::Arc; use std::sync::Arc;
@@ -13,7 +13,10 @@ pub struct NotificationEventService {
pub notifications: Arc<dyn NotificationRepository>, pub notifications: Arc<dyn NotificationRepository>,
} }
fn is_self_action(thought_author: &UserId, actor: &UserId) -> bool { fn is_self_action(
thought_author: &domain::value_objects::UserId,
actor: &domain::value_objects::UserId,
) -> bool {
thought_author == actor thought_author == actor
} }
@@ -36,9 +39,10 @@ impl NotificationEventService {
.save(&Notification { .save(&Notification {
id: NotificationId::new(), id: NotificationId::new(),
user_id: thought.user_id, user_id: thought.user_id,
notification_type: NotificationType::Like, kind: NotificationKind::Like {
from_user_id: Some(user_id.clone()), thought_id: thought_id.clone(),
thought_id: Some(thought_id.clone()), from_user_id: user_id.clone(),
},
read: false, read: false,
created_at: Utc::now(), created_at: Utc::now(),
}) })
@@ -60,9 +64,10 @@ impl NotificationEventService {
.save(&Notification { .save(&Notification {
id: NotificationId::new(), id: NotificationId::new(),
user_id: thought.user_id, user_id: thought.user_id,
notification_type: NotificationType::Boost, kind: NotificationKind::Boost {
from_user_id: Some(user_id.clone()), thought_id: thought_id.clone(),
thought_id: Some(thought_id.clone()), from_user_id: user_id.clone(),
},
read: false, read: false,
created_at: Utc::now(), created_at: Utc::now(),
}) })
@@ -76,9 +81,9 @@ impl NotificationEventService {
.save(&Notification { .save(&Notification {
id: NotificationId::new(), id: NotificationId::new(),
user_id: following_id.clone(), user_id: following_id.clone(),
notification_type: NotificationType::Follow, kind: NotificationKind::Follow {
from_user_id: Some(follower_id.clone()), from_user_id: follower_id.clone(),
thought_id: None, },
read: false, read: false,
created_at: Utc::now(), created_at: Utc::now(),
}) })
@@ -104,9 +109,10 @@ impl NotificationEventService {
.save(&Notification { .save(&Notification {
id: NotificationId::new(), id: NotificationId::new(),
user_id: original.user_id, user_id: original.user_id,
notification_type: NotificationType::Reply, kind: NotificationKind::Reply {
from_user_id: Some(user_id.clone()), thought_id: thought_id.clone(),
thought_id: Some(thought_id.clone()), from_user_id: user_id.clone(),
},
read: false, read: false,
created_at: Utc::now(), created_at: Utc::now(),
}) })
@@ -121,9 +127,10 @@ impl NotificationEventService {
.save(&Notification { .save(&Notification {
id: NotificationId::new(), id: NotificationId::new(),
user_id: mentioned_user_id.clone(), user_id: mentioned_user_id.clone(),
notification_type: NotificationType::Mention, kind: NotificationKind::Mention {
from_user_id: Some(author_user_id.clone()), thought_id: thought_id.clone(),
thought_id: Some(thought_id.clone()), from_user_id: author_user_id.clone(),
},
read: false, read: false,
created_at: Utc::now(), created_at: Utc::now(),
}) })
@@ -139,6 +146,7 @@ mod tests {
use super::*; use super::*;
use domain::{ use domain::{
models::{ models::{
notification::NotificationKind,
thought::{Thought, Visibility}, thought::{Thought, Visibility},
user::User, user::User,
}, },
@@ -184,10 +192,7 @@ mod tests {
.unwrap(); .unwrap();
let notifs = store.notifications.lock().unwrap(); let notifs = store.notifications.lock().unwrap();
assert_eq!(notifs.len(), 1); assert_eq!(notifs.len(), 1);
assert!(matches!( assert!(matches!(notifs[0].kind, NotificationKind::Like { .. }));
notifs[0].notification_type,
NotificationType::Like
));
} }
#[tokio::test] #[tokio::test]
@@ -235,10 +240,7 @@ mod tests {
.unwrap(); .unwrap();
let notifs = store.notifications.lock().unwrap(); let notifs = store.notifications.lock().unwrap();
assert_eq!(notifs.len(), 1); assert_eq!(notifs.len(), 1);
assert!(matches!( assert!(matches!(notifs[0].kind, NotificationKind::Follow { .. }));
notifs[0].notification_type,
NotificationType::Follow
));
} }
#[tokio::test] #[tokio::test]
@@ -269,10 +271,7 @@ mod tests {
.unwrap(); .unwrap();
let notifs = store.notifications.lock().unwrap(); let notifs = store.notifications.lock().unwrap();
assert_eq!(notifs.len(), 1); assert_eq!(notifs.len(), 1);
assert!(matches!( assert!(matches!(notifs[0].kind, NotificationKind::Reply { .. }));
notifs[0].notification_type,
NotificationType::Reply
));
} }
#[tokio::test] #[tokio::test]

View File

@@ -1,22 +1,66 @@
use crate::value_objects::{NotificationId, ThoughtId, UserId}; use crate::value_objects::{NotificationId, ThoughtId, UserId};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq)]
pub enum NotificationType { pub enum NotificationKind {
Like, Like {
Boost, thought_id: ThoughtId,
Follow, from_user_id: UserId,
Mention, },
Reply, Boost {
thought_id: ThoughtId,
from_user_id: UserId,
},
Reply {
thought_id: ThoughtId,
from_user_id: UserId,
},
Mention {
thought_id: ThoughtId,
from_user_id: UserId,
},
Follow {
from_user_id: UserId,
},
}
impl NotificationKind {
pub fn from_user_id(&self) -> &UserId {
match self {
Self::Like { from_user_id, .. } => from_user_id,
Self::Boost { from_user_id, .. } => from_user_id,
Self::Reply { from_user_id, .. } => from_user_id,
Self::Mention { from_user_id, .. } => from_user_id,
Self::Follow { from_user_id } => from_user_id,
}
}
pub fn thought_id(&self) -> Option<&ThoughtId> {
match self {
Self::Like { thought_id, .. } => Some(thought_id),
Self::Boost { thought_id, .. } => Some(thought_id),
Self::Reply { thought_id, .. } => Some(thought_id),
Self::Mention { thought_id, .. } => Some(thought_id),
Self::Follow { .. } => None,
}
}
pub fn kind_str(&self) -> &'static str {
match self {
Self::Like { .. } => "like",
Self::Boost { .. } => "boost",
Self::Reply { .. } => "reply",
Self::Mention { .. } => "mention",
Self::Follow { .. } => "follow",
}
}
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Notification { pub struct Notification {
pub id: NotificationId, pub id: NotificationId,
pub user_id: UserId, pub user_id: UserId,
pub notification_type: NotificationType, pub kind: NotificationKind,
pub from_user_id: Option<UserId>,
pub thought_id: Option<ThoughtId>,
pub read: bool, pub read: bool,
pub created_at: DateTime<Utc>, pub created_at: DateTime<Utc>,
} }