Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(notif): move more stuff into notification (#1778)
Sean Aye7b11ca4a25ee
diff --git a/js/app/packages/service-clients/service-notification/generated/client.ts b/js/app/packages/service-clients/service-notification/generated/client.tsindex a5e49ff0fb..2565a6fcd9 100644--- a/js/app/packages/service-clients/service-notification/generated/client.ts+++ b/js/app/packages/service-clients/service-notification/generated/client.ts@@ -8,7 +8,6 @@ import type {ApiUserNotification,BulkGetByEventItemIdsRequest,BulkGetTypedNotificationsByEventItemIdsParams,- DeviceRequest,EmptyResponse,ErrorResponse,GetAllUserNotificationsResponse,@@ -18,132 +17,6 @@ import type {UserUnsubscribe,} from './schemas';-/**- * @summary Register a user device for push notifications.- */-export type registerDeviceResponse200 = {- data: EmptyResponse;- status: 200;-};--export type registerDeviceResponse401 = {- data: ErrorResponse;- status: 401;-};--export type registerDeviceResponse500 = {- data: ErrorResponse;- status: 500;-};--export type registerDeviceResponse501 = {- data: ErrorResponse;- status: 501;-};--export type registerDeviceResponseSuccess = registerDeviceResponse200 & {- headers: Headers;-};-export type registerDeviceResponseError = (- | registerDeviceResponse401- | registerDeviceResponse500- | registerDeviceResponse501-) & {- headers: Headers;-};--export type registerDeviceResponse =- | registerDeviceResponseSuccess- | registerDeviceResponseError;--export const getRegisterDeviceUrl = () => {- return `/device/register`;-};--export const registerDevice = async (- deviceRequest: DeviceRequest,- options?: RequestInit-): Promise<registerDeviceResponse> => {- const res = await fetch(getRegisterDeviceUrl(), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(deviceRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: registerDeviceResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as registerDeviceResponse;-};--/**- * @summary Unregister a device from receiving push notifications.- */-export type unregisterDeviceResponse200 = {- data: EmptyResponse;- status: 200;-};--export type unregisterDeviceResponse401 = {- data: ErrorResponse;- status: 401;-};--export type unregisterDeviceResponse404 = {- data: ErrorResponse;- status: 404;-};--export type unregisterDeviceResponse500 = {- data: ErrorResponse;- status: 500;-};--export type unregisterDeviceResponseSuccess = unregisterDeviceResponse200 & {- headers: Headers;-};-export type unregisterDeviceResponseError = (- | unregisterDeviceResponse401- | unregisterDeviceResponse404- | unregisterDeviceResponse500-) & {- headers: Headers;-};--export type unregisterDeviceResponse =- | unregisterDeviceResponseSuccess- | unregisterDeviceResponseError;--export const getUnregisterDeviceUrl = () => {- return `/device/unregister`;-};--export const unregisterDevice = async (- deviceRequest: DeviceRequest,- options?: RequestInit-): Promise<unregisterDeviceResponse> => {- const res = await fetch(getUnregisterDeviceUrl(), {- ...options,- method: 'DELETE',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(deviceRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: unregisterDeviceResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as unregisterDeviceResponse;-};-/*** @summary Health check*/diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/deviceRequest.ts b/js/app/packages/service-clients/service-notification/generated/schemas/deviceRequest.tsindex 5158a97fca..3c89dacff4 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/deviceRequest.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/deviceRequest.ts@@ -6,7 +6,12 @@*/import type { DeviceType } from './deviceType';+/**+ * Request to register or unregister a device for push notifications.+ */export interface DeviceRequest {+ /** The device platform type (iOS or Android). */deviceType: DeviceType;+ /** The device push notification token. */token: string;}diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex b81c57fa41..1928c53ccd 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -10,124 +10,6 @@"version": "0.1.0"},"paths": {- "/device/register": {- "post": {- "tags": ["device::register"],- "summary": "Register a user device for push notifications.",- "operationId": "register_device",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/DeviceRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "501": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },- "/device/unregister": {- "delete": {- "tags": ["device::unregister"],- "summary": "Unregister a device from receiving push notifications.",- "operationId": "unregister_device",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/DeviceRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },"/health": {"get": {"tags": ["health"],@@ -1204,13 +1086,16 @@},"DeviceRequest": {"type": "object",+ "description": "Request to register or unregister a device for push notifications.","required": ["deviceType", "token"],"properties": {"deviceType": {- "$ref": "#/components/schemas/DeviceType"+ "$ref": "#/components/schemas/DeviceType",+ "description": "The device platform type (iOS or Android)."},"token": {- "type": "string"+ "type": "string",+ "description": "The device push notification token."}}},diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex dfc3d71e48..58b9b5589f 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -6406,6 +6406,7 @@ dependencies = ["last_online_tracker","macro_db_migrator","macro_user_id",+ "macro_uuid","model-entity","model-error-response","model_user",@@ -6418,6 +6419,7 @@ dependencies = ["serde_json","sha2","sqlx",+ "strum","thiserror 2.0.17","tokio","tracing",diff --git a/rust/cloud-storage/notification/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json b/rust/cloud-storage/notification/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.jsonnew file mode 100644index 0000000000..01cece9642--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json@@ -0,0 +1,33 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM notification_user_device_registration\n WHERE device_token = $1 AND device_type = $2\n RETURNING device_endpoint\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "device_endpoint",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ {+ "Custom": {+ "name": "notification_device_type_option",+ "kind": {+ "Enum": [+ "ios",+ "android"+ ]+ }+ }+ }+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.json b/rust/cloud-storage/notification/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.jsonnew file mode 100644index 0000000000..9e6f7f8877--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT d.device_endpoint\n FROM notification_user_device_registration d\n WHERE d.device_token = $1\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "device_endpoint",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json b/rust/cloud-storage/notification/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.jsonnew file mode 100644index 0000000000..e5d913399d--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO notification_user_device_registration (id, user_id, device_token, device_endpoint, device_type)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (device_endpoint) DO UPDATE SET user_id = $2, device_token = $3, device_type = $5, updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ {+ "Custom": {+ "name": "notification_device_type_option",+ "kind": {+ "Enum": [+ "ios",+ "android"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb"+}diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex 3ef9f18dcb..c4c6122c1c 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -35,6 +35,8 @@ hex = { workspace = true }itertools = { workspace = true }last_online_tracker = { path = "../last_online_tracker" }macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid" }+strum = { workspace = true }model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true, features = ["axum"] }diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rsindex f1f4668e6b..717214e9df 100644--- a/rust/cloud-storage/notification/src/domain/models.rs+++ b/rust/cloud-storage/notification/src/domain/models.rs@@ -2,6 +2,7 @@pub mod android;pub mod apple;+pub mod device;pub mod email_notification_digest;pub mod mobile;pub mod push_notification_event;diff --git a/rust/cloud-storage/notification/src/domain/models/device.rs b/rust/cloud-storage/notification/src/domain/models/device.rsnew file mode 100644index 0000000000..4988d3a980--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/models/device.rs@@ -0,0 +1,32 @@+//! Device registration models.++use serde::{Deserialize, Serialize};+use sqlx::Type;+use strum::{Display, EnumString};++/// The device platform type.+#[derive(Debug, Clone, Serialize, Deserialize, Type, EnumString, Display, Eq, PartialEq)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "lowercase")]+#[sqlx(+ type_name = "notification_device_type_option",+ rename_all = "lowercase"+)]+#[strum(serialize_all = "lowercase")]+pub enum DeviceType {+ /// iOS (APNS).+ Ios,+ /// Android (FCM).+ Android,+}++/// Request to register or unregister a device for push notifications.+#[derive(Debug, Deserialize, Serialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct DeviceRequest {+ /// The device platform type (iOS or Android).+ pub device_type: DeviceType,+ /// The device push notification token.+ pub token: String,+}diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex 36dc7eb5ad..203aead32e 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -15,6 +15,8 @@ use uuid::Uuid;use models_pagination::{CreatedAt, Query};+use crate::domain::models::device::DeviceType;+use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};use crate::domain::models::{DeviceEndpoint, Notification, NotificationExtEmail, NotificationIdAndCollapseKey,@@ -102,7 +104,7 @@ pub trait NotificationRepository: Send + Sync + 'static {/// Mark notifications as seen for a user.fn mark_notifications_seen(&self,- user_id: &MacroUserIdStr<'_>,+ user_id: MacroUserIdStr<'_>,notification_ids: &[Uuid],) -> impl Future<Output = Result<(), Report>> + Send;@@ -170,6 +172,39 @@ pub trait NotificationRepository: Send + Sync + 'static {&self,user_id: MacroUserIdStr<'_>,) -> impl Future<Output = Result<(), Report>> + Send;++ /// Look up an existing device endpoint ARN by its device token.+ ///+ /// Returns `None` if no registration exists for this token.+ fn get_device_endpoint(+ &self,+ device_token: &str,+ ) -> impl Future<Output = Result<Option<String>, Report>> + Send;++ /// Upsert a device registration: create a new one or update the existing+ /// record if the endpoint already exists.+ fn upsert_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_endpoint: &str,+ device_type: &DeviceType,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Delete the device registration matching the given token and type.+ ///+ /// Returns the endpoint ARN that was removed.+ fn delete_device_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> impl Future<Output = Result<String, Report>> + Send;++ /// Delete a device registration by its endpoint ARN.+ fn delete_device_by_endpoint(+ &self,+ endpoint_arn: &str,+ ) -> impl Future<Output = Result<(), Report>> + Send;}/// Port for WebSocket delivery via connection gateway.@@ -238,17 +273,30 @@ pub trait NotificationEgress: Send + Sync + 'static {) -> impl Future<Output = Result<ClaimResult<()>, Report>> + Send;}-/// Port for deleting a device registration from the database by its SNS endpoint ARN.-pub trait DeviceRegistrationDeleter: Send + Sync + 'static {- /// Delete a device registration by its endpoint ARN.- fn delete_device_by_endpoint(+/// Port for SNS platform endpoint management (create, get/set attributes).+pub trait SnsEndpointManager: Send + Sync + 'static {+ /// Create a new SNS platform endpoint for the given platform ARN and device token.+ ///+ /// Returns the new endpoint ARN.+ fn create_platform_endpoint(+ &self,+ platform_arn: &str,+ token: &str,+ ) -> impl Future<Output = Result<String, Report>> + Send;++ /// Get the attributes of an existing SNS endpoint.+ fn get_endpoint_attributes(&self,endpoint_arn: &str,+ ) -> impl Future<Output = Result<HashMap<String, String>, Report>> + Send;++ /// Set/update attributes on an existing SNS endpoint.+ fn set_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ attributes: HashMap<String, String>,) -> impl Future<Output = Result<(), Report>> + Send;-}-/// Port for deleting an SNS platform endpoint.-pub trait SnsEndpointDeleter: Send + Sync + 'static {/// Delete an SNS platform endpoint by its ARN.fn delete_endpoint(&self,diff --git a/rust/cloud-storage/notification/src/domain/service.rs b/rust/cloud-storage/notification/src/domain/service.rsindex 4992aaf989..4bea539efd 100644--- a/rust/cloud-storage/notification/src/domain/service.rs+++ b/rust/cloud-storage/notification/src/domain/service.rs@@ -4,6 +4,7 @@//! - [`NotificationIngressService`]: For callers to send notifications (filter, persist, publish to queue)//! - [`NotificationEgressService`]: For workers to deliver notifications (consume from queue, deliver)+pub mod device;mod egress;mod ingress;mod push_notification_event;@@ -17,6 +18,7 @@ pub use ingress::NotificationIngress;pub use ingress::NotificationIngressService;pub use ingress::NotificationReader;pub use ingress::NotificationReaderService;+pub use ingress::PlatformArnConfig;pub use push_notification_event::PushNotificationEventHandler;pub use push_notification_event::PushNotificationEventService;diff --git a/rust/cloud-storage/notification/src/domain/service/device/mod.rs b/rust/cloud-storage/notification/src/domain/service/device/mod.rsnew file mode 100644index 0000000000..14519bd8bb--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/service/device/mod.rs@@ -0,0 +1,7 @@+//! Device registration domain service.+//!+//! Handles registering and unregistering devices for push notifications,+//! coordinating between the database and SNS platform endpoints.++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rsnew file mode 100644index 0000000000..84f635fd88--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs@@ -0,0 +1,450 @@+use crate::domain::models::device::DeviceType;+use crate::domain::ports::{NotificationQueue, NotificationRepository, SnsEndpointManager};+use crate::domain::service::NotificationReader;+use crate::domain::service::ingress::{NotificationReaderService, PlatformArnConfig};+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use std::collections::HashMap;+use std::sync::Mutex;++fn test_user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").unwrap()+}++// ─── Mocks ───────────────────────────────────────────────────────────────++/// Mock NotificationRepository that only implements device-related methods.+struct MockNotifRepo {+ existing_endpoint: Mutex<Option<String>>,+ upserted: Mutex<Vec<(String, String, String, String)>>,+ deleted_token_result: Mutex<Result<String, &'static str>>,+}++impl MockNotifRepo {+ fn with_existing_endpoint(endpoint: &str) -> Self {+ Self {+ existing_endpoint: Mutex::new(Some(endpoint.to_string())),+ upserted: Mutex::new(Vec::new()),+ deleted_token_result: Mutex::new(Ok("arn:default".to_string())),+ }+ }++ fn empty() -> Self {+ Self {+ existing_endpoint: Mutex::new(None),+ upserted: Mutex::new(Vec::new()),+ deleted_token_result: Mutex::new(Ok("arn:default".to_string())),+ }+ }++ fn with_delete_result(mut self, result: Result<String, &'static str>) -> Self {+ self.deleted_token_result = Mutex::new(result);+ self+ }+}++impl NotificationRepository for MockNotifRepo {+ async fn get_device_endpoint(&self, _device_token: &str) -> Result<Option<String>, Report> {+ Ok(self.existing_endpoint.lock().unwrap().clone())+ }++ async fn upsert_device(+ &self,+ user_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ device_token: &str,+ device_endpoint: &str,+ device_type: &DeviceType,+ ) -> Result<(), Report> {+ self.upserted.lock().unwrap().push((+ user_id.to_string(),+ device_token.to_string(),+ device_endpoint.to_string(),+ format!("{device_type:?}"),+ ));+ Ok(())+ }++ async fn delete_device_by_token(+ &self,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> Result<String, Report> {+ self.deleted_token_result+ .lock()+ .unwrap()+ .clone()+ .map_err(|e| rootcause::report!("{e}"))+ }++ async fn delete_device_by_endpoint(&self, _: &str) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_muted_users<'a>(+ &self,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<std::collections::HashSet<macro_user_id::user_id::MacroUserIdStr<'static>>, Report>+ {+ unimplemented!()+ }+ async fn get_unsubscribed_users<'a>(+ &self,+ _: &str,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<std::collections::HashSet<macro_user_id::user_id::MacroUserIdStr<'static>>, Report>+ {+ unimplemented!()+ }+ async fn create_notification<'a, T: crate::domain::models::Notification + Send + Sync>(+ &self,+ _: crate::domain::models::SendNotificationRequestBuilder<'a, T>,+ _: uuid::Uuid,+ _: &str,+ _: Option<&str>,+ ) -> Result<Option<Vec<crate::domain::models::UserNotificationRow<std::sync::Arc<T>>>>, Report>+ {+ unimplemented!()+ }+ async fn update_sent_status<'a>(+ &self,+ _: uuid::Uuid,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_device_endpoints<'a>(+ &self,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<+ std::collections::HashMap<+ macro_user_id::user_id::MacroUserIdStr<'static>,+ Vec<crate::domain::models::DeviceEndpoint>,+ >,+ Report,+ > {+ unimplemented!()+ }+ async fn mark_notifications_seen(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn mark_notifications_done(+ &self,+ _: ¯o_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ _: bool,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_basic_notifications(+ &self,+ _: &[uuid::Uuid],+ ) -> Result<Vec<crate::domain::models::NotificationIdAndCollapseKey>, Report> {+ unimplemented!()+ }+ async fn get_user_notifications<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: u32,+ _: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn get_user_notifications_by_event_item_ids<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ _: u32,+ _: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn get_user_notification_by_id<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: uuid::Uuid,+ ) -> Result<Option<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn delete_user_notification(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: uuid::Uuid,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn bulk_delete_user_notifications(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn delete_all_user_notifications(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ ) -> Result<(), Report> {+ unimplemented!()+ }+}++struct MockSnsManager {+ created_endpoint: String,+ attributes: Mutex<HashMap<String, String>>,+ set_calls: Mutex<Vec<(String, HashMap<String, String>)>>,+ deleted: Mutex<Vec<String>>,+ get_fails: bool,+ should_fail: bool,+}++impl MockSnsManager {+ fn new() -> Self {+ Self {+ created_endpoint: "arn:new-endpoint".to_string(),+ attributes: Mutex::new(HashMap::from([+ ("Enabled".to_string(), "true".to_string()),+ ("Token".to_string(), "device-token".to_string()),+ ])),+ set_calls: Mutex::new(Vec::new()),+ deleted: Mutex::new(Vec::new()),+ get_fails: false,+ should_fail: false,+ }+ }++ fn with_attributes(self, attrs: HashMap<String, String>) -> Self {+ *self.attributes.lock().unwrap() = attrs;+ self+ }++ fn with_get_fails(mut self) -> Self {+ self.get_fails = true;+ self+ }+}++impl SnsEndpointManager for MockSnsManager {+ async fn create_platform_endpoint(+ &self,+ _platform_arn: &str,+ _token: &str,+ ) -> Result<String, Report> {+ Ok(self.created_endpoint.clone())+ }++ async fn get_endpoint_attributes(+ &self,+ _endpoint_arn: &str,+ ) -> Result<HashMap<String, String>, Report> {+ if self.get_fails {+ return Err(rootcause::report!("get_endpoint_attributes failed"));+ }+ Ok(self.attributes.lock().unwrap().clone())+ }++ async fn set_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ attributes: HashMap<String, String>,+ ) -> Result<(), Report> {+ self.set_calls+ .lock()+ .unwrap()+ .push((endpoint_arn.to_string(), attributes));+ Ok(())+ }++ async fn delete_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ if self.should_fail {+ return Err(rootcause::report!("delete_endpoint failed"));+ }+ self.deleted.lock().unwrap().push(endpoint_arn.to_string());+ Ok(())+ }+}++/// No-op mock for NotificationQueue.+struct MockQueue;++impl NotificationQueue for MockQueue {+ async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(+ &self,+ _: impl Iterator<Item = crate::domain::models::queue_message::QueueMessage<'a, T, U>> + Send,+ ) -> Result<(), Report> {+ Ok(())+ }+ async fn receive_messages(+ &self,+ ) -> Result<Vec<crate::domain::models::queue_message::RawQueueMessage>, Report> {+ Ok(Vec::new())+ }+ async fn delete_message(&self, _: &str) -> Result<(), Report> {+ Ok(())+ }+}++fn test_config() -> PlatformArnConfig {+ PlatformArnConfig {+ apns_platform_arn: "arn:apns".to_string(),+ fcm_platform_arn: "arn:fcm".to_string(),+ }+}++fn make_service(+ db: MockNotifRepo,+ sns: MockSnsManager,+) -> NotificationReaderService<MockNotifRepo, MockQueue, MockSnsManager> {+ NotificationReaderService::new(db, MockQueue, sns, test_config())+}++// ─── Register Tests ──────────────────────────────────────────────────────++#[tokio::test]+async fn register_existing_token_valid_endpoint() {+ let db = MockNotifRepo::with_existing_endpoint("arn:existing");+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .register_device(+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ "device-token",+ &DeviceType::Ios,+ )+ .await+ .unwrap();++ let upserted = service.repository.upserted.lock().unwrap();+ assert_eq!(upserted.len(), 1);+ assert_eq!(upserted[0].2, "arn:existing");+}++#[tokio::test]+async fn register_missing_token_creates_endpoint() {+ let db = MockNotifRepo::empty();+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();++ let upserted = service.repository.upserted.lock().unwrap();+ assert_eq!(upserted.len(), 1);+ assert_eq!(upserted[0].2, "arn:new-endpoint");+}++#[tokio::test]+async fn register_get_attributes_fails_creates_new_endpoint() {+ let db = MockNotifRepo::with_existing_endpoint("arn:existing");+ let sns = MockSnsManager::new().with_get_fails();+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();++ let upserted = service.repository.upserted.lock().unwrap();+ assert_eq!(upserted[0].2, "arn:new-endpoint");+}++#[tokio::test]+async fn register_disabled_endpoint_re_enables() {+ let db = MockNotifRepo::with_existing_endpoint("arn:existing");+ let sns = MockSnsManager::new().with_attributes(HashMap::from([+ ("Enabled".to_string(), "false".to_string()),+ ("Token".to_string(), "device-token".to_string()),+ ]));+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "device-token", &DeviceType::Ios)+ .await+ .unwrap();++ let set_calls = service.sns_endpoint.set_calls.lock().unwrap();+ assert_eq!(set_calls.len(), 1);+ assert_eq!(set_calls[0].0, "arn:existing");+ assert_eq!(set_calls[0].1.get("Enabled").unwrap(), "true");+}++#[tokio::test]+async fn register_token_mismatch_updates() {+ let db = MockNotifRepo::with_existing_endpoint("arn:existing");+ let sns = MockSnsManager::new().with_attributes(HashMap::from([+ ("Enabled".to_string(), "true".to_string()),+ ("Token".to_string(), "old-token".to_string()),+ ]));+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "new-token", &DeviceType::Ios)+ .await+ .unwrap();++ let set_calls = service.sns_endpoint.set_calls.lock().unwrap();+ assert_eq!(set_calls.len(), 1);+ assert_eq!(set_calls[0].1.get("Token").unwrap(), "new-token");+}++#[tokio::test]+async fn register_ios_uses_apns_arn() {+ let db = MockNotifRepo::empty();+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "token", &DeviceType::Ios)+ .await+ .unwrap();+}++#[tokio::test]+async fn register_android_uses_fcm_arn() {+ let db = MockNotifRepo::empty();+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .register_device(test_user_id(), "token", &DeviceType::Android)+ .await+ .unwrap();+}++// ─── Unregister Tests ────────────────────────────────────────────────────++#[tokio::test]+async fn unregister_happy_path() {+ let db = MockNotifRepo::empty().with_delete_result(Ok("arn:to-delete".to_string()));+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ service+ .unregister_device("device-token", &DeviceType::Ios)+ .await+ .unwrap();++ let deleted = service.sns_endpoint.deleted.lock().unwrap();+ assert_eq!(deleted.len(), 1);+ assert_eq!(deleted[0], "arn:to-delete");+}++#[tokio::test]+async fn unregister_db_error_propagates() {+ let db = MockNotifRepo::empty().with_delete_result(Err("device not found"));+ let sns = MockSnsManager::new();+ let service = make_service(db, sns);++ let result = service+ .unregister_device("device-token", &DeviceType::Ios)+ .await;++ assert!(result.is_err());+ // SNS delete should not have been called+ let deleted = service.sns_endpoint.deleted.lock().unwrap();+ assert!(deleted.is_empty());+}diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex 704b001ccc..c1f1f3aa58 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -4,6 +4,7 @@//! filtering recipients, persisting to DB, and publishing to the queue.use crate::domain::models::apple::{APNSPushNotification, Aps};+use crate::domain::models::device::DeviceType;use crate::domain::models::email_notification_digest::BulkDigestStateMachine;use crate::domain::models::mobile::{MessageAttributes, PushType};use crate::domain::models::queue_message::{@@ -16,7 +17,7 @@ use crate::domain::models::request::{use crate::domain::models::{DeviceEndpoint, Notification, NotificationResult, SendNotificationRequest, UserNotificationRow,};-use crate::domain::ports::{NotificationQueue, NotificationRepository};+use crate::domain::ports::{NotificationQueue, NotificationRepository, SnsEndpointManager};use crate::domain::service::SendNotificationError;use ::futures::future::join_all;use macro_user_id::cowlike::CowLike;@@ -26,7 +27,7 @@ use rootcause::Report;use rootcause::prelude::ResultExt;use serde::Serialize;use serde::de::DeserializeOwned;-use std::collections::HashSet;+use std::collections::{HashMap, HashSet};use uuid::Uuid;/// Trait for sending notifications through the ingress service.@@ -90,6 +91,27 @@ pub trait NotificationReader: Send + Sync + 'static {user_id: MacroUserIdStr<'_>,notification_ids: &[Uuid],) -> impl Future<Output = Result<(), Report>> + Send;++ /// Register a device for push notifications.+ ///+ /// Resolves the SNS platform endpoint (creating or re-enabling as needed),+ /// then upserts the device registration in the database.+ fn register_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_type: &DeviceType,+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;++ /// Unregister a device from push notifications.+ ///+ /// Deletes the device registration from the database (by token + type),+ /// then deletes the SNS endpoint.+ fn unregister_device(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;}/// Service for sending notifications (ingress side).@@ -317,23 +339,44 @@ where}}+/// Configuration for SNS platform ARNs.+pub struct PlatformArnConfig {+ /// SNS platform ARN for iOS (APNS).+ pub apns_platform_arn: String,+ /// SNS platform ARN for Android (FCM).+ pub fcm_platform_arn: String,+}+/// Service for reading and updating notifications.////// Handles notification queries, status updates, and deletion./// Does not require a bulk-digest state machine.-pub struct NotificationReaderService<N, Q> {- repository: N,- queue: Q,+pub struct NotificationReaderService<N, Q, S> {+ pub(crate) repository: N,+ pub(crate) queue: Q,+ pub(crate) sns_endpoint: S,+ pub(crate) platform_config: PlatformArnConfig,}-impl<N, Q> NotificationReaderService<N, Q>+impl<N, Q, S> NotificationReaderService<N, Q, S>whereN: NotificationRepository,Q: NotificationQueue,+ S: SnsEndpointManager,{/// Create a new reader service.- pub fn new(repository: N, queue: Q) -> Self {- Self { repository, queue }+ pub fn new(+ repository: N,+ queue: Q,+ sns_endpoint: S,+ platform_config: PlatformArnConfig,+ ) -> Self {+ Self {+ repository,+ queue,+ sns_endpoint,+ platform_config,+ }}/// Update notification status for a user and optionally enqueue push notification clearing.@@ -352,7 +395,7 @@ wherematch &req.status {NotificationStatus::Seen => {self.repository- .mark_notifications_seen(&req.user_id, req.notification_ids)+ .mark_notifications_seen(req.user_id.copied(), req.notification_ids).await?;}NotificationStatus::Done(done) => {@@ -439,10 +482,11 @@ where}}-impl<N, Q> NotificationReader for NotificationReaderService<N, Q>+impl<N, Q, S> NotificationReader for NotificationReaderService<N, Q, S>whereN: NotificationRepository,Q: NotificationQueue,+ S: SnsEndpointManager,{fn update_notifications(&self,@@ -532,4 +576,76 @@ where.bulk_delete_user_notifications(user_id, notification_ids).await}++ #[tracing::instrument(err, skip(self))]+ async fn register_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<(), Report> {+ let platform_arn = match device_type {+ DeviceType::Ios => &self.platform_config.apns_platform_arn,+ DeviceType::Android => &self.platform_config.fcm_platform_arn,+ };++ // Get endpoint if exists, otherwise create new one+ let endpoint = match self.repository.get_device_endpoint(device_token).await {+ Ok(Some(endpoint)) => endpoint,+ _ => {+ self.sns_endpoint+ .create_platform_endpoint(platform_arn, device_token)+ .await?+ }+ };++ // Verify endpoint validity, update or create new endpoint if needed+ let endpoint = match self.sns_endpoint.get_endpoint_attributes(&endpoint).await {+ Err(_) => {+ self.sns_endpoint+ .create_platform_endpoint(platform_arn, device_token)+ .await?+ }+ Ok(attributes) => match (attributes.get("Enabled"), attributes.get("Token")) {+ (Some(endpoint_enabled), Some(endpoint_token))+ if endpoint_enabled == "false" || endpoint_token != device_token =>+ {+ self.sns_endpoint+ .set_endpoint_attributes(+ &endpoint,+ HashMap::from([+ ("Enabled".to_string(), "true".to_string()),+ ("Token".to_string(), device_token.to_string()),+ ]),+ )+ .await?;++ endpoint+ }+ _ => endpoint,+ },+ };++ self.repository+ .upsert_device(user_id, device_token, &endpoint, device_type)+ .await?;++ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn unregister_device(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<(), Report> {+ let endpoint = self+ .repository+ .delete_device_by_token(device_token, device_type)+ .await?;++ self.sns_endpoint.delete_endpoint(&endpoint).await?;++ Ok(())+ }}diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rsindex 0df723b85f..27acc97cae 100644--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/mod.rs@@ -9,7 +9,7 @@ mod test;use crate::domain::models::email_notification_digest::BulkDigestFailureStateMachine;use crate::domain::models::push_notification_event::SnsPushNotificationEvent;-use crate::domain::ports::{DeviceRegistrationDeleter, SnsEndpointDeleter};+use crate::domain::ports::{NotificationRepository, SnsEndpointManager};use rootcause::Report;use std::future::Future;@@ -28,34 +28,34 @@ pub trait PushNotificationEventHandler: Send + Sync + 'static {/// Service for handling SNS push notification platform events.///-/// Generic over three outbound ports: device registration deletion (DB),-/// SNS endpoint deletion, and digest failure state machine.-pub struct PushNotificationEventService<D, S, F> {- device_deleter: D,- sns_deleter: S,+/// Generic over three outbound ports: notification repository (DB device deletion),+/// SNS endpoint manager (endpoint deletion), and digest failure state machine.+pub struct PushNotificationEventService<N, S, F> {+ repository: N,+ sns_manager: S,digest_failure_sm: F,}-impl<D, S, F> PushNotificationEventService<D, S, F>+impl<N, S, F> PushNotificationEventService<N, S, F>where- D: DeviceRegistrationDeleter,- S: SnsEndpointDeleter,+ N: NotificationRepository,+ S: SnsEndpointManager,F: BulkDigestFailureStateMachine,{/// Create a new push notification event service.- pub fn new(device_deleter: D, sns_deleter: S, digest_failure_sm: F) -> Self {+ pub fn new(repository: N, sns_manager: S, digest_failure_sm: F) -> Self {Self {- device_deleter,- sns_deleter,+ repository,+ sns_manager,digest_failure_sm,}}}-impl<D, S, F> PushNotificationEventHandler for PushNotificationEventService<D, S, F>+impl<N, S, F> PushNotificationEventHandler for PushNotificationEventService<N, S, F>where- D: DeviceRegistrationDeleter,- S: SnsEndpointDeleter,+ N: NotificationRepository,+ S: SnsEndpointManager,F: BulkDigestFailureStateMachine,{#[tracing::instrument(err, skip(self))]@@ -68,13 +68,13 @@ where"deleting endpoint");- self.device_deleter+ self.repository.delete_device_by_endpoint(&event.endpoint_arn).await?;match event.event_type {EventType::DeliveryFailure => {- self.sns_deleter+ self.sns_manager.delete_endpoint(&event.endpoint_arn).await?;diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rsindex 07780465d7..eab3b61108 100644--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs@@ -4,17 +4,18 @@ use crate::domain::models::email_notification_digest::{BulkDigestFailureStateMachine, StateMachineDecisionC,};use crate::domain::models::push_notification_event::{EventType, SnsPushNotificationEvent};-use crate::domain::ports::{DeviceRegistrationDeleter, SnsEndpointDeleter};+use crate::domain::ports::{NotificationRepository, SnsEndpointManager};use rootcause::Report;+use std::collections::HashMap;use std::sync::Mutex;-/// Mock device registration deleter that tracks calls.-struct MockDeviceDeleter {+/// Mock notification repository that only implements delete_device_by_endpoint.+struct MockNotifRepo {deleted_endpoints: Mutex<Vec<String>>,should_fail: bool,}-impl MockDeviceDeleter {+impl MockNotifRepo {fn new() -> Self {Self {deleted_endpoints: Mutex::new(Vec::new()),@@ -34,7 +35,7 @@ impl MockDeviceDeleter {}}-impl DeviceRegistrationDeleter for MockDeviceDeleter {+impl NotificationRepository for MockNotifRepo {async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {self.deleted_endpoints.lock()@@ -45,15 +46,144 @@ impl DeviceRegistrationDeleter for MockDeviceDeleter {}Ok(())}++ async fn get_muted_users<'a>(+ &self,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<std::collections::HashSet<macro_user_id::user_id::MacroUserIdStr<'static>>, Report>+ {+ unimplemented!()+ }+ async fn get_unsubscribed_users<'a>(+ &self,+ _: &str,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<std::collections::HashSet<macro_user_id::user_id::MacroUserIdStr<'static>>, Report>+ {+ unimplemented!()+ }+ async fn create_notification<'a, T: crate::domain::models::Notification + Send + Sync>(+ &self,+ _: crate::domain::models::SendNotificationRequestBuilder<'a, T>,+ _: uuid::Uuid,+ _: &str,+ _: Option<&str>,+ ) -> Result<Option<Vec<crate::domain::models::UserNotificationRow<std::sync::Arc<T>>>>, Report>+ {+ unimplemented!()+ }+ async fn update_sent_status<'a>(+ &self,+ _: uuid::Uuid,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_device_endpoints<'a>(+ &self,+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ ) -> Result<+ std::collections::HashMap<+ macro_user_id::user_id::MacroUserIdStr<'static>,+ Vec<crate::domain::models::DeviceEndpoint>,+ >,+ Report,+ > {+ unimplemented!()+ }+ async fn mark_notifications_seen(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn mark_notifications_done(+ &self,+ _: ¯o_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ _: bool,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_basic_notifications(+ &self,+ _: &[uuid::Uuid],+ ) -> Result<Vec<crate::domain::models::NotificationIdAndCollapseKey>, Report> {+ unimplemented!()+ }+ async fn get_user_notifications<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: u32,+ _: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn get_user_notifications_by_event_item_ids<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ _: u32,+ _: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn get_user_notification_by_id<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: uuid::Uuid,+ ) -> Result<Option<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn delete_user_notification(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: uuid::Uuid,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn bulk_delete_user_notifications(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn delete_all_user_notifications(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_device_endpoint(&self, _: &str) -> Result<Option<String>, Report> {+ unimplemented!()+ }+ async fn upsert_device(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ _: &str,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn delete_device_by_token(+ &self,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ ) -> Result<String, Report> {+ unimplemented!()+ }}-/// Mock SNS endpoint deleter that tracks calls.-struct MockSnsDeleter {+/// Mock SNS endpoint manager that only implements delete_endpoint.+struct MockSnsManager {deleted_endpoints: Mutex<Vec<String>>,should_fail: bool,}-impl MockSnsDeleter {+impl MockSnsManager {fn new() -> Self {Self {deleted_endpoints: Mutex::new(Vec::new()),@@ -73,7 +203,7 @@ impl MockSnsDeleter {}}-impl SnsEndpointDeleter for MockSnsDeleter {+impl SnsEndpointManager for MockSnsManager {async fn delete_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {self.deleted_endpoints.lock()@@ -84,6 +214,20 @@ impl SnsEndpointDeleter for MockSnsDeleter {}Ok(())}++ async fn create_platform_endpoint(&self, _: &str, _: &str) -> Result<String, Report> {+ unimplemented!()+ }+ async fn get_endpoint_attributes(&self, _: &str) -> Result<HashMap<String, String>, Report> {+ unimplemented!()+ }+ async fn set_endpoint_attributes(+ &self,+ _: &str,+ _: HashMap<String, String>,+ ) -> Result<(), Report> {+ unimplemented!()+ }}/// Mock digest failure state machine that tracks calls.@@ -127,10 +271,10 @@ impl BulkDigestFailureStateMachine for MockDigestFailureStateMachine {#[tokio::test]async fn test_delivery_failure_deletes_device_and_sns_endpoint() {- let device_deleter = MockDeviceDeleter::new();- let sns_deleter = MockSnsDeleter::new();+ let repository = MockNotifRepo::new();+ let sns_manager = MockSnsManager::new();let digest_sm = MockDigestFailureStateMachine::new();- let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);+ let service = PushNotificationEventService::new(repository, sns_manager, digest_sm);let event = SnsPushNotificationEvent {endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),@@ -141,18 +285,18 @@ async fn test_delivery_failure_deletes_device_and_sns_endpoint() {service.handle_event(&event).await.unwrap();assert_eq!(- service.device_deleter.get_deleted(),+ service.repository.get_deleted(),vec![event.endpoint_arn.clone()]);- assert_eq!(service.sns_deleter.get_deleted(), vec![event.endpoint_arn]);+ assert_eq!(service.sns_manager.get_deleted(), vec![event.endpoint_arn]);}#[tokio::test]async fn test_endpoint_deleted_only_deletes_device() {- let device_deleter = MockDeviceDeleter::new();- let sns_deleter = MockSnsDeleter::new();+ let repository = MockNotifRepo::new();+ let sns_manager = MockSnsManager::new();let digest_sm = MockDigestFailureStateMachine::new();- let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);+ let service = PushNotificationEventService::new(repository, sns_manager, digest_sm);let event = SnsPushNotificationEvent {endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),@@ -162,22 +306,19 @@ async fn test_endpoint_deleted_only_deletes_device() {service.handle_event(&event).await.unwrap();- assert_eq!(- service.device_deleter.get_deleted(),- vec![event.endpoint_arn]- );+ assert_eq!(service.repository.get_deleted(), vec![event.endpoint_arn]);assert!(- service.sns_deleter.get_deleted().is_empty(),+ service.sns_manager.get_deleted().is_empty(),"SNS endpoint should not be deleted for EndpointDeleted events");}#[tokio::test]async fn test_device_deletion_failure_propagates_error() {- let device_deleter = MockDeviceDeleter::failing();- let sns_deleter = MockSnsDeleter::new();+ let repository = MockNotifRepo::failing();+ let sns_manager = MockSnsManager::new();let digest_sm = MockDigestFailureStateMachine::new();- let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);+ let service = PushNotificationEventService::new(repository, sns_manager, digest_sm);let event = SnsPushNotificationEvent {endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),@@ -190,17 +331,17 @@ async fn test_device_deletion_failure_propagates_error() {// SNS deletion should not be attempted when DB deletion failsassert!(- service.sns_deleter.get_deleted().is_empty(),+ service.sns_manager.get_deleted().is_empty(),"SNS endpoint should not be deleted when device deletion fails");}#[tokio::test]async fn test_sns_deletion_failure_propagates_error() {- let device_deleter = MockDeviceDeleter::new();- let sns_deleter = MockSnsDeleter::failing();+ let repository = MockNotifRepo::new();+ let sns_manager = MockSnsManager::failing();let digest_sm = MockDigestFailureStateMachine::new();- let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);+ let service = PushNotificationEventService::new(repository, sns_manager, digest_sm);let event = SnsPushNotificationEvent {endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),@@ -212,18 +353,15 @@ async fn test_sns_deletion_failure_propagates_error() {assert!(result.is_err());// Device should still have been deleted before the SNS failure- assert_eq!(- service.device_deleter.get_deleted(),- vec![event.endpoint_arn]- );+ assert_eq!(service.repository.get_deleted(), vec![event.endpoint_arn]);}#[tokio::test]async fn test_delivery_failure_calls_digest_state_machine() {- let device_deleter = MockDeviceDeleter::new();- let sns_deleter = MockSnsDeleter::new();+ let repository = MockNotifRepo::new();+ let sns_manager = MockSnsManager::new();let digest_sm = MockDigestFailureStateMachine::new();- let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);+ let service = PushNotificationEventService::new(repository, sns_manager, digest_sm);let event = SnsPushNotificationEvent {endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),@@ -238,10 +376,10 @@ async fn test_delivery_failure_calls_digest_state_machine() {#[tokio::test]async fn test_endpoint_deleted_does_not_call_digest_state_machine() {- let device_deleter = MockDeviceDeleter::new();- let sns_deleter = MockSnsDeleter::new();+ let repository = MockNotifRepo::new();+ let sns_manager = MockSnsManager::new();let digest_sm = MockDigestFailureStateMachine::new();- let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);+ let service = PushNotificationEventService::new(repository, sns_manager, digest_sm);let event = SnsPushNotificationEvent {endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),@@ -259,10 +397,10 @@ async fn test_endpoint_deleted_does_not_call_digest_state_machine() {#[tokio::test]async fn test_digest_state_machine_failure_does_not_propagate() {- let device_deleter = MockDeviceDeleter::new();- let sns_deleter = MockSnsDeleter::new();+ let repository = MockNotifRepo::new();+ let sns_manager = MockSnsManager::new();let digest_sm = MockDigestFailureStateMachine::failing();- let service = PushNotificationEventService::new(device_deleter, sns_deleter, digest_sm);+ let service = PushNotificationEventService::new(repository, sns_manager, digest_sm);let event = SnsPushNotificationEvent {endpoint_arn: "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),@@ -276,8 +414,8 @@ async fn test_digest_state_machine_failure_does_not_propagate() {assert_eq!(service.digest_failure_sm.get_calls(), vec!["msg-789"]);assert_eq!(- service.device_deleter.get_deleted(),+ service.repository.get_deleted(),vec![event.endpoint_arn.clone()]);- assert_eq!(service.sns_deleter.get_deleted(), vec![event.endpoint_arn]);+ assert_eq!(service.sns_manager.get_deleted(), vec![event.endpoint_arn]);}diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex a3a854873e..470ad5a26c 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -1,6 +1,7 @@//! Unit tests for the notification services.use crate::domain::models::apple::APNSPushNotification;+use crate::domain::models::device::DeviceType;use crate::domain::models::email_notification_digest::BulkDigestStateMachine;use crate::domain::models::email_notification_digest::ports::DigestBatch;use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatcher};@@ -17,11 +18,11 @@ use crate::domain::models::{};use crate::domain::ports::{EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,- RateLimitPort, WebSocketSender,+ RateLimitPort, SnsEndpointManager, WebSocketSender,};use crate::domain::service::{NotificationEgressService, NotificationIngress, NotificationIngressService, NotificationReader,- NotificationReaderService,+ NotificationReaderService, PlatformArnConfig,};use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;@@ -231,7 +232,7 @@ impl NotificationRepository for MockRepository {async fn mark_notifications_seen(&self,- user_id: &MacroUserIdStr<'_>,+ user_id: MacroUserIdStr<'_>,notification_ids: &[Uuid],) -> Result<(), Report> {self.mark_seen_calls@@ -311,6 +312,32 @@ impl NotificationRepository for MockRepository {) -> Result<(), Report> {Ok(())}++ async fn get_device_endpoint(&self, _device_token: &str) -> Result<Option<String>, Report> {+ Ok(None)+ }++ async fn upsert_device(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _device_token: &str,+ _device_endpoint: &str,+ _device_type: &DeviceType,+ ) -> Result<(), Report> {+ Ok(())+ }++ async fn delete_device_by_token(+ &self,+ _device_token: &str,+ _device_type: &DeviceType,+ ) -> Result<String, Report> {+ Ok(String::new())+ }++ async fn delete_device_by_endpoint(&self, _endpoint_arn: &str) -> Result<(), Report> {+ Ok(())+ }}impl NotificationRepository for std::sync::Arc<MockRepository> {@@ -358,7 +385,7 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {async fn mark_notifications_seen(&self,- user_id: &MacroUserIdStr<'_>,+ user_id: MacroUserIdStr<'_>,notification_ids: &[Uuid],) -> Result<(), Report> {(**self)@@ -443,6 +470,36 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {) -> Result<(), Report> {(**self).delete_all_user_notifications(user_id).await}++ async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {+ (**self).get_device_endpoint(device_token).await+ }++ async fn upsert_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_endpoint: &str,+ device_type: &DeviceType,+ ) -> Result<(), Report> {+ (**self)+ .upsert_device(user_id, device_token, device_endpoint, device_type)+ .await+ }++ async fn delete_device_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<String, Report> {+ (**self)+ .delete_device_by_token(device_token, device_type)+ .await+ }++ async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ (**self).delete_device_by_endpoint(endpoint_arn).await+ }}/// Mock queue that tracks published messages.@@ -502,6 +559,45 @@ impl NotificationQueue for std::sync::Arc<MockQueue> {}}+/// No-op mock for SNS endpoint management used in reader service tests.+struct MockSnsEndpoint;++impl SnsEndpointManager for MockSnsEndpoint {+ async fn create_platform_endpoint(+ &self,+ _platform_arn: &str,+ _token: &str,+ ) -> Result<String, Report> {+ Ok(String::new())+ }++ async fn get_endpoint_attributes(+ &self,+ _endpoint_arn: &str,+ ) -> Result<HashMap<String, String>, Report> {+ Ok(HashMap::new())+ }++ async fn set_endpoint_attributes(+ &self,+ _endpoint_arn: &str,+ _attributes: HashMap<String, String>,+ ) -> Result<(), Report> {+ Ok(())+ }++ async fn delete_endpoint(&self, _endpoint_arn: &str) -> Result<(), Report> {+ Ok(())+ }+}++fn test_platform_config() -> PlatformArnConfig {+ PlatformArnConfig {+ apns_platform_arn: "arn:aws:sns:us-east-1:000:app/APNS/test".to_string(),+ fcm_platform_arn: "arn:aws:sns:us-east-1:000:app/GCM/test".to_string(),+ }+}+#[tokio::test]async fn test_send_notification_success() {let service =@@ -1171,7 +1267,12 @@ async fn test_mark_seen_publishes_ios_clear_message() {),);let queue = Arc::new(MockQueue::new());- let service = NotificationReaderService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(+ repo.clone(),+ queue.clone(),+ MockSnsEndpoint,+ test_platform_config(),+ );let notification_ids = [notif_id];service@@ -1244,7 +1345,12 @@ async fn test_mark_seen_skips_push_when_no_collapse_key() {DeviceEndpoint::Ios("arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob".to_string()),));let queue = Arc::new(MockQueue::new());- let service = NotificationReaderService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(+ repo.clone(),+ queue.clone(),+ MockSnsEndpoint,+ test_platform_config(),+ );let notification_ids = [notif_id];service@@ -1280,7 +1386,12 @@ async fn test_mark_seen_skips_push_when_no_device_endpoints() {// No device endpoints registered);let queue = Arc::new(MockQueue::new());- let service = NotificationReaderService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(+ repo.clone(),+ queue.clone(),+ MockSnsEndpoint,+ test_platform_config(),+ );let notification_ids = [notif_id];service@@ -1322,7 +1433,12 @@ async fn test_mark_done_updates_db_and_clears_push() {),);let queue = Arc::new(MockQueue::new());- let service = NotificationReaderService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(+ repo.clone(),+ queue.clone(),+ MockSnsEndpoint,+ test_platform_config(),+ );let notification_ids = [notif_id];service@@ -1367,7 +1483,12 @@ async fn test_mark_undone_updates_db_no_push_clear() {),);let queue = Arc::new(MockQueue::new());- let service = NotificationReaderService::new(repo.clone(), queue.clone());+ let service = NotificationReaderService::new(+ repo.clone(),+ queue.clone(),+ MockSnsEndpoint,+ test_platform_config(),+ );let notification_ids = [notif_id];servicediff --git a/rust/cloud-storage/notification/src/inbound/http/device.rs b/rust/cloud-storage/notification/src/inbound/http/device.rsnew file mode 100644index 0000000000..65777d4253--- /dev/null+++ b/rust/cloud-storage/notification/src/inbound/http/device.rs@@ -0,0 +1,69 @@+//! HTTP handlers for device registration.++use axum::{+ Json, Router,+ extract::State,+ routing::{delete, post},+};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;+use reqwest::StatusCode;++use crate::domain::models::device::DeviceRequest;+use crate::domain::service::NotificationReader;+use crate::inbound::http::NotificationRouterState;++/// Construct the device registration router.+pub fn device_router<S: NotificationReader>() -> Router<NotificationRouterState<S>> {+ Router::new()+ .route("/register", post(register_device::<S>))+ .route("/unregister", delete(unregister_device::<S>))+}++/// Register a device for push notifications.+#[tracing::instrument(skip(state, macro_user, req), fields(user_id=?macro_user.macro_user_id))]+async fn register_device<S: NotificationReader>(+ State(state): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Json(req): Json<DeviceRequest>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ state+ .inner+ .register_device(macro_user.macro_user_id, &req.token, &req.device_type)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to register device");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "unable to register device",+ }),+ )+ })?;++ Ok(Json(()))+}++/// Unregister a device from push notifications.+#[tracing::instrument(skip(state, _macro_user, req))]+async fn unregister_device<S: NotificationReader>(+ State(state): State<NotificationRouterState<S>>,+ _macro_user: MacroUserExtractor,+ Json(req): Json<DeviceRequest>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ state+ .inner+ .unregister_device(&req.token, &req.device_type)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to unregister device");+ (+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "device not found",+ }),+ )+ })?;++ Ok(Json(()))+}diff --git a/rust/cloud-storage/notification/src/inbound/http.rs b/rust/cloud-storage/notification/src/inbound/http/mod.rssimilarity index 97%rename from rust/cloud-storage/notification/src/inbound/http.rsrename to rust/cloud-storage/notification/src/inbound/http/mod.rsindex 63e65fa6c9..ad7fd60ccb 100644--- a/rust/cloud-storage/notification/src/inbound/http.rs+++ b/rust/cloud-storage/notification/src/inbound/http/mod.rs@@ -1,9 +1,11 @@//! This module exposes the http adapter for inbound http requests via an axum router+pub mod device;+use axum::{Json, Router,extract::{Path, Query, State},- routing::patch,+ routing::{delete, patch},};use model_error_response::ErrorResponse;use model_user::axum_extractor::MacroUserExtractor;@@ -64,10 +66,14 @@ impl<S: NotificationReader> NotificationRouterState<S> {/// construct the routerpub fn router<S: NotificationReader, T: Serialize + DeserializeOwned + Send + 'static>()-> Router<NotificationRouterState<S>> {- Router::new()- .route("/bulk/seen", patch(bulk_mark_seen))- .route("/bulk/done", patch(bulk_mark_done))- .route("/bulk/undone", patch(bulk_mark_undone))+ Router::new().nest(+ "/bulk",+ Router::new()+ .route("/", delete(bulk_delete_notifications))+ .route("/seen", patch(bulk_mark_seen))+ .route("/done", patch(bulk_mark_done))+ .route("/undone", patch(bulk_mark_undone)),+ )}/// the params for paginationdiff --git a/rust/cloud-storage/notification/src/outbound/device_registration.rs b/rust/cloud-storage/notification/src/outbound/device_registration.rsindex 943c0c0de5..2c5256c5ae 100644--- a/rust/cloud-storage/notification/src/outbound/device_registration.rs+++ b/rust/cloud-storage/notification/src/outbound/device_registration.rs@@ -1,6 +1,7 @@-//! Database adapter for deleting device registrations.+//! Database adapter for device registration operations.-use crate::domain::ports::DeviceRegistrationDeleter;+use crate::domain::models::device::DeviceType;+use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;use sqlx::PgPool;@@ -13,6 +14,28 @@ pub trait DeviceRegistrationDbOps: Send + Sync + 'static {&self,endpoint_arn: &str,) -> impl std::future::Future<Output = Result<(), Report>> + Send;++ /// Look up an existing device endpoint ARN by its device token.+ fn get_device_endpoint(+ &self,+ device_token: &str,+ ) -> impl std::future::Future<Output = Result<Option<String>, Report>> + Send;++ /// Upsert a device registration.+ fn upsert_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_endpoint: &str,+ device_type: &DeviceType,+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;++ /// Delete by token and type, returning the endpoint ARN.+ fn delete_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> impl std::future::Future<Output = Result<String, Report>> + Send;}impl DeviceRegistrationDbOps for PgPool {@@ -29,23 +52,68 @@ impl DeviceRegistrationDbOps for PgPool {Ok(())}-}-/// Database-backed adapter for deleting device registrations.-pub struct DbDeviceRegistrationDeleter<D> {- db: D,-}+ async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {+ let result = sqlx::query!(+ r#"+ SELECT d.device_endpoint+ FROM notification_user_device_registration d+ WHERE d.device_token = $1+ LIMIT 1+ "#,+ device_token+ )+ .map(|row| row.device_endpoint)+ .fetch_optional(self)+ .await?;-impl<D> DbDeviceRegistrationDeleter<D> {- /// Create a new database device registration deleter.- pub fn new(db: D) -> Self {- Self { db }+ Ok(result)}-}-impl<D: DeviceRegistrationDbOps> DeviceRegistrationDeleter for DbDeviceRegistrationDeleter<D> {- #[tracing::instrument(err, skip(self))]- async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {- self.db.delete_by_endpoint(endpoint_arn).await+ async fn upsert_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_endpoint: &str,+ device_type: &DeviceType,+ ) -> Result<(), Report> {+ let id = macro_uuid::generate_uuid_v7();+ let user_id_str = user_id.as_ref();+ sqlx::query!(+ r#"+ INSERT INTO notification_user_device_registration (id, user_id, device_token, device_endpoint, device_type)+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (device_endpoint) DO UPDATE SET user_id = $2, device_token = $3, device_type = $5, updated_at = NOW()+ "#,+ id,+ user_id_str,+ device_token,+ device_endpoint,+ device_type as _,+ )+ .execute(self)+ .await?;++ Ok(())+ }++ async fn delete_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<String, Report> {+ let result = sqlx::query!(+ r#"+ DELETE FROM notification_user_device_registration+ WHERE device_token = $1 AND device_type = $2+ RETURNING device_endpoint+ "#,+ device_token,+ device_type as _,+ )+ .fetch_one(self)+ .await?;++ Ok(result.device_endpoint)}}diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rsindex 5ef9d83c80..e977893393 100644--- a/rust/cloud-storage/notification/src/outbound/repository.rs+++ b/rust/cloud-storage/notification/src/outbound/repository.rs@@ -3,11 +3,13 @@#[cfg(test)]mod test;+use crate::domain::models::device::DeviceType;use crate::domain::models::{DeviceEndpoint, Notification, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,UserNotificationRow,};use crate::domain::ports::NotificationRepository;+use crate::outbound::device_registration::DeviceRegistrationDbOps;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;@@ -51,7 +53,7 @@ impl<D> DbNotificationRepository<D> {/// Trait for database operations needed by the notification repository.////// This allows the adapter to work with different database client implementations.-pub trait NotificationDbOps: Send + Sync + 'static {+pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {/// Get users who have muted all notifications.fn get_muted_users<'a>(&self,@@ -800,11 +802,11 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificatiasync fn mark_notifications_seen(&self,- user_id: &MacroUserIdStr<'_>,+ user_id: MacroUserIdStr<'_>,notification_ids: &[Uuid],) -> Result<(), Report> {self.db- .mark_notifications_seen(user_id, notification_ids)+ .mark_notifications_seen(&user_id, notification_ids).await}@@ -883,4 +885,32 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati) -> Result<(), Report> {self.db.delete_all_user_notifications(user_id).await}++ async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {+ self.db.get_device_endpoint(device_token).await+ }++ async fn upsert_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_endpoint: &str,+ device_type: &DeviceType,+ ) -> Result<(), Report> {+ self.db+ .upsert_device(user_id, device_token, device_endpoint, device_type)+ .await+ }++ async fn delete_device_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<String, Report> {+ self.db.delete_by_token(device_token, device_type).await+ }++ async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ self.db.delete_by_endpoint(endpoint_arn).await+ }}diff --git a/rust/cloud-storage/notification/src/outbound/sns_endpoint.rs b/rust/cloud-storage/notification/src/outbound/sns_endpoint.rsindex 3381b66f8c..de91788e9d 100644--- a/rust/cloud-storage/notification/src/outbound/sns_endpoint.rs+++ b/rust/cloud-storage/notification/src/outbound/sns_endpoint.rs@@ -1,12 +1,34 @@-//! SNS adapter for deleting platform endpoints.+//! SNS adapter for platform endpoint operations.-use crate::domain::ports::SnsEndpointDeleter;+use std::collections::HashMap;++use crate::domain::ports::SnsEndpointManager;use rootcause::Report;-/// Trait for SNS endpoint operations.+/// Trait for SNS endpoint management operations (create, get/set attributes, delete).////// This allows the adapter to work with different SNS client implementations.-pub trait SnsEndpointOps: Send + Sync + 'static {+pub trait SnsEndpointManagementOps: Send + Sync + 'static {+ /// Create a new SNS platform endpoint for the given platform ARN and device token.+ fn create_platform_endpoint(+ &self,+ platform_arn: &str,+ token: &str,+ ) -> impl std::future::Future<Output = Result<String, Report>> + Send;++ /// Get the attributes of an existing SNS endpoint.+ fn get_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ ) -> impl std::future::Future<Output = Result<HashMap<String, String>, Report>> + Send;++ /// Set/update attributes on an existing SNS endpoint.+ fn set_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ attributes: HashMap<String, String>,+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;+/// Delete an SNS platform endpoint by its ARN.fn delete_endpoint(&self,@@ -14,7 +36,55 @@ pub trait SnsEndpointOps: Send + Sync + 'static {) -> impl std::future::Future<Output = Result<(), Report>> + Send;}-impl SnsEndpointOps for aws_sdk_sns::Client {+impl SnsEndpointManagementOps for aws_sdk_sns::Client {+ async fn create_platform_endpoint(+ &self,+ platform_arn: &str,+ token: &str,+ ) -> Result<String, Report> {+ match self+ .create_platform_endpoint()+ .platform_application_arn(platform_arn)+ .token(token)+ .send()+ .await?+ .endpoint_arn()+ {+ Some(endpoint) => Ok(endpoint.to_string()),+ None => Err(rootcause::report!("unable to create platform endpoint")),+ }+ }++ async fn get_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ ) -> Result<HashMap<String, String>, Report> {+ let output = self+ .get_endpoint_attributes()+ .endpoint_arn(endpoint_arn)+ .send()+ .await?;++ match output.attributes() {+ Some(attrs) => Ok(attrs.clone()),+ None => Err(rootcause::report!("unable to get endpoint attributes")),+ }+ }++ async fn set_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ attributes: HashMap<String, String>,+ ) -> Result<(), Report> {+ self.set_endpoint_attributes()+ .endpoint_arn(endpoint_arn)+ .set_attributes(Some(attributes))+ .send()+ .await?;++ Ok(())+ }+async fn delete_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {self.delete_endpoint().endpoint_arn(endpoint_arn)@@ -25,19 +95,47 @@ impl SnsEndpointOps for aws_sdk_sns::Client {}}-/// SNS adapter for deleting platform endpoints.-pub struct SnsEndpointDeletionAdapter<S> {+/// SNS adapter for platform endpoint management.+pub struct SnsEndpointManagerAdapter<S> {sns: S,}-impl<S> SnsEndpointDeletionAdapter<S> {- /// Create a new SNS endpoint deletion adapter.+impl<S> SnsEndpointManagerAdapter<S> {+ /// Create a new SNS endpoint manager adapter.pub fn new(sns: S) -> Self {Self { sns }}}-impl<S: SnsEndpointOps> SnsEndpointDeleter for SnsEndpointDeletionAdapter<S> {+impl<S: SnsEndpointManagementOps> SnsEndpointManager for SnsEndpointManagerAdapter<S> {+ #[tracing::instrument(err, skip(self))]+ async fn create_platform_endpoint(+ &self,+ platform_arn: &str,+ token: &str,+ ) -> Result<String, Report> {+ self.sns.create_platform_endpoint(platform_arn, token).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ ) -> Result<HashMap<String, String>, Report> {+ self.sns.get_endpoint_attributes(endpoint_arn).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn set_endpoint_attributes(+ &self,+ endpoint_arn: &str,+ attributes: HashMap<String, String>,+ ) -> Result<(), Report> {+ self.sns+ .set_endpoint_attributes(endpoint_arn, attributes)+ .await+ }+#[tracing::instrument(err, skip(self))]async fn delete_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {self.sns.delete_endpoint(endpoint_arn).awaitdiff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rsindex 123f88b806..cd1febbb65 100644--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs@@ -2,7 +2,7 @@ use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{CreatedAt, Query};use notification::domain::models::{DeviceEndpoint, Notification, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,- UserNotificationRow,+ UserNotificationRow, device::DeviceType,};use notification::domain::ports::NotificationRepository;use notification::outbound::repository::DbNotificationRepository;@@ -84,7 +84,7 @@ impl NotificationRepository for SandboxNotificationRepository {async fn mark_notifications_seen(&self,- user_id: &MacroUserIdStr<'_>,+ user_id: MacroUserIdStr<'_>,notification_ids: &[Uuid],) -> Result<(), Report> {self.inner@@ -169,4 +169,34 @@ impl NotificationRepository for SandboxNotificationRepository {) -> Result<(), Report> {self.inner.delete_all_user_notifications(user_id).await}++ async fn get_device_endpoint(&self, device_token: &str) -> Result<Option<String>, Report> {+ self.inner.get_device_endpoint(device_token).await+ }++ async fn upsert_device(+ &self,+ user_id: MacroUserIdStr<'_>,+ device_token: &str,+ device_endpoint: &str,+ device_type: &DeviceType,+ ) -> Result<(), Report> {+ self.inner+ .upsert_device(user_id, device_token, device_endpoint, device_type)+ .await+ }++ async fn delete_device_by_token(+ &self,+ device_token: &str,+ device_type: &DeviceType,+ ) -> Result<String, Report> {+ self.inner+ .delete_device_by_token(device_token, device_type)+ .await+ }++ async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {+ self.inner.delete_device_by_endpoint(endpoint_arn).await+ }}diff --git a/rust/cloud-storage/notification_service/src/api/device/mod.rs b/rust/cloud-storage/notification_service/src/api/device/mod.rsdeleted file mode 100644index c0d347501e..0000000000--- a/rust/cloud-storage/notification_service/src/api/device/mod.rs+++ /dev/null@@ -1,20 +0,0 @@-use axum::{- Router,- routing::{delete, post},-};-use tower::ServiceBuilder;--use crate::api::context::ApiContext;--pub(in crate::api) mod register;-pub(in crate::api) mod unregister;-pub fn router() -> Router<ApiContext> {- Router::new()- .route(- "/register",- post(register::handler).layer(ServiceBuilder::new().layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))),- )- .route("/unregister", delete(unregister::handler))-}diff --git a/rust/cloud-storage/notification_service/src/api/device/register.rs b/rust/cloud-storage/notification_service/src/api/device/register.rsdeleted file mode 100644index e4697335f3..0000000000--- a/rust/cloud-storage/notification_service/src/api/device/register.rs+++ /dev/null@@ -1,127 +0,0 @@-use axum::{- Extension, Json,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::{EmptyResponse, ErrorResponse};-use model_notifications::DeviceType;-use notification_db_client::device;-use std::collections::HashMap;--use crate::api::context::ApiContext;-use crate::model::device::DeviceRequest;-use model::user::UserContext;--/// Register a user device for push notifications.-#[utoipa::path(- post,- operation_id = "register_device",- path = "/device/register",- request_body = DeviceRequest,- responses(- (status = 200, body=EmptyResponse),- (status = 401, body=ErrorResponse),- (status = 500, body=ErrorResponse),- (status = 501, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]-pub async fn handler(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- extract::Json(req): extract::Json<DeviceRequest>,-) -> Result<Response, Response> {- let platform_arn = match req.device_type {- DeviceType::Ios => &ctx.config.sns_apns_platform_arn,- DeviceType::Android => &ctx.config.sns_fcm_platform_arn,- };-- // get endpoint if exists, otherwise create new one- let endpoint = match device::get_device_endpoint(&ctx.db, &req.token).await {- Ok(Some(endpoint)) => endpoint,- _ => ctx- .sns_client- .create_platform_endpoint(platform_arn, &req.token)- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to create endpoint for device");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to create endpoint for device",- }),- )- .into_response()- })?,- };-- // verify endpoint validity, update or create new endpoint if needed- let endpoint = match ctx.sns_client.get_endpoint_attributes(&endpoint).await {- Err(e) => {- tracing::error!(error=?e, "unable to get endpoint attributes");- ctx.sns_client- .create_platform_endpoint(platform_arn, &req.token)- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to create endpoint for device");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to get endpoint attributes",- }),- )- .into_response()- })?- }- Ok(attributes) => match (attributes.get("Enabled"), attributes.get("Token")) {- (Some(endpoint_enabled), Some(endpoint_token))- if endpoint_enabled == "false" || endpoint_token != &req.token =>- {- ctx.sns_client- .set_endpoint_attributes(- &endpoint,- HashMap::from([- ("Enabled".to_string(), "true".to_string()),- ("Token".to_string(), req.token.clone()),- ]),- )- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to update endpoint attributes");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to update endpoint attributes",- }),- )- .into_response()- })?;-- endpoint- }- _ => endpoint,- },- };-- device::upsert_user_device(- &ctx.db,- &user_context.user_id,- &req.token,- &endpoint,- &req.device_type,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to register device");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to register device",- }),- )- .into_response()- })?;-- Ok((StatusCode::OK, Json(EmptyResponse {})).into_response())-}diff --git a/rust/cloud-storage/notification_service/src/api/device/unregister.rs b/rust/cloud-storage/notification_service/src/api/device/unregister.rsdeleted file mode 100644index 5c772203c4..0000000000--- a/rust/cloud-storage/notification_service/src/api/device/unregister.rs+++ /dev/null@@ -1,61 +0,0 @@-use axum::{- Extension, Json,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::{EmptyResponse, ErrorResponse};-use notification_db_client::device;--use crate::api::context::ApiContext;-use crate::model::device::DeviceRequest;-use model::user::UserContext;--/// Unregister a device from receiving push notifications.-#[utoipa::path(- delete,- operation_id = "unregister_device",- path = "/device/unregister",- request_body = DeviceRequest,- responses(- (status = 200, body=EmptyResponse),- (status = 401, body=ErrorResponse),- (status = 404, body=ErrorResponse),- (status = 500, body=ErrorResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]-pub async fn handler(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- extract::Json(req): extract::Json<DeviceRequest>,-) -> Result<Response, Response> {- let device_endpoint = device::delete_user_device_token(&ctx.db, &req.token, &req.device_type)- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to delete device token");- (- StatusCode::NOT_FOUND,- Json(ErrorResponse {- message: "device not found",- }),- )- .into_response()- })?;-- ctx.sns_client- .delete_endpoint(&device_endpoint)- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to delete endpoint");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to unregister device",- }),- )- .into_response()- })?;-- Ok((StatusCode::OK, Json(EmptyResponse {})).into_response())-}diff --git a/rust/cloud-storage/notification_service/src/api/mod.rs b/rust/cloud-storage/notification_service/src/api/mod.rsindex ef0e96cdbf..91fe47ab3e 100644--- a/rust/cloud-storage/notification_service/src/api/mod.rs+++ b/rust/cloud-storage/notification_service/src/api/mod.rs@@ -12,7 +12,6 @@ use utoipa_swagger_ui::SwaggerUi;pub mod context;// Routes-mod device;mod health;mod unsubscribe;pub(crate) mod user_notification;@@ -72,11 +71,12 @@ fn api_router<S: ::notification::domain::service::NotificationReader>(};let internal_router = Router::new()- .nest("/device", device::router()).nest(- "/user_notifications",- user_notification::router(ingress_state),+ "/device",+ ::notification::inbound::http::device::device_router(),)+ .nest("/user_notifications", user_notification::router())+ .with_state(ingress_state).nest("/unsubscribe", unsubscribe::router()).layer(middleware);Router::new()diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rsindex 39d0f6453e..2715dd78ef 100644--- a/rust/cloud-storage/notification_service/src/api/swagger.rs+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs@@ -14,11 +14,11 @@ use utoipa::OpenApi;use crate::{api::{- device, health,+ health,unsubscribe::{self, unsubscribe_item::UnsubscribeItemPathParams},user_notification,},- model::{device::DeviceRequest, notification::CreateNotification},+ model::notification::CreateNotification,};#[derive(OpenApi)]@@ -27,10 +27,6 @@ use crate::{terms_of_service = "https://macro.com/terms",),paths(- /// /devices- device::register::handler,- device::unregister::handler,-/// /healthhealth::health_handler,@@ -60,10 +56,10 @@ use crate::{EmptyResponse,ErrorResponse,CreateNotification,+ notification_crate::domain::models::device::DeviceRequest,UnsubscribeItemPathParams,UserUnsubscribe,DeviceType,- DeviceRequest,PushNotificationData,NewEmailMetadata,diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rsindex 5a00e076a0..7f8f323fdb 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs@@ -101,12 +101,8 @@ pub fn to_typed_row(////// Instantiates the notification crate's generic router, then overwrites the/// GET `/` route with a wrapper that deserializes each row into [`NotifEvent`].-pub fn router<- S: ::notification::domain::service::NotificationReader,- O: Clone + Send + Sync + 'static,->(- state: ::notification::inbound::http::NotificationRouterState<S>,-) -> axum::Router<O> {+pub fn router<S: ::notification::domain::service::NotificationReader>()+-> axum::Router<NotificationRouterState<S>> {::notification::inbound::http::router::<S, serde_json::Value>().route("/", axum::routing::get(list_typed_notifications::<S>)).route(@@ -122,11 +118,6 @@ pub fn router<axum::routing::get(get_typed_notification_by_id::<S>).delete(::notification::inbound::http::delete_notification::<S>),)- .route(- "/bulk",- axum::routing::delete(::notification::inbound::http::bulk_delete_notifications::<S>),- )- .with_state(state)}/// Wrapper handler that calls the inner generic list handler with `serde_json::Value`,diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rsindex b8996c06bc..a62ef67f69 100644--- a/rust/cloud-storage/notification_service/src/main.rs+++ b/rust/cloud-storage/notification_service/src/main.rs@@ -68,13 +68,12 @@ pub async fn main() -> anyhow::Result<()> {#[cfg(feature = "push_notification_event_handler")]{- let device_deleter =- ::notification::outbound::device_registration::DbDeviceRegistrationDeleter::new(- db.clone(),+ let event_notif_repo =+ ::notification::outbound::repository::DbNotificationRepository::new(db.clone());+ let event_sns_manager =+ ::notification::outbound::sns_endpoint::SnsEndpointManagerAdapter::new(+ aws_sdk_sns::Client::new(&aws_config),);- let sns_deleter = ::notification::outbound::sns_endpoint::SnsEndpointDeletionAdapter::new(- aws_sdk_sns::Client::new(&aws_config),- );let push_event_redis_conn = redis_client.get_multiplexed_async_connection()@@ -96,8 +95,8 @@ pub async fn main() -> anyhow::Result<()> {};let event_service = ::notification::domain::service::PushNotificationEventService::new(- device_deleter,- sns_deleter,+ event_notif_repo,+ event_sns_manager,digest_failure_sm,);let event_queue =@@ -128,9 +127,19 @@ pub async fn main() -> anyhow::Result<()> {aws_sdk_sqs::Client::new(&aws_config),vars.notification_queue.as_ref().to_string(),);+ let sns_endpoint_manager =+ ::notification::outbound::sns_endpoint::SnsEndpointManagerAdapter::new(+ aws_sdk_sns::Client::new(&aws_config),+ );+ let platform_config = ::notification::domain::service::PlatformArnConfig {+ apns_platform_arn: config.sns_apns_platform_arn.clone(),+ fcm_platform_arn: config.sns_fcm_platform_arn.clone(),+ };let reader_service = ::notification::domain::service::NotificationReaderService::new(notification_repository,notification_queue.clone(),+ sns_endpoint_manager,+ platform_config,);let ingress_state = ::notification::inbound::http::NotificationRouterState::new(reader_service);diff --git a/rust/cloud-storage/notification_service/src/model/device.rs b/rust/cloud-storage/notification_service/src/model/device.rsdeleted file mode 100644index b1d806f546..0000000000--- a/rust/cloud-storage/notification_service/src/model/device.rs+++ /dev/null@@ -1,10 +0,0 @@-use model_notifications::DeviceType;-use serde::{Deserialize, Serialize};-use utoipa::ToSchema;--#[derive(Debug, Deserialize, Serialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct DeviceRequest {- pub device_type: DeviceType,- pub token: String,-}diff --git a/rust/cloud-storage/notification_service/src/model/mod.rs b/rust/cloud-storage/notification_service/src/model/mod.rsindex b96df937d9..10cdf5de42 100644--- a/rust/cloud-storage/notification_service/src/model/mod.rs+++ b/rust/cloud-storage/notification_service/src/model/mod.rs@@ -1,2 +1 @@-pub mod device;pub mod notification;