Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(notif): delete invalid notifs when listing (#1702)

Sean Aye1bb0c5efc984
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 53b9f717a6..eb02009f04 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -6427,6 +6427,7 @@ dependencies = [
"chrono",
"email_validator",
"http-body-util",
+ "itertools 0.14.0",
"macro_auth",
"macro_aws_config",
"macro_cors",
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index f289d71b4a..f1f4668e6b 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -1,13 +1,7 @@
//! Domain models for the notification service.
-use std::sync::Arc;
-
-use macro_user_id::user_id::MacroUserIdStr;
-use serde::{Deserialize, Serialize, de::DeserializeOwned};
-
pub mod android;
pub mod apple;
-
pub mod email_notification_digest;
pub mod mobile;
pub mod push_notification_event;
@@ -16,16 +10,17 @@ pub mod rate_limit;
pub mod recipient;
pub mod request;
+use crate::domain::models::{apple::APNSPushNotification, queue_message::EmailContent};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
pub use mobile::{DeviceEndpoint, HashedCollapseKey, NotifCollapseKey};
+use model_entity::Entity;
+use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
pub use rate_limit::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult};
pub use recipient::{ExclusionReason, FilteredRecipient, RecipientExclusion};
pub use request::{NotificationResult, SendNotificationRequest, SendNotificationRequestBuilder};
-
-use chrono::{DateTime, Utc};
-use model_entity::Entity;
-use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
-
-use crate::domain::models::{apple::APNSPushNotification, queue_message::EmailContent};
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
+use std::sync::Arc;
/// Notification ID paired with its APNS collapse key, for push clearing.
#[derive(Debug, Clone)]
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
index f85429e320..f74dbe9aef 100644
--- a/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
@@ -637,7 +637,7 @@ where
// retrieve the notification data and add it to the batch
let Some(notif) = self
.notif_repo
- .get_user_notification_by_id::<serde_json::Value>(user_id.as_ref(), notif_id)
+ .get_user_notification_by_id::<serde_json::Value>(user_id.copied(), notif_id)
.await?
else {
return Err(report!(
diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rs
index 06c9bfb972..8a384e936b 100644
--- a/rust/cloud-storage/notification/src/domain/models/request.rs
+++ b/rust/cloud-storage/notification/src/domain/models/request.rs
@@ -222,7 +222,7 @@ pub struct UpdateNotificationsRequest<'a> {
#[derive(Debug)]
pub struct GetNotificationsByEventItemIdsRequest<'a> {
/// The user whose notifications to retrieve.
- pub user_id: &'a str,
+ pub user_id: MacroUserIdStr<'a>,
/// The event item IDs to filter by.
pub event_item_ids: &'a [Uuid],
/// Maximum number of results per page (default 20, max 500).
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index 08e01f0736..620adc29d3 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -125,7 +125,7 @@ pub trait NotificationRepository: Send + Sync + 'static {
/// The metadata JSON column is deserialized into `T`.
fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;
@@ -136,7 +136,7 @@ pub trait NotificationRepository: Send + Sync + 'static {
/// matching one of the provided `event_item_ids`.
fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
event_item_ids: &[Uuid],
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
@@ -147,21 +147,21 @@ pub trait NotificationRepository: Send + Sync + 'static {
/// Returns `None` if no active (non-deleted) notification exists for the given user and ID.
fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> impl Future<Output = Result<Option<UserNotificationRow<T>>, Report>> + Send;
/// Soft-delete a single user notification.
fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> impl Future<Output = Result<(), Report>> + Send;
/// Soft-delete multiple user notifications.
fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> impl Future<Output = Result<(), Report>> + Send;
}
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
index 6b259e1b32..704b001ccc 100644
--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -20,6 +20,7 @@ use crate::domain::ports::{NotificationQueue, NotificationRepository};
use crate::domain::service::SendNotificationError;
use ::futures::future::join_all;
use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, PaginateOn, Paginated, Query, TypeEraseCursor};
use rootcause::Report;
use rootcause::prelude::ResultExt;
@@ -58,7 +59,7 @@ pub trait NotificationReader: Send + Sync + 'static {
/// not deleted and not done, ordered by creation time descending.
fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: Option<u32>,
cursor: Query<Uuid, CreatedAt, ()>,
) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send;
@@ -72,21 +73,21 @@ pub trait NotificationReader: Send + Sync + 'static {
/// Get a single user notification by ID.
fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> impl Future<Output = Result<Option<UserNotificationRow<T>>, Report>> + Send;
/// Soft-delete a single user notification.
fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> impl Future<Output = Result<(), Report>> + Send;
/// Soft-delete multiple user notifications.
fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> impl Future<Output = Result<(), Report>> + Send;
}
@@ -453,7 +454,7 @@ where
#[tracing::instrument(err, skip(self))]
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: Option<u32>,
cursor: Query<Uuid, CreatedAt, ()>,
) -> Result<Paginated<UserNotificationRow<T>, String>, Report> {
@@ -502,7 +503,7 @@ where
#[tracing::instrument(err, skip(self))]
async fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<Option<UserNotificationRow<T>>, Report> {
self.repository
@@ -513,7 +514,7 @@ where
#[tracing::instrument(err, skip(self))]
async fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<(), Report> {
self.repository
@@ -524,7 +525,7 @@ where
#[tracing::instrument(err, skip(self))]
async fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> Result<(), Report> {
self.repository
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index 5c6ee53e84..9d22c420eb 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -264,7 +264,7 @@ impl NotificationRepository for MockRepository {
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- _user_id: &str,
+ _user_id: MacroUserIdStr<'_>,
_limit: u32,
_cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,
) -> Result<Vec<UserNotificationRow<T>>, Report> {
@@ -273,7 +273,7 @@ impl NotificationRepository for MockRepository {
async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(
&self,
- _user_id: &str,
+ _user_id: MacroUserIdStr<'_>,
_event_item_ids: &[Uuid],
_limit: u32,
_cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,
@@ -283,7 +283,7 @@ impl NotificationRepository for MockRepository {
async fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- _user_id: &str,
+ _user_id: MacroUserIdStr<'_>,
_notification_id: Uuid,
) -> Result<Option<UserNotificationRow<T>>, Report> {
Ok(None)
@@ -291,7 +291,7 @@ impl NotificationRepository for MockRepository {
async fn delete_user_notification(
&self,
- _user_id: &str,
+ _user_id: MacroUserIdStr<'_>,
_notification_id: Uuid,
) -> Result<(), Report> {
Ok(())
@@ -299,7 +299,7 @@ impl NotificationRepository for MockRepository {
async fn bulk_delete_user_notifications(
&self,
- _user_id: &str,
+ _user_id: MacroUserIdStr<'_>,
_notification_ids: &[Uuid],
) -> Result<(), Report> {
Ok(())
@@ -379,7 +379,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: u32,
cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,
) -> Result<Vec<UserNotificationRow<T>>, Report> {
@@ -390,7 +390,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
event_item_ids: &[Uuid],
limit: u32,
cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,
@@ -402,7 +402,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
async fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<Option<UserNotificationRow<T>>, Report> {
(**self)
@@ -412,7 +412,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
async fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<(), Report> {
(**self)
@@ -422,7 +422,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
async fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> Result<(), Report> {
(**self)
diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
index 7aa0119183..7228e8fd4c 100644
--- a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
@@ -14,6 +14,7 @@ use ai::tool::{
AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolCallError, ToolResult,
};
use async_trait::async_trait;
+use cowlike::CowLike;
use models_pagination::CreatedAt;
use rootcause::compat::boxed_error::IntoBoxedError;
use schemars::JsonSchema;
@@ -141,7 +142,7 @@ where
let paginated = service_context
.service
.get_user_notifications::<serde_json::Value>(
- (*request_context.user_id).as_ref(),
+ (*request_context.user_id).copied(),
Some(limit),
models_pagination::Query::Sort(CreatedAt, ()),
)
diff --git a/rust/cloud-storage/notification/src/inbound/http.rs b/rust/cloud-storage/notification/src/inbound/http.rs
index 7405300363..63e65fa6c9 100644
--- a/rust/cloud-storage/notification/src/inbound/http.rs
+++ b/rust/cloud-storage/notification/src/inbound/http.rs
@@ -40,7 +40,8 @@ pub struct NotificationIdPath {
/// the router state for a notification router
pub struct NotificationRouterState<S> {
- inner: Arc<S>,
+ /// the inner S wrapped in an [Arc]
+ pub inner: Arc<S>,
}
impl<S> Clone for NotificationRouterState<S> {
@@ -90,7 +91,7 @@ pub async fn list_user_notifications<
S: NotificationReader,
T: Serialize + DeserializeOwned + Send,
>(
- State(service): State<NotificationRouterState<S>>,
+ service: &NotificationRouterState<S>,
macro_user: MacroUserExtractor,
Query(Params { limit }): Query<Params>,
cursor: CursorExtractor<Uuid, CreatedAt, ()>,
@@ -98,7 +99,7 @@ pub async fn list_user_notifications<
let query = cursor.into_query(CreatedAt, ());
let result = service
.inner
- .get_user_notifications::<T>(macro_user.macro_user_id.as_ref(), limit, query)
+ .get_user_notifications::<T>(macro_user.macro_user_id, limit, query)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notifications");
@@ -154,7 +155,7 @@ pub async fn bulk_get_by_event_item_ids<
let result = service
.inner
.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {
- user_id: macro_user.macro_user_id.as_ref(),
+ user_id: macro_user.macro_user_id,
event_item_ids: &req.event_item_ids,
limit,
cursor: cursor.into_query(CreatedAt, ()),
@@ -301,7 +302,7 @@ pub async fn get_by_event_item_id<S: NotificationReader, T: Serialize + Deserial
let result = service
.inner
.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {
- user_id: macro_user.macro_user_id.as_ref(),
+ user_id: macro_user.macro_user_id,
event_item_ids: &[event_item_id],
limit,
cursor: cursor.into_query(CreatedAt, ()),
@@ -349,7 +350,7 @@ pub async fn get_notification_by_id<
) -> Result<Json<UserNotificationRow<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
.inner
- .get_user_notification_by_id::<T>(macro_user.macro_user_id.as_ref(), notification_id)
+ .get_user_notification_by_id::<T>(macro_user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notification by id");
@@ -395,7 +396,7 @@ pub async fn delete_notification<S: NotificationReader>(
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
- .delete_user_notification(macro_user.macro_user_id.as_ref(), notification_id)
+ .delete_user_notification(macro_user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to delete user notification");
@@ -430,7 +431,7 @@ pub async fn bulk_delete_notifications<S: NotificationReader>(
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
- .bulk_delete_user_notifications(macro_user.macro_user_id.as_ref(), &req.notification_ids)
+ .bulk_delete_user_notifications(macro_user.macro_user_id, &req.notification_ids)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to delete user notifications");
diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rs
index 7fe35fb6f0..b557db1b82 100644
--- a/rust/cloud-storage/notification/src/outbound/repository.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository.rs
@@ -116,7 +116,7 @@ pub trait NotificationDbOps: Send + Sync + 'static {
/// The metadata JSON column is deserialized into `T`.
fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
) -> impl std::future::Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;
@@ -124,7 +124,7 @@ pub trait NotificationDbOps: Send + Sync + 'static {
/// Get a user's active notifications filtered by event item IDs, with cursor-based pagination.
fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
event_item_ids: &[Uuid],
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
@@ -133,21 +133,21 @@ pub trait NotificationDbOps: Send + Sync + 'static {
/// Get a single user notification by ID.
fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> impl std::future::Future<Output = Result<Option<UserNotificationRow<T>>, Report>> + Send;
/// Soft-delete a single user notification.
fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> impl std::future::Future<Output = Result<(), Report>> + Send;
/// Soft-delete multiple user notifications.
fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> impl std::future::Future<Output = Result<(), Report>> + Send;
}
@@ -431,7 +431,7 @@ impl NotificationDbOps for PgPool {
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
) -> Result<Vec<UserNotificationRow<T>>, Report> {
@@ -464,7 +464,7 @@ impl NotificationDbOps for PgPool {
ORDER BY un.created_at DESC, un.notification_id DESC
LIMIT $2
"#,
- user_id,
+ user_id.as_ref(),
query_limit,
cursor_timestamp,
cursor_id as _,
@@ -511,7 +511,7 @@ impl NotificationDbOps for PgPool {
async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
event_item_ids: &[Uuid],
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
@@ -547,7 +547,7 @@ impl NotificationDbOps for PgPool {
ORDER BY un.created_at DESC, un.notification_id DESC
LIMIT $3
"#,
- user_id,
+ user_id.as_ref(),
&event_item_ids,
query_limit,
cursor_timestamp,
@@ -595,7 +595,7 @@ impl NotificationDbOps for PgPool {
async fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<Option<UserNotificationRow<T>>, Report> {
let row = sqlx::query!(
@@ -621,7 +621,7 @@ impl NotificationDbOps for PgPool {
AND un.deleted_at IS NULL
LIMIT 1
"#,
- user_id,
+ user_id.as_ref(),
notification_id,
)
.fetch_optional(self)
@@ -667,7 +667,7 @@ impl NotificationDbOps for PgPool {
async fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<(), Report> {
sqlx::query!(
@@ -676,7 +676,7 @@ impl NotificationDbOps for PgPool {
SET deleted_at = NOW()
WHERE user_id = $1 AND notification_id = $2
"#,
- user_id,
+ user_id.as_ref(),
notification_id,
)
.execute(self)
@@ -687,7 +687,7 @@ impl NotificationDbOps for PgPool {
async fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> Result<(), Report> {
sqlx::query!(
@@ -696,7 +696,7 @@ impl NotificationDbOps for PgPool {
SET deleted_at = NOW()
WHERE user_id = $1 AND notification_id = ANY($2)
"#,
- user_id,
+ user_id.as_ref(),
notification_ids,
)
.execute(self)
@@ -779,7 +779,7 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
) -> Result<Vec<UserNotificationRow<T>>, Report> {
@@ -788,7 +788,7 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
event_item_ids: &[Uuid],
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
@@ -800,7 +800,7 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
async fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<Option<UserNotificationRow<T>>, Report> {
self.db
@@ -810,7 +810,7 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
async fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<(), Report> {
self.db
@@ -820,7 +820,7 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
async fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> Result<(), Report> {
self.db
diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rs
index df7a11959d..70a6f9df49 100644
--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs
@@ -278,7 +278,11 @@ async fn test_get_basic_notifications_empty(pool: Pool<Postgres>) {
)]
async fn test_get_user_notifications(pool: Pool<Postgres>) {
let result: Vec<UserNotificationRow<TestNotification>> = pool
- .get_user_notifications("macro|[email protected]", 10, Query::Sort(CreatedAt, ()))
+ .get_user_notifications(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ 10,
+ Query::Sort(CreatedAt, ()),
+ )
.await
.unwrap();
@@ -301,7 +305,11 @@ async fn test_get_user_notifications(pool: Pool<Postgres>) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_get_user_notifications_empty(pool: Pool<Postgres>) {
let result: Vec<UserNotificationRow<TestNotification>> = pool
- .get_user_notifications("macro|[email protected]", 10, Query::Sort(CreatedAt, ()))
+ .get_user_notifications(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ 10,
+ Query::Sort(CreatedAt, ()),
+ )
.await
.unwrap();
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
index 82ed4681ec..50a6f454b4 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -1,7 +1,3 @@
-use std::collections::HashMap;
-use std::collections::HashSet;
-use std::sync::Arc;
-
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Query};
use notification::domain::models::{
@@ -13,6 +9,9 @@ use notification::outbound::repository::DbNotificationRepository;
use rootcause::Report;
use serde::de::DeserializeOwned;
use sqlx::PgPool;
+use std::collections::HashMap;
+use std::collections::HashSet;
+use std::sync::Arc;
use uuid::Uuid;
/// Notification repository that wraps the real DB repository but overrides
@@ -113,7 +112,7 @@ impl NotificationRepository for SandboxNotificationRepository {
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
) -> Result<Vec<UserNotificationRow<T>>, Report> {
@@ -124,7 +123,7 @@ impl NotificationRepository for SandboxNotificationRepository {
async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
event_item_ids: &[Uuid],
limit: u32,
cursor: Query<Uuid, CreatedAt, ()>,
@@ -136,7 +135,7 @@ impl NotificationRepository for SandboxNotificationRepository {
async fn get_user_notification_by_id<T: DeserializeOwned + Send>(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<Option<UserNotificationRow<T>>, Report> {
self.inner
@@ -146,7 +145,7 @@ impl NotificationRepository for SandboxNotificationRepository {
async fn delete_user_notification(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_id: Uuid,
) -> Result<(), Report> {
self.inner
@@ -156,7 +155,7 @@ impl NotificationRepository for SandboxNotificationRepository {
async fn bulk_delete_user_notifications(
&self,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
notification_ids: &[Uuid],
) -> Result<(), Report> {
self.inner
diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.toml
index 17bc32838d..dd60641fe0 100644
--- a/rust/cloud-storage/notification_service/Cargo.toml
+++ b/rust/cloud-storage/notification_service/Cargo.toml
@@ -28,6 +28,7 @@ axum = { workspace = true }
chrono = { workspace = true }
email_validator = { path = "../email_validator" }
http-body-util = { workspace = true }
+itertools = { workspace = true }
macro_auth = { path = "../macro_auth" }
macro_aws_config = { path = "../macro_aws_config" }
macro_cors = { path = "../macro_cors" }
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rs
index 7c1ef3d644..5a00e076a0 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs
@@ -1,11 +1,15 @@
use ::notification::domain::models::UserNotificationRow;
+use axum::extract::State;
use chrono::{DateTime, Utc};
+use itertools::{Either, Itertools};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use model_error_response::ErrorResponse;
use model_notifications::NotifEvent;
+use notification::{domain::service::NotificationReader, inbound::http::NotificationRouterState};
use serde::Serialize;
use utoipa::ToSchema;
+use uuid::Uuid;
#[cfg(test)]
mod test;
@@ -145,7 +149,7 @@ pub fn router<
)
)]
async fn list_typed_notifications<S: ::notification::domain::service::NotificationReader>(
- state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,
+ State(state): State<::notification::inbound::http::NotificationRouterState<S>>,
macro_user: model_user::axum_extractor::MacroUserExtractor,
query: axum::extract::Query<::notification::inbound::http::Params>,
cursor: models_pagination::CursorExtractor<uuid::Uuid, models_pagination::CreatedAt, ()>,
@@ -156,29 +160,81 @@ async fn list_typed_notifications<S: ::notification::domain::service::Notificati
axum::Json<model_error_response::ErrorResponse<'static>>,
),
> {
+ let user = macro_user.macro_user_id.clone();
let axum::Json(response) = ::notification::inbound::http::list_user_notifications::<
S,
serde_json::Value,
- >(state, macro_user, query, cursor)
+ >(&state, macro_user, query, cursor)
.await?;
- let items = response
+ let (notifs, failed): (Vec<_>, Vec<_>) = response
.items
.into_iter()
- .filter_map(|row| {
- to_typed_row(row)
- .inspect_err(|e| tracing::warn!(error=?e, "failed to deserialize notification row"))
- .ok()
- })
- .map(ApiUserNotification::from_notification)
- .collect();
+ .map(|r| (r.notification_id, to_typed_row(r)))
+ .partition_map(|r| match r {
+ (_id, Ok(notif)) => Either::Left(notif),
+ (id, Err(e)) => Either::Right((id, e)),
+ });
+
+ if !failed.is_empty() {
+ tokio::task::spawn(
+ CleanUpNotificationsTask {
+ service: state,
+ user,
+ failed_notifs: failed,
+ }
+ .delete_failures(),
+ );
+ }
Ok(axum::Json(GetAllUserNotificationsResponse {
- items,
+ items: notifs
+ .into_iter()
+ .map(ApiUserNotification::from_notification)
+ .collect(),
next_cursor: response.next_cursor,
}))
}
+struct CleanUpNotificationsTask<S> {
+ service: NotificationRouterState<S>,
+ user: MacroUserIdStr<'static>,
+ failed_notifs: Vec<(Uuid, serde_json::Error)>,
+}
+
+impl<S> CleanUpNotificationsTask<S>
+where
+ S: NotificationReader,
+{
+ async fn delete_failures(self) {
+ let CleanUpNotificationsTask {
+ service,
+ failed_notifs,
+ user,
+ } = self;
+
+ fn filter_erors((uuid, err): (Uuid, serde_json::Error)) -> Option<Uuid> {
+ let output = err
+ .to_string()
+ .contains("channel_message_document")
+ .then_some(uuid);
+
+ if output.is_none() {
+ tracing::warn!("{err:?}");
+ }
+
+ output
+ }
+
+ let to_delete: Vec<_> = failed_notifs.into_iter().filter_map(filter_erors).collect();
+
+ let _ = service
+ .inner
+ .bulk_delete_user_notifications(user, to_delete.as_slice())
+ .await;
+ }
+}
+
/// Wrapper handler that calls the inner generic bulk-get handler with `serde_json::Value`,
/// then converts each row to [`UserNotificationRow<NotifEvent>`].
///