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
Stack/01 service migrations (#1331)
Sean Aye53c3e4f8ec50
diff --git a/.gitignore b/.gitignoreindex b7e1829819..7738ab28bd 100644--- a/.gitignore+++ b/.gitignore@@ -5,3 +5,6 @@**/.DS_Store.run/.claude/.local+temp/+.env.local+run-local.fishdiff --git a/flake.nix b/flake.nixindex 5605e1a6c2..fc90658538 100644--- a/flake.nix+++ b/flake.nix@@ -42,6 +42,7 @@nodejs_24pulumipulumiPackages.pulumi-nodejs+ sopsbiomejqstripe-cli@@ -58,27 +59,34 @@])];- libraries = with pkgs; [- openssl- glib- libclang- ] ++ pkgs.lib.optionals isLinux [- glibc.dev- gcc- ] ++ pkgs.lib.optionals isDarwin [- libiconv- ];+ libraries =+ with pkgs;+ [+ openssl+ glib+ libclang+ ]+ ++ pkgs.lib.optionals isLinux [+ glibc.dev+ gcc+ ]+ ++ pkgs.lib.optionals isDarwin [+ libiconv+ ];in{- devShell = pkgs.mkShell ({- buildInputs = packages ++ libraries;- PKG_CONFIG_PATH = "${pkgs.openssl.dev}/lib/pkgconfig";- LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";- SOPS_KMS_ARN = "arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93,arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93";- } // pkgs.lib.optionalAttrs isLinux {- LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";- BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";- });+ devShell = pkgs.mkShell (+ {+ buildInputs = packages ++ libraries;+ PKG_CONFIG_PATH = "${pkgs.openssl.dev}/lib/pkgconfig";+ LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";+ SOPS_KMS_ARN = "arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93,arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93";+ }+ // pkgs.lib.optionalAttrs isLinux {+ LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";+ BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";+ }+ );});}diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsxindex e4ed56779b..c531fc225d 100644--- a/js/app/packages/app/component/UnifiedListView.tsx+++ b/js/app/packages/app/component/UnifiedListView.tsx@@ -69,6 +69,7 @@ import {} from '@macro-entity';import { usePropertyEditorHotkeys } from '../component/property-edit-modal/hooks/usePropertyEditorHotkeys';import {+ getMetadata,isChannelMention,isChannelMessageReply,isChannelMessageSend,@@ -1062,15 +1063,22 @@ export function UnifiedListView(props: UnifiedListViewProps) {const blockOrchestrator = useGlobalBlockOrchestrator();const gotoChannelNotification = async (notification: UnifiedNotification) => {- if (- !isChannelMention(notification) &&- !isChannelMessageReply(notification) &&- !isChannelMessageSend(notification)- )+ let message_id: string | undefined;+ let thread_id: string | undefined;++ if (isChannelMention(notification)) {+ const metadata = getMetadata(notification);+ message_id = metadata.messageId;+ } else if (isChannelMessageReply(notification)) {+ const metadata = getMetadata(notification);+ message_id = metadata.messageId;+ thread_id = metadata.threadId;+ } else if (isChannelMessageSend(notification)) {+ const metadata = getMetadata(notification);+ message_id = metadata.messageId;+ } else {return;-- const message_id = notification.notificationMetadata.messageId;- let thread_id: string | null | undefined;+ }const blockHandle = await blockOrchestrator.getBlockHandle(notification.entity_id,@@ -1078,9 +1086,6 @@ export function UnifiedListView(props: UnifiedListViewProps) {);if (!blockHandle) return;- if (!isChannelMessageSend(notification))- thread_id = notification.notificationMetadata.threadId;-notificationSource.markAsRead(notification);return blockHandle?.goToLocationFromParams({diff --git a/js/app/packages/app/component/dock/QuickAccess.tsx b/js/app/packages/app/component/dock/QuickAccess.tsxindex 2b1cfa5492..93db749cdb 100644--- a/js/app/packages/app/component/dock/QuickAccess.tsx+++ b/js/app/packages/app/component/dock/QuickAccess.tsx@@ -8,9 +8,11 @@ import { useChannelsContext } from '@core/context/channels';import { Tooltip } from '@core/component/Tooltip';import { UserIcon } from '@core/component/UserIcon';import {+ getMetadata,isChannelMention,isChannelMessageReply,notificationIsRead,+ tryToTypedNotification,type UnifiedNotification,} from '@notifications';import type { ApiChannelWithLatest as ChannelWithLatest } from '@service-comms/generated/models';@@ -99,13 +101,21 @@ function QuickAccessItem(props: QuickAccessItemProps) {const channelId = notification.entity_id;if (isChannelMention(notification) || isChannelMessageReply(notification)) {- const metadata = notification.notificationMetadata;- if (metadata && metadata.messageId) {- navigateToMessage(- channelId,- metadata.messageId,- metadata.threadId || undefined- );+ const typed = tryToTypedNotification(notification);+ if (typed) {+ const metadata = getMetadata(typed);+ if (metadata && 'messageId' in metadata && metadata.messageId) {+ navigateToMessage(+ channelId,+ metadata.messageId,+ ('threadId' in metadata && metadata.threadId) || undefined+ );+ } else {+ replaceOrInsertSplit(+ { type: 'channel', id: channelId },+ 'quick-access'+ );+ }} else {replaceOrInsertSplit({ type: 'channel', id: channelId },diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsxindex 52cd7622ff..7bb43ed2f9 100644--- a/js/app/packages/block-email/component/EmailContext.tsx+++ b/js/app/packages/block-email/component/EmailContext.tsx@@ -18,6 +18,7 @@ import {import { whenSettled } from '@core/util/whenSettled';import {createEffectOnEntityTypeNotification,+ getMetadata,isNewEmail,} from '@notifications';import {@@ -156,7 +157,8 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {'email',(notification) => {if (!isNewEmail(notification)) return;- const notificationThreadId = notification.notificationMetadata.threadId;+ const metadata = getMetadata(notification);+ const notificationThreadId = metadata.threadId;if (notificationThreadId === threadQuery.data?.db_id) {threadQuery.refetch();}diff --git a/js/app/packages/core/component/Notifications.tsx b/js/app/packages/core/component/Notifications.tsxindex ed519cab6f..b17cc17cd2 100644--- a/js/app/packages/core/component/Notifications.tsx+++ b/js/app/packages/core/component/Notifications.tsx@@ -9,6 +9,7 @@ import {tryToTypedNotification,type UnifiedNotification,} from '@notifications';+import type { NotificationEventType } from '@service-notification/generated/schemas';import { openNotification } from '@notifications/notification-navigation';import { createMemo, For, Show } from 'solid-js';@@ -70,7 +71,7 @@ export function Notifications(props: NotificationsProps) {<div>{NOTIFICATION_LABEL_BY_TYPE[- notification.notificationEventType+ notification.notificationEventType as NotificationEventType]}</div>diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsxindex 048a34e3a2..457a7e78cd 100644--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx@@ -13,6 +13,7 @@ import ChatIcon from '@icon/regular/chat.svg';import CheckIcon from '@icon/regular/check.svg';import {getAllNotificationsFromGroup,+ getMetadata,getMostRecentNotification,isChannelMessageReply,type NotificationStack,@@ -337,9 +338,9 @@ function NotificationRow(props: {return '';}- const metadata = tryToTypedNotification(- props.notification- )?.notificationMetadata;+ const typed = tryToTypedNotification(props.notification);+ if (!typed) return '';+ const metadata = getMetadata(typed);if (!metadata ||!('messageContent' in metadata) ||@@ -347,9 +348,10 @@ function NotificationRow(props: {)return '';+ const content = metadata.messageContent;return (<Show- when={metadata.messageContent.trim()}+ when={content?.trim()}fallback={<span class="italic text-ink-disabled">Attached items</span>}>{(content) => (@@ -435,9 +437,14 @@ function StackedNotificationRow(props: {);const messageContent = createMemo(() => {- const metadata = mostRecent()?.notificationMetadata;+ const notification = mostRecent();+ if (!notification) return '';+ const typed = tryToTypedNotification(notification);+ if (!typed) return '';+ const metadata = getMetadata(typed);if (metadata && 'messageContent' in metadata) {- return metadata.messageContent?.trim() ?? '';+ const content = metadata.messageContent as string | null | undefined;+ return content?.trim() ?? '';}return '';});@@ -533,9 +540,11 @@ function StackedRepliesRow(props: {const notification = props.group.notifications[0];if (!notification) return '';const typed = tryToTypedNotification(notification);- if (!typed || !isChannelMessageReply(typed) || !typed.notificationMetadata)- return '';- return typed.notificationMetadata.threadParentSenderId ?? '';+ if (!typed || !isChannelMessageReply(typed)) return '';+ const metadata = getMetadata(+ typed as TypedNotification<'channel_message_reply'>+ );+ return metadata?.threadParentSenderId ?? '';};const { firstName } = useDisplayNameParts(tryMacroId(threadParentSenderId()));diff --git a/js/app/packages/macro-entity/src/types/notification.ts b/js/app/packages/macro-entity/src/types/notification.tsindex d4f3c12e2d..0b859c6e53 100644--- a/js/app/packages/macro-entity/src/types/notification.ts+++ b/js/app/packages/macro-entity/src/types/notification.ts@@ -1,8 +1,8 @@// Temporarily use the generated types for now-import type { UserNotification } from '@service-notification/generated/schemas/userNotification';+import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';import type { Accessor } from 'solid-js';-export type Notification = Omit<UserNotification, 'ownerId'>;+export type Notification = Omit<ApiUserNotification, 'ownerId'>;export type WithNotification<T> = T & {notifications?: Accessor<Notification[]>;diff --git a/js/app/packages/notifications/index.ts b/js/app/packages/notifications/index.tsindex c362ec5e5c..08747a5e4e 100644--- a/js/app/packages/notifications/index.ts+++ b/js/app/packages/notifications/index.ts@@ -41,6 +41,7 @@ export type {} from './notification-metadata';export {extractMetadata,+ getMetadata,isChannelInvite,isChannelMention,isChannelMessageDocument,diff --git a/js/app/packages/notifications/notification-metadata.ts b/js/app/packages/notifications/notification-metadata.tsindex 5d3069c6a9..19ba8f3340 100644--- a/js/app/packages/notifications/notification-metadata.ts+++ b/js/app/packages/notifications/notification-metadata.ts@@ -31,114 +31,103 @@ export interface NotificationMetadataByType {export type UnifiedNotificationMetadata =NotificationMetadataByType[keyof NotificationMetadataByType];+/**+ * A notification with a specific event type.+ * Use `getMetadata(notification)` to access the typed metadata content.+ */export type TypedNotification<T extends NotificationEventType = NotificationEventType,-> = {- [K in T]: Omit<- UnifiedNotification,- 'notificationEventType' | 'notificationMetadata'- > & {- notificationEventType: K;- notificationMetadata: K extends keyof NotificationMetadataByType- ? NotificationMetadataByType[K]- : never;- };-}[T];+> = UnifiedNotification & {+ notificationEventType: T;+};++/**+ * Extract the typed metadata content from a notification.+ * The API returns notificationMetadata in { tag, content } format - this extracts the content.+ */+export function getMetadata<T extends NotificationEventType>(+ n: TypedNotification<T>+): T extends keyof NotificationMetadataByType+ ? NotificationMetadataByType[T]+ : never {+ // The notificationMetadata is { tag, content } format from the API+ const metadata = n.notificationMetadata as { tag: string; content: unknown };+ return metadata.content as T extends keyof NotificationMetadataByType+ ? NotificationMetadataByType[T]+ : never;+}++function isNotificationType<T extends NotificationEventType>(+ n: UnifiedNotification,+ type: T+): n is TypedNotification<T> {+ return n.notificationEventType === type;+}export function isItemSharedUser(n: UnifiedNotification): n is TypedNotification<'item_shared_user'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'item_shared_user'- );+ return isNotificationType(n, 'item_shared_user');}export function isItemSharedOrganization(n: UnifiedNotification): n is TypedNotification<'item_shared_organization'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'item_shared_organization'- );+ return isNotificationType(n, 'item_shared_organization');}export function isChannelMention(n: UnifiedNotification): n is TypedNotification<'channel_mention'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'channel_mention'- );+ return isNotificationType(n, 'channel_mention');}export function isDocumentMention(n: UnifiedNotification): n is TypedNotification<'document_mention'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'document_mention'- );+ return isNotificationType(n, 'document_mention');}export function isChannelInvite(n: UnifiedNotification): n is TypedNotification<'channel_invite'> {- return (- 'notificationEventType' in n && n.notificationEventType === 'channel_invite'- );+ return isNotificationType(n, 'channel_invite');}export function isChannelMessageSend(n: UnifiedNotification): n is TypedNotification<'channel_message_send'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'channel_message_send'- );+ return isNotificationType(n, 'channel_message_send');}export function isChannelMessageReply(n: UnifiedNotification): n is TypedNotification<'channel_message_reply'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'channel_message_reply'- );+ return isNotificationType(n, 'channel_message_reply');}export function isChannelMessageDocument(n: UnifiedNotification): n is TypedNotification<'channel_message_document'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'channel_message_document'- );+ return isNotificationType(n, 'channel_message_document');}export function isNewEmail(n: UnifiedNotification): n is TypedNotification<'new_email'> {- return (- 'notificationEventType' in n && n.notificationEventType === 'new_email'- );+ return isNotificationType(n, 'new_email');}export function isInviteToTeam(n: UnifiedNotification): n is TypedNotification<'invite_to_team'> {- return (- 'notificationEventType' in n && n.notificationEventType === 'invite_to_team'- );+ return isNotificationType(n, 'invite_to_team');}export function isRejectTeamInvite(n: UnifiedNotification): n is TypedNotification<'reject_team_invite'> {- return (- 'notificationEventType' in n &&- n.notificationEventType === 'reject_team_invite'- );+ return isNotificationType(n, 'reject_team_invite');}export function extractMetadata<T extends NotificationEventType>(diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex cc1ab76d24..6f43c463ed 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -7,6 +7,7 @@ import { getNotificationById } from '@queries/notification/user-notifications';import { errAsync, ResultAsync } from 'neverthrow';import { match, P } from 'ts-pattern';import {+ getMetadata,tryToTypedNotification,type TypedNotification,} from './notification-metadata';@@ -67,11 +68,9 @@ async function openChannelNotification(layoutManager: SplitManager) {const channelId = notification.entity_id;- const messageId = notification.notificationMetadata.messageId;- const threadId =- 'threadId' in notification.notificationMetadata- ? notification.notificationMetadata.threadId- : undefined;+ const metadata = getMetadata(notification);+ const messageId = metadata.messageId;+ const threadId = 'threadId' in metadata ? metadata.threadId : undefined;openSplitIfNotOpen(layoutManager, 'channel', channelId);const orchestrator = layoutManager.getOrchestrator();@@ -119,7 +118,7 @@ function getSupportedHandler(.with({ notificationEventType: 'new_email' },(n) => async (lm: SplitManager) => {- openSplitIfNotOpen(lm, 'email', n.notificationMetadata.threadId);+ openSplitIfNotOpen(lm, 'email', getMetadata(n).threadId);}).with(@@ -137,7 +136,7 @@ function getSupportedHandler((n) => async (lm: SplitManager) =>openSplitIfNotOpen(lm,- safeFileTypeToBlockName(n.notificationMetadata.itemType),+ safeFileTypeToBlockName(getMetadata(n).itemType),n.entity_id))@@ -151,7 +150,7 @@ function getSupportedHandler((n) => async (lm: SplitManager) =>openSplitIfNotOpen(lm,- safeFileTypeToBlockName(n.notificationMetadata.fileType),+ safeFileTypeToBlockName(getMetadata(n).fileType),n.entity_id))@@ -164,7 +163,7 @@ function getSupportedHandler(.with({ notificationEventType: 'task_assigned' },(n) => async (lm: SplitManager) => {- openSplitIfNotOpen(lm, 'task', n.notificationMetadata.taskId);+ openSplitIfNotOpen(lm, 'task', getMetadata(n).taskId);}).exhaustive();diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.tsindex a700d18a38..02e369a0b9 100644--- a/js/app/packages/notifications/notification-preview.ts+++ b/js/app/packages/notifications/notification-preview.ts@@ -1,7 +1,7 @@import type { BlockName } from '@core/block';import { type EntityType, NotificationType } from '@core/types';import type { NotificationEventType } from '@service-notification/generated/schemas';-import type { TypedNotification } from './notification-metadata';+import { getMetadata, type TypedNotification } from './notification-metadata';export type NotificationData = {actor?: { id: string };@@ -49,7 +49,7 @@ const extractors: {) => NotificationData | null;} = {item_shared_user: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -69,7 +69,7 @@ const extractors: {};},item_shared_organization: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -89,7 +89,7 @@ const extractors: {};},channel_mention: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -98,7 +98,7 @@ const extractors: {target: {type: 'channel',id: n.entity_id,- show: n.notificationMetadata.channelType !== 'directMessage',+ show: m.channelType !== 'directMessage',},content: m.messageContent,meta: {@@ -107,7 +107,7 @@ const extractors: {};},document_mention: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -121,7 +121,7 @@ const extractors: {};},channel_invite: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -132,7 +132,7 @@ const extractors: {};},channel_message_send: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -141,7 +141,7 @@ const extractors: {target: {type: 'channel',id: n.entity_id,- show: n.notificationMetadata.channelType !== 'directMessage',+ show: m.channelType !== 'directMessage',},content: m.messageContent,meta: {@@ -150,7 +150,7 @@ const extractors: {};},channel_message_reply: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -159,7 +159,7 @@ const extractors: {target: {type: 'channel',id: n.entity_id,- show: n.notificationMetadata.channelType !== 'directMessage',+ show: m.channelType !== 'directMessage',},content: m.messageContent,meta: {@@ -169,7 +169,7 @@ const extractors: {};},channel_message_document: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -183,7 +183,7 @@ const extractors: {};},new_email: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;const actorId = n.senderId ?? m.sender;return {@@ -200,7 +200,7 @@ const extractors: {};},invite_to_team: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -211,7 +211,7 @@ const extractors: {};},reject_team_invite: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,@@ -222,7 +222,7 @@ const extractors: {};},task_assigned: (n) => {- const m = n.notificationMetadata;+ const m = getMetadata(n);if (!m) return null;return {type: n.notificationEventType,diff --git a/js/app/packages/notifications/notification-stacking.ts b/js/app/packages/notifications/notification-stacking.tsindex ec864e7e29..5322b5ad8d 100644--- a/js/app/packages/notifications/notification-stacking.ts+++ b/js/app/packages/notifications/notification-stacking.ts@@ -1,4 +1,5 @@import {+ getMetadata,isChannelMention,isChannelMessageReply,isChannelMessageSend,@@ -36,7 +37,10 @@ export function getAllNotificationsFromGroup(export function getThreadId(group: NotificationStack): string {const notification = group.notifications[0];if (notification.notificationEventType === 'channel_message_reply') {- return notification.notificationMetadata?.threadId ?? '';+ const metadata = getMetadata(+ notification as TypedNotification<'channel_message_reply'>+ );+ return metadata?.threadId ?? '';}return '';}@@ -51,13 +55,18 @@ export function stackNotifications(const mentionedMsgIds = new Set(notifications.filter(isChannelMention)- .map((n) => n.notificationMetadata?.messageId)+ .map((n) => getMetadata(n).messageId).filter(Boolean));- const isShadowed = (n: { notificationMetadata?: { messageId?: string } }) =>- n.notificationMetadata?.messageId &&- mentionedMsgIds.has(n.notificationMetadata.messageId);+ const isShadowed = (+ n:+ | TypedNotification<'channel_message_send'>+ | TypedNotification<'channel_message_reply'>+ ) => {+ const metadata = getMetadata(n);+ return metadata.messageId && mentionedMsgIds.has(metadata.messageId);+ };// Partition by typeconst mentions = notifications.filter(isChannelMention);@@ -126,10 +135,7 @@ function makeStack(function makeReplyStacks(replies: TypedNotification<'channel_message_reply'>[]): NotificationStack[] {- const byThread = groupBy(- replies,- (r) => r.notificationMetadata?.threadId ?? ''- );+ const byThread = groupBy(replies, (r) => getMetadata(r)?.threadId ?? '');return [...byThread.entries()].filter(([threadId]) => threadId !== '').map(([, group]) => ({diff --git a/js/app/packages/notifications/queries/entities-notifications-query.ts b/js/app/packages/notifications/queries/entities-notifications-query.tsindex dbd20c2ede..e14a7a7545 100644--- a/js/app/packages/notifications/queries/entities-notifications-query.ts+++ b/js/app/packages/notifications/queries/entities-notifications-query.ts@@ -1,9 +1,9 @@import type { Entity } from '@core/types';import { isErr } from '@core/util/maybeResult';import { notificationServiceClient } from '@service-notification/client';-import type { UserNotification } from '@service-notification/generated/schemas';+import type { ApiUserNotification } from '@service-notification/generated/schemas';-type UnifiedNotification = Omit<UserNotification, 'ownerId'>;+type UnifiedNotification = Omit<ApiUserNotification, 'ownerId'>;export const fetchNotificationsForEntities = async (entities: Entity[]diff --git a/js/app/packages/notifications/tests/notification-preview.test.ts b/js/app/packages/notifications/tests/notification-preview.test.tsindex f71f252e4e..0519a930c9 100644--- a/js/app/packages/notifications/tests/notification-preview.test.ts+++ b/js/app/packages/notifications/tests/notification-preview.test.ts@@ -13,19 +13,22 @@ function createEmailNotification(entity_id: 'thread-1',entity_type: 'email',createdAt: Date.now(),- updatedAt: null,- viewedAt: null,- deletedAt: null,+ updatedAt: 0,+ viewedAt: 0,+ deletedAt: 0,done: false,sent: true,senderId,notificationEventType: 'new_email' as NotificationEventType,notificationMetadata: {- sender: metadataSender,- subject: 'Test Subject',- snippet: 'Test snippet',- threadId: 'thread-1',- toEmail: '[email protected]',+ tag: 'new_email',+ content: {+ sender: metadataSender,+ subject: 'Test Subject',+ snippet: 'Test snippet',+ threadId: 'thread-1',+ toEmail: '[email protected]',+ },},} as UnifiedNotification;}diff --git a/js/app/packages/notifications/tests/notification-stacking.test.ts b/js/app/packages/notifications/tests/notification-stacking.test.tsindex 35c04808ac..08c114e75e 100644--- a/js/app/packages/notifications/tests/notification-stacking.test.ts+++ b/js/app/packages/notifications/tests/notification-stacking.test.ts@@ -20,14 +20,17 @@ function createNotification(entity_id: 'channel-1',entity_type: 'channel',createdAt,- updatedAt: null,- viewedAt: null,- deletedAt: null,+ updatedAt: 0,+ viewedAt: 0,+ deletedAt: 0,done: false,sent: true,senderId: 'user-1',notificationEventType: type,- notificationMetadata: metadata,+ notificationMetadata: {+ tag: type,+ content: metadata,+ },} as UnifiedNotification;}diff --git a/js/app/packages/notifications/types.ts b/js/app/packages/notifications/types.tsindex 2955a0aea9..6d69373222 100644--- a/js/app/packages/notifications/types.ts+++ b/js/app/packages/notifications/types.ts@@ -1,7 +1,7 @@import type { Entity, EntityType } from '@core/types';-import type { UserNotification } from '@service-notification/generated/schemas';+import type { ApiUserNotification } from '@service-notification/generated/schemas';-export type UnifiedNotification = Omit<UserNotification, 'ownerId'>;+export type UnifiedNotification = Omit<ApiUserNotification, 'ownerId'>;export type CompositeEntity = `${EntityType}@${string}`;diff --git a/js/app/packages/queries/notification/tests/user-notifications.test.tsx b/js/app/packages/queries/notification/tests/user-notifications.test.tsxindex e878673e37..99a4e17576 100644--- a/js/app/packages/queries/notification/tests/user-notifications.test.tsx+++ b/js/app/packages/queries/notification/tests/user-notifications.test.tsx@@ -3,8 +3,8 @@*/import { err, ok } from '@core/util/maybeResult';+import type { ApiUserNotification } from '@service-notification/generated/schemas/apiUserNotification';import type { GetAllUserNotificationsResponse } from '@service-notification/generated/schemas/getAllUserNotificationsResponse';-import type { UserNotification } from '@service-notification/generated/schemas/userNotification';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import type { JSX } from 'solid-js';import { render } from 'solid-js/web';@@ -47,29 +47,33 @@ vi.mock('../../client', () => ({type UserNotificationsPageParam = { limit: number; cursor?: string };function createMockNotification(- overrides: Partial<UserNotification> = {}-): UserNotification {+ overrides: Partial<ApiUserNotification> = {}+): ApiUserNotification {return {id: `notification-${Math.random().toString(36).slice(2)}`,entity_id: 'entity-1',entity_type: 'document',createdAt: Date.now(),- updatedAt: null,- viewedAt: null,- deletedAt: null,+ updatedAt: 0,+ viewedAt: 0,+ deletedAt: 0,done: false,sent: true,- notificationEventType: 'ItemShared',+ ownerId: 'owner-1',+ notificationEventType: 'item_shared_user',notificationMetadata: {- sharer_id: 'user-1',- permission_level: 'editor',+ tag: 'item_shared_user',+ content: {+ sharedBy: 'user-1',+ permissionLevel: 'editor',+ },},...overrides,- } as UserNotification;+ } as ApiUserNotification;}function createMockNotificationPage(- notifications: UserNotification[],+ notifications: ApiUserNotification[],nextCursor?: string): GetAllUserNotificationsResponse {return {@@ -144,8 +148,8 @@ describe('notification mutations', () => {describe('useMarkNotificationsAsSeenMutation', () => {it('should optimistically update viewedAt when marking as seen', async () => {- const n1 = createMockNotification({ id: 'n1', viewedAt: null });- const n2 = createMockNotification({ id: 'n2', viewedAt: null });+ const n1 = createMockNotification({ id: 'n1', viewedAt: 0 });+ const n2 = createMockNotification({ id: 'n2', viewedAt: 0 });seedQueryCache([createMockNotificationPage([n1, n2])]);mockBulkMarkNotificationAsSeen.mockResolvedValue(ok({ success: true }));@@ -163,14 +167,14 @@ describe('notification mutations', () => {await mutatePromise;const notifications = getNotificationsFromCache();- expect(notifications[0].viewedAt).not.toBeNull();- expect(notifications[1].viewedAt).toBeNull();+ expect(notifications[0].viewedAt).toBeGreaterThan(0);+ expect(notifications[1].viewedAt).toBe(0);cleanup();});it('should rollback optimistic update on error', async () => {- const n1 = createMockNotification({ id: 'n1', viewedAt: null });+ const n1 = createMockNotification({ id: 'n1', viewedAt: 0 });seedQueryCache([createMockNotificationPage([n1])]);mockBulkMarkNotificationAsSeen.mockResolvedValue(@@ -194,14 +198,14 @@ describe('notification mutations', () => {await new Promise((r) => setTimeout(r, 10));const notifications = getNotificationsFromCache();- expect(notifications[0].viewedAt).toBeNull();+ expect(notifications[0].viewedAt).toBe(0);cleanup();});it('should handle marking notifications across multiple pages', async () => {- const n1 = createMockNotification({ id: 'n1', viewedAt: null });- const n2 = createMockNotification({ id: 'n2', viewedAt: null });+ const n1 = createMockNotification({ id: 'n1', viewedAt: 0 });+ const n2 = createMockNotification({ id: 'n2', viewedAt: 0 });seedQueryCache([createMockNotificationPage([n1]),createMockNotificationPage([n2]),@@ -222,8 +226,8 @@ describe('notification mutations', () => {await mutatePromise;const notifications = getNotificationsFromCache();- expect(notifications[0].viewedAt).toBeNull(); // n1 unchanged- expect(notifications[1].viewedAt).not.toBeNull(); // n2 updated+ expect(notifications[0].viewedAt).toBe(0); // n1 unchanged+ expect(notifications[1].viewedAt).toBeGreaterThan(0); // n2 updatedcleanup();});diff --git a/js/app/packages/service-clients/service-notification/client.ts b/js/app/packages/service-clients/service-notification/client.tsindex dfde969ef9..3388b708fd 100644--- a/js/app/packages/service-clients/service-notification/client.ts+++ b/js/app/packages/service-clients/service-notification/client.ts@@ -12,13 +12,12 @@ import {import type { SafeFetchInit } from '@core/util/safeFetch';import { z } from 'zod';import type {- BulkGetUserNotificationsByEventItemIdRequest,+ BulkGetByEventItemIdsRequest,GetAllUserNotificationsResponse,- GetUserNotificationParams,} from './generated/schemas';+import type { ApiUserNotification } from './generated/schemas/apiUserNotification';import type { DeviceRequest } from './generated/schemas/deviceRequest';import type { NotificationBulkRequest } from './generated/schemas/notificationBulkRequest';-import type { UserNotification } from './generated/schemas/userNotification';import type { UserUnsubscribe } from './generated/schemas/userUnsubscribe';const notificationHost: string = SERVER_HOSTS['notification-service'];@@ -34,7 +33,7 @@ export type IncomingNotification = {type WithEventItemId = { event_item_id: string };type WithItem = { item_id: string; item_type: string };-export type UnifiedNotification = Omit<UserNotification, 'ownerId'> & {+export type UnifiedNotification = Omit<ApiUserNotification, 'ownerId'> & {senderId?: string | null;// whether the notification is incoming on the websocket and needs processing// as opposed to coming from the database or an already processed notification@@ -90,8 +89,10 @@ export const documentMentionMetadata = z.object({.optional(),});+type NotificationParams = { cursor?: string; limit?: number };+export const notificationServiceClient = {- async userNotifications(args: GetUserNotificationParams) {+ async userNotifications(args: NotificationParams) {const { limit, cursor } = args;return mapOk(await notificationFetch<GetAllUserNotificationsResponse>(@@ -107,7 +108,7 @@ export const notificationServiceClient = {},async getUserNotificationById(notificationId: string) {return mapOk(- await notificationFetch<UserNotification>(+ await notificationFetch<ApiUserNotification>(`/user_notifications/${notificationId}`,{ method: 'GET' }),@@ -115,8 +116,7 @@ export const notificationServiceClient = {);},async bulkGetUserNotificationsByEventItemId(- args: GetUserNotificationParams &- BulkGetUserNotificationsByEventItemIdRequest+ args: NotificationParams & BulkGetByEventItemIdsRequest) {const { limit, cursor } = args;return mapOk(diff --git a/js/app/packages/service-clients/service-notification/generated/client.ts b/js/app/packages/service-clients/service-notification/generated/client.tsindex 6bedddef2f..3234a325d3 100644--- a/js/app/packages/service-clients/service-notification/generated/client.ts+++ b/js/app/packages/service-clients/service-notification/generated/client.ts@@ -5,18 +5,18 @@* OpenAPI spec version: 0.1.0*/import type {- BulkGetUserNotificationsByEventItemIdParams,- BulkGetUserNotificationsByEventItemIdRequest,+ ApiUserNotification,+ BulkGetByEventItemIdsRequest,+ BulkGetTypedNotificationsByEventItemIdsParams,CreateNotification,DeviceRequest,EmptyResponse,ErrorResponse,GetAllUserNotificationsResponse,- GetUserNotificationParams,- GetUserNotificationsByEventItemIdParams,+ GetTypedNotificationsByEventItemIdParams,+ ListTypedNotificationsParams,Notification,NotificationBulkRequest,- UserNotification,UserUnsubscribe,} from './schemas';@@ -555,46 +555,48 @@ export const removeUnsubscribeAll = async (};/**- * @summary Gets the user's unseen notifications in a paginated format.+ * Rows that fail to deserialize are dropped with a warning log.+ * @summary Wrapper handler that calls the inner generic list handler with `serde_json::Value`,+then converts each row to [`UserNotificationRow<NotifEvent>`].*/-export type getUserNotificationResponse200 = {+export type listTypedNotificationsResponse200 = {data: GetAllUserNotificationsResponse;status: 200;};-export type getUserNotificationResponse400 = {+export type listTypedNotificationsResponse400 = {data: ErrorResponse;status: 400;};-export type getUserNotificationResponse401 = {+export type listTypedNotificationsResponse401 = {data: ErrorResponse;status: 401;};-export type getUserNotificationResponse500 = {+export type listTypedNotificationsResponse500 = {data: ErrorResponse;status: 500;};-export type getUserNotificationResponseSuccess =- getUserNotificationResponse200 & {+export type listTypedNotificationsResponseSuccess =+ listTypedNotificationsResponse200 & {headers: Headers;};-export type getUserNotificationResponseError = (- | getUserNotificationResponse400- | getUserNotificationResponse401- | getUserNotificationResponse500+export type listTypedNotificationsResponseError = (+ | listTypedNotificationsResponse400+ | listTypedNotificationsResponse401+ | listTypedNotificationsResponse500) & {headers: Headers;};-export type getUserNotificationResponse =- | getUserNotificationResponseSuccess- | getUserNotificationResponseError;+export type listTypedNotificationsResponse =+ | listTypedNotificationsResponseSuccess+ | listTypedNotificationsResponseError;-export const getGetUserNotificationUrl = (- params: GetUserNotificationParams+export const getListTypedNotificationsUrl = (+ params?: ListTypedNotificationsParams) => {const normalizedParams = new URLSearchParams();@@ -607,475 +609,594 @@ export const getGetUserNotificationUrl = (const stringifiedParams = normalizedParams.toString();return stringifiedParams.length > 0- ? `/user_notifications?${stringifiedParams}`- : `/user_notifications`;+ ? `/v1/user_notifications?${stringifiedParams}`+ : `/v1/user_notifications`;};-export const getUserNotification = async (- params: GetUserNotificationParams,+export const listTypedNotifications = async (+ params?: ListTypedNotificationsParams,options?: RequestInit-): Promise<getUserNotificationResponse> => {- const res = await fetch(getGetUserNotificationUrl(params), {+): Promise<listTypedNotificationsResponse> => {+ const res = await fetch(getListTypedNotificationsUrl(params), {...options,method: 'GET',});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: getUserNotificationResponse['data'] = body+ const data: listTypedNotificationsResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as getUserNotificationResponse;+ } as listTypedNotificationsResponse;};/**- * @summary Marks the user's notifications as deleted+ * Rows that fail to deserialize are dropped with a warning log.+ * @summary Wrapper handler that calls the inner generic bulk-get handler with `serde_json::Value`,+then converts each row to [`UserNotificationRow<NotifEvent>`].*/-export type bulkDeleteUserNotificationResponse200 = {- data: EmptyResponse;+export type bulkGetTypedNotificationsByEventItemIdsResponse200 = {+ data: GetAllUserNotificationsResponse;status: 200;};-export type bulkDeleteUserNotificationResponseSuccess =- bulkDeleteUserNotificationResponse200 & {+export type bulkGetTypedNotificationsByEventItemIdsResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type bulkGetTypedNotificationsByEventItemIdsResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type bulkGetTypedNotificationsByEventItemIdsResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type bulkGetTypedNotificationsByEventItemIdsResponseSuccess =+ bulkGetTypedNotificationsByEventItemIdsResponse200 & {headers: Headers;};+export type bulkGetTypedNotificationsByEventItemIdsResponseError = (+ | bulkGetTypedNotificationsByEventItemIdsResponse400+ | bulkGetTypedNotificationsByEventItemIdsResponse401+ | bulkGetTypedNotificationsByEventItemIdsResponse500+) & {+ headers: Headers;+};++export type bulkGetTypedNotificationsByEventItemIdsResponse =+ | bulkGetTypedNotificationsByEventItemIdsResponseSuccess+ | bulkGetTypedNotificationsByEventItemIdsResponseError;++export const getBulkGetTypedNotificationsByEventItemIdsUrl = (+ params?: BulkGetTypedNotificationsByEventItemIdsParams+) => {+ const normalizedParams = new URLSearchParams();++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString());+ }+ });-export type bulkDeleteUserNotificationResponse =- bulkDeleteUserNotificationResponseSuccess;+ const stringifiedParams = normalizedParams.toString();-export const getBulkDeleteUserNotificationUrl = () => {- return `/user_notifications/bulk`;+ return stringifiedParams.length > 0+ ? `/v1/user_notifications/item/bulk?${stringifiedParams}`+ : `/v1/user_notifications/item/bulk`;};-export const bulkDeleteUserNotification = async (- notificationBulkRequest: NotificationBulkRequest,+export const bulkGetTypedNotificationsByEventItemIds = async (+ bulkGetByEventItemIdsRequest: BulkGetByEventItemIdsRequest,+ params?: BulkGetTypedNotificationsByEventItemIdsParams,options?: RequestInit-): Promise<bulkDeleteUserNotificationResponse> => {- const res = await fetch(getBulkDeleteUserNotificationUrl(), {- ...options,- method: 'DELETE',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(notificationBulkRequest),- });+): Promise<bulkGetTypedNotificationsByEventItemIdsResponse> => {+ const res = await fetch(+ getBulkGetTypedNotificationsByEventItemIdsUrl(params),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(bulkGetByEventItemIdsRequest),+ }+ );const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: bulkDeleteUserNotificationResponse['data'] = body+ const data: bulkGetTypedNotificationsByEventItemIdsResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as bulkDeleteUserNotificationResponse;+ } as bulkGetTypedNotificationsByEventItemIdsResponse;};/**- * @summary Marks the user's notifications as done+ * @summary Typed wrapper for getting notifications by a single event item ID.*/-export type bulkMarkUserNotificationDoneResponse200 = {- data: EmptyResponse;+export type getTypedNotificationsByEventItemIdResponse200 = {+ data: GetAllUserNotificationsResponse;status: 200;};-export type bulkMarkUserNotificationDoneResponseSuccess =- bulkMarkUserNotificationDoneResponse200 & {+export type getTypedNotificationsByEventItemIdResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type getTypedNotificationsByEventItemIdResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type getTypedNotificationsByEventItemIdResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type getTypedNotificationsByEventItemIdResponseSuccess =+ getTypedNotificationsByEventItemIdResponse200 & {headers: Headers;};+export type getTypedNotificationsByEventItemIdResponseError = (+ | getTypedNotificationsByEventItemIdResponse400+ | getTypedNotificationsByEventItemIdResponse401+ | getTypedNotificationsByEventItemIdResponse500+) & {+ headers: Headers;+};-export type bulkMarkUserNotificationDoneResponse =- bulkMarkUserNotificationDoneResponseSuccess;+export type getTypedNotificationsByEventItemIdResponse =+ | getTypedNotificationsByEventItemIdResponseSuccess+ | getTypedNotificationsByEventItemIdResponseError;-export const getBulkMarkUserNotificationDoneUrl = () => {- return `/user_notifications/bulk/done`;+export const getGetTypedNotificationsByEventItemIdUrl = (+ eventItemId: string,+ params?: GetTypedNotificationsByEventItemIdParams+) => {+ const normalizedParams = new URLSearchParams();++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString());+ }+ });++ const stringifiedParams = normalizedParams.toString();++ return stringifiedParams.length > 0+ ? `/v1/user_notifications/item/${eventItemId}?${stringifiedParams}`+ : `/v1/user_notifications/item/${eventItemId}`;};-export const bulkMarkUserNotificationDone = async (- notificationBulkRequest: NotificationBulkRequest,+export const getTypedNotificationsByEventItemId = async (+ eventItemId: string,+ params?: GetTypedNotificationsByEventItemIdParams,options?: RequestInit-): Promise<bulkMarkUserNotificationDoneResponse> => {- const res = await fetch(getBulkMarkUserNotificationDoneUrl(), {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(notificationBulkRequest),- });+): Promise<getTypedNotificationsByEventItemIdResponse> => {+ const res = await fetch(+ getGetTypedNotificationsByEventItemIdUrl(eventItemId, params),+ {+ ...options,+ method: 'GET',+ }+ );const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: bulkMarkUserNotificationDoneResponse['data'] = body+ const data: getTypedNotificationsByEventItemIdResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as bulkMarkUserNotificationDoneResponse;+ } as getTypedNotificationsByEventItemIdResponse;};/**- * @summary Marks the user's notifications as seen+ * @summary Typed wrapper for getting a single notification by ID.*/-export type bulkMarkUserNotificationSeenResponse200 = {- data: EmptyResponse;+export type getTypedNotificationByIdResponse200 = {+ data: ApiUserNotification;status: 200;};-export type bulkMarkUserNotificationSeenResponseSuccess =- bulkMarkUserNotificationSeenResponse200 & {+export type getTypedNotificationByIdResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type getTypedNotificationByIdResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type getTypedNotificationByIdResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type getTypedNotificationByIdResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type getTypedNotificationByIdResponseSuccess =+ getTypedNotificationByIdResponse200 & {headers: Headers;};+export type getTypedNotificationByIdResponseError = (+ | getTypedNotificationByIdResponse400+ | getTypedNotificationByIdResponse401+ | getTypedNotificationByIdResponse404+ | getTypedNotificationByIdResponse500+) & {+ headers: Headers;+};-export type bulkMarkUserNotificationSeenResponse =- bulkMarkUserNotificationSeenResponseSuccess;+export type getTypedNotificationByIdResponse =+ | getTypedNotificationByIdResponseSuccess+ | getTypedNotificationByIdResponseError;-export const getBulkMarkUserNotificationSeenUrl = () => {- return `/user_notifications/bulk/seen`;+export const getGetTypedNotificationByIdUrl = (notificationId: string) => {+ return `/v1/user_notifications/${notificationId}`;};-export const bulkMarkUserNotificationSeen = async (- notificationBulkRequest: NotificationBulkRequest,+export const getTypedNotificationById = async (+ notificationId: string,options?: RequestInit-): Promise<bulkMarkUserNotificationSeenResponse> => {- const res = await fetch(getBulkMarkUserNotificationSeenUrl(), {+): Promise<getTypedNotificationByIdResponse> => {+ const res = await fetch(getGetTypedNotificationByIdUrl(notificationId), {...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(notificationBulkRequest),+ method: 'GET',});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: bulkMarkUserNotificationSeenResponse['data'] = body+ const data: getTypedNotificationByIdResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as bulkMarkUserNotificationSeenResponse;+ } as getTypedNotificationByIdResponse;};/**- * @summary Marks the user's notifications as undone.+ * @summary Soft-delete multiple user notifications.*/-export type bulkMarkUserNotificationUndoneResponse200 = {- data: EmptyResponse;+export type bulkDeleteUserNotificationsV2Response200 = {+ data: void;status: 200;};-export type bulkMarkUserNotificationUndoneResponseSuccess =- bulkMarkUserNotificationUndoneResponse200 & {+export type bulkDeleteUserNotificationsV2Response400 = {+ data: ErrorResponse;+ status: 400;+};++export type bulkDeleteUserNotificationsV2Response401 = {+ data: ErrorResponse;+ status: 401;+};++export type bulkDeleteUserNotificationsV2Response500 = {+ data: ErrorResponse;+ status: 500;+};++export type bulkDeleteUserNotificationsV2ResponseSuccess =+ bulkDeleteUserNotificationsV2Response200 & {headers: Headers;};+export type bulkDeleteUserNotificationsV2ResponseError = (+ | bulkDeleteUserNotificationsV2Response400+ | bulkDeleteUserNotificationsV2Response401+ | bulkDeleteUserNotificationsV2Response500+) & {+ headers: Headers;+};-export type bulkMarkUserNotificationUndoneResponse =- bulkMarkUserNotificationUndoneResponseSuccess;+export type bulkDeleteUserNotificationsV2Response =+ | bulkDeleteUserNotificationsV2ResponseSuccess+ | bulkDeleteUserNotificationsV2ResponseError;-export const getBulkMarkUserNotificationUndoneUrl = () => {- return `/user_notifications/bulk/undone`;+export const getBulkDeleteUserNotificationsV2Url = () => {+ return `/v2/user_notifications/bulk`;};-export const bulkMarkUserNotificationUndone = async (+export const bulkDeleteUserNotificationsV2 = async (notificationBulkRequest: NotificationBulkRequest,options?: RequestInit-): Promise<bulkMarkUserNotificationUndoneResponse> => {- const res = await fetch(getBulkMarkUserNotificationUndoneUrl(), {+): Promise<bulkDeleteUserNotificationsV2Response> => {+ const res = await fetch(getBulkDeleteUserNotificationsV2Url(), {...options,- method: 'PATCH',+ method: 'DELETE',headers: { 'Content-Type': 'application/json', ...options?.headers },body: JSON.stringify(notificationBulkRequest),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: bulkMarkUserNotificationUndoneResponse['data'] = body+ const data: bulkDeleteUserNotificationsV2Response['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as bulkMarkUserNotificationUndoneResponse;+ } as bulkDeleteUserNotificationsV2Response;};/**- * @summary Gets the user's notifications for a provided event item ids in a paginated format.-This will only return unseen notifications.+ * @summary Mark notifications as done.*/-export type bulkGetUserNotificationsByEventItemIdResponse200 = {- data: GetAllUserNotificationsResponse;+export type bulkMarkNotificationsDoneResponse200 = {+ data: void;status: 200;};-export type bulkGetUserNotificationsByEventItemIdResponse400 = {+export type bulkMarkNotificationsDoneResponse400 = {data: ErrorResponse;status: 400;};-export type bulkGetUserNotificationsByEventItemIdResponse401 = {+export type bulkMarkNotificationsDoneResponse401 = {data: ErrorResponse;status: 401;};-export type bulkGetUserNotificationsByEventItemIdResponse500 = {+export type bulkMarkNotificationsDoneResponse500 = {data: ErrorResponse;status: 500;};-export type bulkGetUserNotificationsByEventItemIdResponseSuccess =- bulkGetUserNotificationsByEventItemIdResponse200 & {+export type bulkMarkNotificationsDoneResponseSuccess =+ bulkMarkNotificationsDoneResponse200 & {headers: Headers;};-export type bulkGetUserNotificationsByEventItemIdResponseError = (- | bulkGetUserNotificationsByEventItemIdResponse400- | bulkGetUserNotificationsByEventItemIdResponse401- | bulkGetUserNotificationsByEventItemIdResponse500+export type bulkMarkNotificationsDoneResponseError = (+ | bulkMarkNotificationsDoneResponse400+ | bulkMarkNotificationsDoneResponse401+ | bulkMarkNotificationsDoneResponse500) & {headers: Headers;};-export type bulkGetUserNotificationsByEventItemIdResponse =- | bulkGetUserNotificationsByEventItemIdResponseSuccess- | bulkGetUserNotificationsByEventItemIdResponseError;--export const getBulkGetUserNotificationsByEventItemIdUrl = (- params: BulkGetUserNotificationsByEventItemIdParams-) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString());- }- });-- const stringifiedParams = normalizedParams.toString();+export type bulkMarkNotificationsDoneResponse =+ | bulkMarkNotificationsDoneResponseSuccess+ | bulkMarkNotificationsDoneResponseError;- return stringifiedParams.length > 0- ? `/user_notifications/item/bulk?${stringifiedParams}`- : `/user_notifications/item/bulk`;+export const getBulkMarkNotificationsDoneUrl = () => {+ return `/v2/user_notifications/bulk/done`;};-export const bulkGetUserNotificationsByEventItemId = async (- bulkGetUserNotificationsByEventItemIdRequest: BulkGetUserNotificationsByEventItemIdRequest,- params: BulkGetUserNotificationsByEventItemIdParams,+export const bulkMarkNotificationsDone = async (+ notificationBulkRequest: NotificationBulkRequest,options?: RequestInit-): Promise<bulkGetUserNotificationsByEventItemIdResponse> => {- const res = await fetch(getBulkGetUserNotificationsByEventItemIdUrl(params), {+): Promise<bulkMarkNotificationsDoneResponse> => {+ const res = await fetch(getBulkMarkNotificationsDoneUrl(), {...options,- method: 'POST',+ method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(bulkGetUserNotificationsByEventItemIdRequest),+ body: JSON.stringify(notificationBulkRequest),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: bulkGetUserNotificationsByEventItemIdResponse['data'] = body+ const data: bulkMarkNotificationsDoneResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as bulkGetUserNotificationsByEventItemIdResponse;+ } as bulkMarkNotificationsDoneResponse;};/**- * @summary Gets the user's notifications for a given event item id in a paginated format.+ * @summary Mark notifications as seen.*/-export type getUserNotificationsByEventItemIdResponse200 = {- data: GetAllUserNotificationsResponse;+export type bulkMarkNotificationsSeenResponse200 = {+ data: void;status: 200;};-export type getUserNotificationsByEventItemIdResponse400 = {+export type bulkMarkNotificationsSeenResponse400 = {data: ErrorResponse;status: 400;};-export type getUserNotificationsByEventItemIdResponse401 = {+export type bulkMarkNotificationsSeenResponse401 = {data: ErrorResponse;status: 401;};-export type getUserNotificationsByEventItemIdResponse500 = {+export type bulkMarkNotificationsSeenResponse500 = {data: ErrorResponse;status: 500;};-export type getUserNotificationsByEventItemIdResponseSuccess =- getUserNotificationsByEventItemIdResponse200 & {+export type bulkMarkNotificationsSeenResponseSuccess =+ bulkMarkNotificationsSeenResponse200 & {headers: Headers;};-export type getUserNotificationsByEventItemIdResponseError = (- | getUserNotificationsByEventItemIdResponse400- | getUserNotificationsByEventItemIdResponse401- | getUserNotificationsByEventItemIdResponse500+export type bulkMarkNotificationsSeenResponseError = (+ | bulkMarkNotificationsSeenResponse400+ | bulkMarkNotificationsSeenResponse401+ | bulkMarkNotificationsSeenResponse500) & {headers: Headers;};-export type getUserNotificationsByEventItemIdResponse =- | getUserNotificationsByEventItemIdResponseSuccess- | getUserNotificationsByEventItemIdResponseError;--export const getGetUserNotificationsByEventItemIdUrl = (- eventItemId: string,- params: GetUserNotificationsByEventItemIdParams-) => {- const normalizedParams = new URLSearchParams();-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString());- }- });+export type bulkMarkNotificationsSeenResponse =+ | bulkMarkNotificationsSeenResponseSuccess+ | bulkMarkNotificationsSeenResponseError;- const stringifiedParams = normalizedParams.toString();-- return stringifiedParams.length > 0- ? `/user_notifications/item/${eventItemId}?${stringifiedParams}`- : `/user_notifications/item/${eventItemId}`;+export const getBulkMarkNotificationsSeenUrl = () => {+ return `/v2/user_notifications/bulk/seen`;};-export const getUserNotificationsByEventItemId = async (- eventItemId: string,- params: GetUserNotificationsByEventItemIdParams,+export const bulkMarkNotificationsSeen = async (+ notificationBulkRequest: NotificationBulkRequest,options?: RequestInit-): Promise<getUserNotificationsByEventItemIdResponse> => {- const res = await fetch(- getGetUserNotificationsByEventItemIdUrl(eventItemId, params),- {- ...options,- method: 'GET',- }- );+): Promise<bulkMarkNotificationsSeenResponse> => {+ const res = await fetch(getBulkMarkNotificationsSeenUrl(), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(notificationBulkRequest),+ });const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: getUserNotificationsByEventItemIdResponse['data'] = body+ const data: bulkMarkNotificationsSeenResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as getUserNotificationsByEventItemIdResponse;+ } as bulkMarkNotificationsSeenResponse;};/**- * @summary Gets a single user notification by id.+ * @summary Mark notifications as not done.*/-export type getUserNotificationByIdResponse200 = {- data: UserNotification;+export type bulkMarkNotificationsUndoneResponse200 = {+ data: void;status: 200;};-export type getUserNotificationByIdResponse400 = {+export type bulkMarkNotificationsUndoneResponse400 = {data: ErrorResponse;status: 400;};-export type getUserNotificationByIdResponse401 = {+export type bulkMarkNotificationsUndoneResponse401 = {data: ErrorResponse;status: 401;};-export type getUserNotificationByIdResponse404 = {- data: ErrorResponse;- status: 404;-};--export type getUserNotificationByIdResponse500 = {+export type bulkMarkNotificationsUndoneResponse500 = {data: ErrorResponse;status: 500;};-export type getUserNotificationByIdResponseSuccess =- getUserNotificationByIdResponse200 & {+export type bulkMarkNotificationsUndoneResponseSuccess =+ bulkMarkNotificationsUndoneResponse200 & {headers: Headers;};-export type getUserNotificationByIdResponseError = (- | getUserNotificationByIdResponse400- | getUserNotificationByIdResponse401- | getUserNotificationByIdResponse404- | getUserNotificationByIdResponse500+export type bulkMarkNotificationsUndoneResponseError = (+ | bulkMarkNotificationsUndoneResponse400+ | bulkMarkNotificationsUndoneResponse401+ | bulkMarkNotificationsUndoneResponse500) & {headers: Headers;};-export type getUserNotificationByIdResponse =- | getUserNotificationByIdResponseSuccess- | getUserNotificationByIdResponseError;+export type bulkMarkNotificationsUndoneResponse =+ | bulkMarkNotificationsUndoneResponseSuccess+ | bulkMarkNotificationsUndoneResponseError;-export const getGetUserNotificationByIdUrl = (notificationId: string) => {- return `/user_notifications/${notificationId}`;+export const getBulkMarkNotificationsUndoneUrl = () => {+ return `/v2/user_notifications/bulk/undone`;};-export const getUserNotificationById = async (- notificationId: string,+export const bulkMarkNotificationsUndone = async (+ notificationBulkRequest: NotificationBulkRequest,options?: RequestInit-): Promise<getUserNotificationByIdResponse> => {- const res = await fetch(getGetUserNotificationByIdUrl(notificationId), {+): Promise<bulkMarkNotificationsUndoneResponse> => {+ const res = await fetch(getBulkMarkNotificationsUndoneUrl(), {...options,- method: 'GET',+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(notificationBulkRequest),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: getUserNotificationByIdResponse['data'] = body+ const data: bulkMarkNotificationsUndoneResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as getUserNotificationByIdResponse;+ } as bulkMarkNotificationsUndoneResponse;};/**- * @summary Marks the user's notification as deleted.+ * @summary Soft-delete a single user notification.*/-export type deleteUserNotificationResponse200 = {- data: EmptyResponse;+export type deleteUserNotificationV2Response200 = {+ data: void;status: 200;};-export type deleteUserNotificationResponseSuccess =- deleteUserNotificationResponse200 & {+export type deleteUserNotificationV2Response400 = {+ data: ErrorResponse;+ status: 400;+};++export type deleteUserNotificationV2Response401 = {+ data: ErrorResponse;+ status: 401;+};++export type deleteUserNotificationV2Response500 = {+ data: ErrorResponse;+ status: 500;+};++export type deleteUserNotificationV2ResponseSuccess =+ deleteUserNotificationV2Response200 & {headers: Headers;};+export type deleteUserNotificationV2ResponseError = (+ | deleteUserNotificationV2Response400+ | deleteUserNotificationV2Response401+ | deleteUserNotificationV2Response500+) & {+ headers: Headers;+};-export type deleteUserNotificationResponse =- deleteUserNotificationResponseSuccess;+export type deleteUserNotificationV2Response =+ | deleteUserNotificationV2ResponseSuccess+ | deleteUserNotificationV2ResponseError;-export const getDeleteUserNotificationUrl = (notificationId: string) => {- return `/user_notifications/${notificationId}`;+export const getDeleteUserNotificationV2Url = (notificationId: string) => {+ return `/v2/user_notifications/${notificationId}`;};-export const deleteUserNotification = async (+export const deleteUserNotificationV2 = async (notificationId: string,options?: RequestInit-): Promise<deleteUserNotificationResponse> => {- const res = await fetch(getDeleteUserNotificationUrl(notificationId), {+): Promise<deleteUserNotificationV2Response> => {+ const res = await fetch(getDeleteUserNotificationV2Url(notificationId), {...options,method: 'DELETE',});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: deleteUserNotificationResponse['data'] = body+ const data: deleteUserNotificationV2Response['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as deleteUserNotificationResponse;+ } as deleteUserNotificationV2Response;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotification.ts b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotification.tsnew file mode 100644index 0000000000..a5bff3483d--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotification.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++import type { ApiUserNotificationAllOf } from './apiUserNotificationAllOf';+import type { Entity } from './entity';++export type ApiUserNotification = Entity & ApiUserNotificationAllOf;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOf.tsnew file mode 100644index 0000000000..45c12a25bf--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOf.ts@@ -0,0 +1,37 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiUserNotificationAllOfDeletedAt } from './apiUserNotificationAllOfDeletedAt';+import type { ApiUserNotificationAllOfSenderId } from './apiUserNotificationAllOfSenderId';+import type { ApiUserNotificationAllOfUpdatedAt } from './apiUserNotificationAllOfUpdatedAt';+import type { ApiUserNotificationAllOfViewedAt } from './apiUserNotificationAllOfViewedAt';+import type { NotifEvent } from './notifEvent';++export type ApiUserNotificationAllOf = {+ /** When the notification was created. */+ createdAt: number;+ /** When the notification was deleted. */+ deletedAt: ApiUserNotificationAllOfDeletedAt;+ /** Whether the notification is marked as done. */+ done: boolean;+ /** The notification ID. */+ id: string;+ /** The notification event type string (e.g. "channel_mention").+TODO make this a new type */+ notificationEventType: string;+ /** Deserialized notification metadata. */+ notificationMetadata: NotifEvent;+ /** The user who owns this notification. */+ ownerId: string;+ /** The user who triggered the notification. */+ senderId?: ApiUserNotificationAllOfSenderId;+ /** Whether the notification has been sent. */+ sent: boolean;+ /** When the notification was last updated. */+ updatedAt: ApiUserNotificationAllOfUpdatedAt;+ /** When the notification was viewed/seen. */+ viewedAt: ApiUserNotificationAllOfViewedAt;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetUserNotificationsByEventItemIdRequest.ts b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfDeletedAt.tssimilarity index 53%rename from js/app/packages/service-clients/service-notification/generated/schemas/bulkGetUserNotificationsByEventItemIdRequest.tsrename to js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfDeletedAt.tsindex 4bb794a35d..2f728764f2 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetUserNotificationsByEventItemIdRequest.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfDeletedAt.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/-export interface BulkGetUserNotificationsByEventItemIdRequest {- eventItemIds: string[];-}+/**+ * When the notification was deleted.+ */+export type ApiUserNotificationAllOfDeletedAt = number | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfSenderId.ts b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfSenderId.tsnew file mode 100644index 0000000000..78b1de1fbc--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfSenderId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The user who triggered the notification.+ */+export type ApiUserNotificationAllOfSenderId = string | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfUpdatedAt.ts b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfUpdatedAt.tsnew file mode 100644index 0000000000..0183f78fd8--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfUpdatedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the notification was last updated.+ */+export type ApiUserNotificationAllOfUpdatedAt = number | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfViewedAt.ts b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfViewedAt.tsnew file mode 100644index 0000000000..03b083b422--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/apiUserNotificationAllOfViewedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the notification was viewed/seen.+ */+export type ApiUserNotificationAllOfViewedAt = number | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetByEventItemIdsRequest.ts b/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetByEventItemIdsRequest.tsnew file mode 100644index 0000000000..d230558ab3--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetByEventItemIdsRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request body for bulk-fetching notifications by event item IDs.+ */+export interface BulkGetByEventItemIdsRequest {+ /** The event item IDs to filter notifications by. */+ eventItemIds: string[];+}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetUserNotificationsByEventItemIdParams.ts b/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetTypedNotificationsByEventItemIdsParams.tssimilarity index 60%rename from js/app/packages/service-clients/service-notification/generated/schemas/bulkGetUserNotificationsByEventItemIdParams.tsrename to js/app/packages/service-clients/service-notification/generated/schemas/bulkGetTypedNotificationsByEventItemIdsParams.tsindex 77ad189f3e..13f9bc92a2 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetUserNotificationsByEventItemIdParams.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/bulkGetTypedNotificationsByEventItemIdsParams.ts@@ -5,14 +5,14 @@* OpenAPI spec version: 0.1.0*/-export type BulkGetUserNotificationsByEventItemIdParams = {+export type BulkGetTypedNotificationsByEventItemIdsParams = {/*** Size limit per page. Default 20, max 500.* @minimum 0*/- limit: number;+ limit?: number;/**- * Cursor value. Base64 encoded timestamp and item id, separated by |.+ * Cursor value. Base64 encoded timestamp and item id.*/cursor?: string;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponse.ts b/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponse.tsindex 2aff286bf6..36715d133c 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponse.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponse.ts@@ -4,11 +4,15 @@* notification_service* OpenAPI spec version: 0.1.0*/-+import type { ApiUserNotification } from './apiUserNotification';import type { GetAllUserNotificationsResponseNextCursor } from './getAllUserNotificationsResponseNextCursor';-import type { UserNotification } from './userNotification';+/**+ * The strongly typed response for listing user notifications.+ */export interface GetAllUserNotificationsResponse {- items: UserNotification[];+ /** The list of items returned. */+ items: ApiUserNotification[];+ /** The next page cursor if it exists. */next_cursor?: GetAllUserNotificationsResponseNextCursor;}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponseNextCursor.ts b/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponseNextCursor.tsindex fdc6683de3..288c79c993 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponseNextCursor.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/getAllUserNotificationsResponseNextCursor.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * The next page cursor if it exists.+ */export type GetAllUserNotificationsResponseNextCursor = string | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/getTypedNotificationsByEventItemIdParams.ts b/js/app/packages/service-clients/service-notification/generated/schemas/getTypedNotificationsByEventItemIdParams.tsnew file mode 100644index 0000000000..d30f63a3f5--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/getTypedNotificationsByEventItemIdParams.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type GetTypedNotificationsByEventItemIdParams = {+ /**+ * Size limit per page.+ * @minimum 0+ */+ limit?: number;+ /**+ * Cursor value. Base64 encoded timestamp and item id.+ */+ cursor?: string;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/getUserNotificationsByEventItemIdParams.ts b/js/app/packages/service-clients/service-notification/generated/schemas/getUserNotificationsByEventItemIdParams.tsdeleted file mode 100644index 91e8d2ce2c..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/getUserNotificationsByEventItemIdParams.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type GetUserNotificationsByEventItemIdParams = {- /**- * Size limit per page. Default 20, max 500.- */- limit: number;- /**- * Cursor value. Base64 encoded timestamp and item id, separated by |.- */- cursor?: string;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.tsindex f0fa4f7c37..9df349a1e6 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts@@ -5,8 +5,14 @@* OpenAPI spec version: 0.1.0*/-export * from './bulkGetUserNotificationsByEventItemIdParams';-export * from './bulkGetUserNotificationsByEventItemIdRequest';+export * from './apiUserNotification';+export * from './apiUserNotificationAllOf';+export * from './apiUserNotificationAllOfDeletedAt';+export * from './apiUserNotificationAllOfSenderId';+export * from './apiUserNotificationAllOfUpdatedAt';+export * from './apiUserNotificationAllOfViewedAt';+export * from './bulkGetByEventItemIdsRequest';+export * from './bulkGetTypedNotificationsByEventItemIdsParams';export * from './channelInviteMetadata';export * from './channelInviteMetadataAllOf';export * from './channelMentionMetadata';@@ -33,8 +39,7 @@ export * from './entityType';export * from './errorResponse';export * from './getAllUserNotificationsResponse';export * from './getAllUserNotificationsResponseNextCursor';-export * from './getUserNotificationParams';-export * from './getUserNotificationsByEventItemIdParams';+export * from './getTypedNotificationsByEventItemIdParams';export * from './inviteToTeamMetadata';export * from './inviteToTeamMetadataRole';export * from './itemSharedMetadata';@@ -43,8 +48,26 @@ export * from './itemSharedMetadataPermissionLevel';export * from './itemSharedOrganizationMetadata';export * from './itemSharedOrganizationMetadataItemName';export * from './itemSharedOrganizationMetadataPermissionLevel';+export * from './listTypedNotificationsParams';export * from './newEmailMetadata';export * from './newEmailMetadataSender';+export * from './notifEvent';+export * from './notifEventOneOf';+export * from './notifEventOneOfFive';+export * from './notifEventOneOfFiveTag';+export * from './notifEventOneOfNine';+export * from './notifEventOneOfNineTag';+export * from './notifEventOneOfOnefive';+export * from './notifEventOneOfOnefiveTag';+export * from './notifEventOneOfOneone';+export * from './notifEventOneOfOneoneTag';+export * from './notifEventOneOfOnethree';+export * from './notifEventOneOfOnethreeTag';+export * from './notifEventOneOfSeven';+export * from './notifEventOneOfSevenTag';+export * from './notifEventOneOfTag';+export * from './notifEventOneOfThree';+export * from './notifEventOneOfThreeTag';export * from './notification';export * from './notificationAllOf';export * from './notificationAllOfSenderId';diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/getUserNotificationParams.ts b/js/app/packages/service-clients/service-notification/generated/schemas/listTypedNotificationsParams.tssimilarity index 51%rename from js/app/packages/service-clients/service-notification/generated/schemas/getUserNotificationParams.tsrename to js/app/packages/service-clients/service-notification/generated/schemas/listTypedNotificationsParams.tsindex 0dfd33e025..71c8209f79 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/getUserNotificationParams.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/listTypedNotificationsParams.ts@@ -5,13 +5,14 @@* OpenAPI spec version: 0.1.0*/-export type GetUserNotificationParams = {+export type ListTypedNotificationsParams = {/**- * Size limit per page. Default 20, max 500.+ * Size limit per page.+ * @minimum 0*/- limit: number;+ limit?: number;/**- * Base 64 encoded cursor+ * Cursor value. Base64 encoded timestamp and item id.*/cursor?: string;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.tsnew file mode 100644index 0000000000..485865839b--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts@@ -0,0 +1,32 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOf } from './notifEventOneOf';+import type { NotifEventOneOfFive } from './notifEventOneOfFive';+import type { NotifEventOneOfNine } from './notifEventOneOfNine';+import type { NotifEventOneOfOnefive } from './notifEventOneOfOnefive';+import type { NotifEventOneOfOneone } from './notifEventOneOfOneone';+import type { NotifEventOneOfOnethree } from './notifEventOneOfOnethree';+import type { NotifEventOneOfSeven } from './notifEventOneOfSeven';+import type { NotifEventOneOfThree } from './notifEventOneOfThree';++/**+ * Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`+as the serde adjacently-tagged field names so it can be deserialized from the+shape produced by [`UserNotificationRow::into_tagged`] ++[`UserNotificationRow::into_json`].++Only includes variants whose metadata types implement the `Notification` trait.+ */+export type NotifEvent =+ | NotifEventOneOf+ | NotifEventOneOfThree+ | NotifEventOneOfFive+ | NotifEventOneOfSeven+ | NotifEventOneOfNine+ | NotifEventOneOfOneone+ | NotifEventOneOfOnethree+ | NotifEventOneOfOnefive;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOf.tsnew file mode 100644index 0000000000..a0a1c58702--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfTag } from './notifEventOneOfTag';++/**+ * Someone mentioned you in a channel.+ */+export type NotifEventOneOf = {+ /** Someone mentioned you in a channel. */+ content: unknown;+ tag: NotifEventOneOfTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFive.tsnew file mode 100644index 0000000000..5e90268405--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFive.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfFiveTag } from './notifEventOneOfFiveTag';++/**+ * The user was invited to a channel.+ */+export type NotifEventOneOfFive = {+ /** The user was invited to a channel. */+ content: unknown;+ tag: NotifEventOneOfFiveTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFiveTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFiveTag.tsnew file mode 100644index 0000000000..f150ced342--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFiveTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfFiveTag =+ (typeof NotifEventOneOfFiveTag)[keyof typeof NotifEventOneOfFiveTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfFiveTag = {+ channel_invite: 'channel_invite',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNine.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNine.tsnew file mode 100644index 0000000000..f963be0223--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNine.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfNineTag } from './notifEventOneOfNineTag';++/**+ * Someone replied to a thread in a channel that the user is part of.+ */+export type NotifEventOneOfNine = {+ /** Someone replied to a thread in a channel that the user is part of. */+ content: unknown;+ tag: NotifEventOneOfNineTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNineTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNineTag.tsnew file mode 100644index 0000000000..05a2ac4a0f--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNineTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfNineTag =+ (typeof NotifEventOneOfNineTag)[keyof typeof NotifEventOneOfNineTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfNineTag = {+ channel_message_reply: 'channel_message_reply',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefive.tsnew file mode 100644index 0000000000..f7443e4301--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefive.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfOnefiveTag } from './notifEventOneOfOnefiveTag';++/**+ * A user was assigned to a task.+ */+export type NotifEventOneOfOnefive = {+ /** A user was assigned to a task. */+ content: unknown;+ tag: NotifEventOneOfOnefiveTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefiveTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefiveTag.tsnew file mode 100644index 0000000000..97d8d0e7b5--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefiveTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfOnefiveTag =+ (typeof NotifEventOneOfOnefiveTag)[keyof typeof NotifEventOneOfOnefiveTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfOnefiveTag = {+ task_assigned: 'task_assigned',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneone.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneone.tsnew file mode 100644index 0000000000..c53e3aaf7c--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneone.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfOneoneTag } from './notifEventOneOfOneoneTag';++/**+ * A new email has been sent to the user.+ */+export type NotifEventOneOfOneone = {+ /** A new email has been sent to the user. */+ content: unknown;+ tag: NotifEventOneOfOneoneTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneoneTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneoneTag.tsnew file mode 100644index 0000000000..af04788408--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneoneTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfOneoneTag =+ (typeof NotifEventOneOfOneoneTag)[keyof typeof NotifEventOneOfOneoneTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfOneoneTag = {+ new_email: 'new_email',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethree.tsnew file mode 100644index 0000000000..e5635943bb--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethree.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfOnethreeTag } from './notifEventOneOfOnethreeTag';++/**+ * A user was invited to a team.+ */+export type NotifEventOneOfOnethree = {+ /** A user was invited to a team. */+ content: unknown;+ tag: NotifEventOneOfOnethreeTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethreeTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethreeTag.tsnew file mode 100644index 0000000000..0f32334084--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethreeTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfOnethreeTag =+ (typeof NotifEventOneOfOnethreeTag)[keyof typeof NotifEventOneOfOnethreeTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfOnethreeTag = {+ invite_to_team: 'invite_to_team',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSeven.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSeven.tsnew file mode 100644index 0000000000..94044d715f--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSeven.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfSevenTag } from './notifEventOneOfSevenTag';++/**+ * A user sent a message in a channel.+ */+export type NotifEventOneOfSeven = {+ /** A user sent a message in a channel. */+ content: unknown;+ tag: NotifEventOneOfSevenTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSevenTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSevenTag.tsnew file mode 100644index 0000000000..33521eafb2--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSevenTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfSevenTag =+ (typeof NotifEventOneOfSevenTag)[keyof typeof NotifEventOneOfSevenTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfSevenTag = {+ channel_message_send: 'channel_message_send',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTag.tsnew file mode 100644index 0000000000..97fd21d675--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfTag =+ (typeof NotifEventOneOfTag)[keyof typeof NotifEventOneOfTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfTag = {+ channel_mention: 'channel_mention',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThree.tsnew file mode 100644index 0000000000..c4e6a4590c--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThree.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotifEventOneOfThreeTag } from './notifEventOneOfThreeTag';++/**+ * Someone mentioned you in a document.+ */+export type NotifEventOneOfThree = {+ /** Someone mentioned you in a document. */+ content: unknown;+ tag: NotifEventOneOfThreeTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeTag.tsnew file mode 100644index 0000000000..235cb87a62--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThreeTag.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotifEventOneOfThreeTag =+ (typeof NotifEventOneOfThreeTag)[keyof typeof NotifEventOneOfThreeTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfThreeTag = {+ document_mention: 'document_mention',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationBulkRequest.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationBulkRequest.tsindex adfa50b79e..dfcd0b4dc3 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationBulkRequest.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationBulkRequest.ts@@ -5,6 +5,9 @@* OpenAPI spec version: 0.1.0*/+/**+ * the notification ids that we are bulk updating+ */export interface NotificationBulkRequest {/** The ids of the notifications to handle */notificationIds: string[];diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex c9ce1043e1..cbadb63ca9 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -409,26 +409,28 @@}}},- "/user_notifications": {+ "/v1/user_notifications": {"get": {- "tags": ["user_notification::get_user_notification"],- "summary": "Gets the user's unseen notifications in a paginated format.",- "operationId": "get_user_notification",+ "tags": ["user_notification"],+ "summary": "Wrapper handler that calls the inner generic list handler with `serde_json::Value`,\nthen converts each row to [`UserNotificationRow<NotifEvent>`].",+ "description": "Rows that fail to deserialize are dropped with a warning log.",+ "operationId": "list_typed_notifications","parameters": [{"name": "limit","in": "query",- "description": "Size limit per page. Default 20, max 500.",- "required": true,+ "description": "Size limit per page.",+ "required": false,"schema": {"type": "integer",- "format": "int64"+ "format": "int32",+ "minimum": 0}},{"name": "cursor","in": "query",- "description": "Base 64 encoded cursor",+ "description": "Cursor value. Base64 encoded timestamp and item id.","required": false,"schema": {"type": "string"@@ -479,16 +481,39 @@}}},- "/user_notifications/bulk": {- "delete": {- "tags": ["user_notification::bulk_delete_user_notification"],- "summary": "Marks the user's notifications as deleted",- "operationId": "bulk_delete_user_notification",+ "/v1/user_notifications/item/bulk": {+ "post": {+ "tags": ["user_notification"],+ "summary": "Wrapper handler that calls the inner generic bulk-get handler with `serde_json::Value`,\nthen converts each row to [`UserNotificationRow<NotifEvent>`].",+ "description": "Rows that fail to deserialize are dropped with a warning log.",+ "operationId": "bulk_get_typed_notifications_by_event_item_ids",+ "parameters": [+ {+ "name": "limit",+ "in": "query",+ "description": "Size limit per page. Default 20, max 500.",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "minimum": 0+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Cursor value. Base64 encoded timestamp and item id.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],"requestBody": {"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/NotificationBulkRequest"+ "$ref": "#/components/schemas/BulkGetByEventItemIdsRequest"}}},@@ -500,94 +525,37 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/GetAllUserNotificationsResponse"}}}- }- }- }- },- "/user_notifications/bulk/done": {- "patch": {- "tags": ["user_notification::bulk_mark_user_notification_done"],- "summary": "Marks the user's notifications as done",- "operationId": "bulk_mark_user_notification_done",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/NotificationBulkRequest"- }- }},- "required": true- },- "responses": {- "200": {+ "400": {"description": "","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/ErrorResponse"}}}- }- }- }- },- "/user_notifications/bulk/seen": {- "patch": {- "tags": ["user_notification::bulk_mark_user_notification_seen"],- "summary": "Marks the user's notifications as seen",- "operationId": "bulk_mark_user_notification_seen",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/NotificationBulkRequest"- }- }},- "required": true- },- "responses": {- "200": {+ "401": {"description": "","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/ErrorResponse"}}}- }- }- }- },- "/user_notifications/bulk/undone": {- "patch": {- "tags": ["user_notification::bulk_mark_user_notification_undone"],- "summary": "Marks the user's notifications as undone.",- "operationId": "bulk_mark_user_notification_undone",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/NotificationBulkRequest"- }- }},- "required": true- },- "responses": {- "200": {+ "500": {"description": "","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/ErrorResponse"}}}@@ -595,19 +563,27 @@}}},- "/user_notifications/item/bulk": {- "post": {- "tags": [- "user_notification::bulk_get_user_notifications_by_event_item_id"- ],- "summary": "Gets the user's notifications for a provided event item ids in a paginated format.\nThis will only return unseen notifications.",- "operationId": "bulk_get_user_notifications_by_event_item_id",+ "/v1/user_notifications/item/{event_item_id}": {+ "get": {+ "tags": ["user_notification"],+ "summary": "Typed wrapper for getting notifications by a single event item ID.",+ "operationId": "get_typed_notifications_by_event_item_id","parameters": [+ {+ "name": "event_item_id",+ "in": "path",+ "description": "The event item ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },{"name": "limit","in": "query",- "description": "Size limit per page. Default 20, max 500.",- "required": true,+ "description": "Size limit per page.",+ "required": false,"schema": {"type": "integer","format": "int32",@@ -617,23 +593,13 @@{"name": "cursor","in": "query",- "description": "Cursor value. Base64 encoded timestamp and item id, separated by |.",+ "description": "Cursor value. Base64 encoded timestamp and item id.","required": false,"schema": {"type": "string"}}],- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/BulkGetUserNotificationsByEventItemIdRequest"- }- }- },- "required": true- },"responses": {"200": {"description": "",@@ -678,38 +644,20 @@}}},- "/user_notifications/item/{event_item_id}": {+ "/v1/user_notifications/{notification_id}": {"get": {- "tags": ["user_notification::get_user_notifications_by_event_item_id"],- "summary": "Gets the user's notifications for a given event item id in a paginated format.",- "operationId": "get_user_notifications_by_event_item_id",+ "tags": ["user_notification"],+ "summary": "Typed wrapper for getting a single notification by ID.",+ "operationId": "get_typed_notification_by_id","parameters": [{- "name": "event_item_id",+ "name": "notification_id","in": "path",- "description": "The event item id",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "limit",- "in": "query",- "description": "Size limit per page. Default 20, max 500.",+ "description": "ID of the notification","required": true,"schema": {- "type": "integer",- "format": "int64"- }- },- {- "name": "cursor",- "in": "query",- "description": "Cursor value. Base64 encoded timestamp and item id, separated by |.",- "required": false,- "schema": {- "type": "string"+ "type": "string",+ "format": "uuid"}}],@@ -719,7 +667,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/GetAllUserNotificationsResponse"+ "$ref": "#/components/schemas/ApiUserNotification"}}}@@ -744,6 +692,16 @@}}},+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {@@ -757,32 +715,128 @@}}},- "/user_notifications/{notification_id}": {- "get": {- "tags": ["user_notification::get_user_notification_by_id"],- "summary": "Gets a single user notification by id.",- "operationId": "get_user_notification_by_id",- "parameters": [- {- "name": "notification_id",- "in": "path",- "description": "ID of the notification",- "required": true,- "schema": {- "type": "string"+ "/v2/user_notifications/bulk": {+ "delete": {+ "tags": ["notification_crate::inbound::http"],+ "summary": "Soft-delete multiple user notifications.",+ "operationId": "bulk_delete_user_notifications_v2",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NotificationBulkRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": ""+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }}}- ],+ }+ }+ },+ "/v2/user_notifications/bulk/done": {+ "patch": {+ "tags": ["notification_crate::inbound::http"],+ "summary": "Mark notifications as done.",+ "operationId": "bulk_mark_notifications_done",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NotificationBulkRequest"+ }+ }+ },+ "required": true+ },"responses": {"200": {+ "description": ""+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {"description": "","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/UserNotification"+ "$ref": "#/components/schemas/ErrorResponse"}}}+ }+ }+ }+ },+ "/v2/user_notifications/bulk/seen": {+ "patch": {+ "tags": ["notification_crate::inbound::http"],+ "summary": "Mark notifications as seen.",+ "operationId": "bulk_mark_notifications_seen",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NotificationBulkRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": ""},"400": {"description": "",@@ -804,7 +858,49 @@}}},- "404": {+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/v2/user_notifications/bulk/undone": {+ "patch": {+ "tags": ["notification_crate::inbound::http"],+ "summary": "Mark notifications as not done.",+ "operationId": "bulk_mark_notifications_undone",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NotificationBulkRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": ""+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {"description": "","content": {"application/json": {@@ -825,11 +921,13 @@}}}- },+ }+ },+ "/v2/user_notifications/{notification_id}": {"delete": {- "tags": ["user_notification::delete_user_notification"],- "summary": "Marks the user's notification as deleted.",- "operationId": "delete_user_notification",+ "tags": ["notification_crate::inbound::http"],+ "summary": "Soft-delete a single user notification.",+ "operationId": "delete_user_notification_v2","parameters": [{"name": "notification_id",@@ -837,17 +935,41 @@"description": "ID of the notification","required": true,"schema": {- "type": "string"+ "type": "string",+ "format": "uuid"}}],"responses": {"200": {+ "description": ""+ },+ "400": {"description": "","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"}}}@@ -858,15 +980,92 @@},"components": {"schemas": {- "BulkGetUserNotificationsByEventItemIdRequest": {+ "ApiUserNotification": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Entity",+ "description": "The entity the notification is about."+ },+ {+ "type": "object",+ "required": [+ "ownerId",+ "id",+ "notificationEventType",+ "sent",+ "done",+ "createdAt",+ "viewedAt",+ "updatedAt",+ "deletedAt",+ "notificationMetadata"+ ],+ "properties": {+ "createdAt": {+ "type": "integer",+ "format": "int64",+ "description": "When the notification was created."+ },+ "deletedAt": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "When the notification was deleted."+ },+ "done": {+ "type": "boolean",+ "description": "Whether the notification is marked as done."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The notification ID."+ },+ "notificationEventType": {+ "type": "string",+ "description": "The notification event type string (e.g. \"channel_mention\").\nTODO make this a new type"+ },+ "notificationMetadata": {+ "$ref": "#/components/schemas/NotifEvent",+ "description": "Deserialized notification metadata."+ },+ "ownerId": {+ "type": "string",+ "description": "The user who owns this notification."+ },+ "senderId": {+ "type": ["string", "null"],+ "description": "The user who triggered the notification."+ },+ "sent": {+ "type": "boolean",+ "description": "Whether the notification has been sent."+ },+ "updatedAt": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "When the notification was last updated."+ },+ "viewedAt": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "When the notification was viewed/seen."+ }+ }+ }+ ]+ },+ "BulkGetByEventItemIdsRequest": {"type": "object",+ "description": "Request body for bulk-fetching notifications by event item IDs.","required": ["eventItemIds"],"properties": {"eventItemIds": {"type": "array","items": {- "type": "string"- }+ "type": "string",+ "format": "uuid"+ },+ "description": "The event item IDs to filter notifications by."}}},@@ -1100,16 +1299,19 @@},"GetAllUserNotificationsResponse": {"type": "object",+ "description": "The strongly typed response for listing user notifications.","required": ["items"],"properties": {"items": {"type": "array","items": {- "$ref": "#/components/schemas/UserNotification"- }+ "$ref": "#/components/schemas/ApiUserNotification"+ },+ "description": "The list of items returned."},"next_cursor": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The next page cursor if it exists."}}},@@ -1223,6 +1425,123 @@}}},+ "NotifEvent": {+ "oneOf": [+ {+ "type": "object",+ "description": "Someone mentioned you in a channel.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "Someone mentioned you in a channel."+ },+ "tag": {+ "type": "string",+ "enum": ["channel_mention"]+ }+ }+ },+ {+ "type": "object",+ "description": "Someone mentioned you in a document.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "Someone mentioned you in a document."+ },+ "tag": {+ "type": "string",+ "enum": ["document_mention"]+ }+ }+ },+ {+ "type": "object",+ "description": "The user was invited to a channel.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "The user was invited to a channel."+ },+ "tag": {+ "type": "string",+ "enum": ["channel_invite"]+ }+ }+ },+ {+ "type": "object",+ "description": "A user sent a message in a channel.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "A user sent a message in a channel."+ },+ "tag": {+ "type": "string",+ "enum": ["channel_message_send"]+ }+ }+ },+ {+ "type": "object",+ "description": "Someone replied to a thread in a channel that the user is part of.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "Someone replied to a thread in a channel that the user is part of."+ },+ "tag": {+ "type": "string",+ "enum": ["channel_message_reply"]+ }+ }+ },+ {+ "type": "object",+ "description": "A new email has been sent to the user.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "A new email has been sent to the user."+ },+ "tag": {+ "type": "string",+ "enum": ["new_email"]+ }+ }+ },+ {+ "type": "object",+ "description": "A user was invited to a team.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "A user was invited to a team."+ },+ "tag": {+ "type": "string",+ "enum": ["invite_to_team"]+ }+ }+ },+ {+ "type": "object",+ "description": "A user was assigned to a task.",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "description": "A user was assigned to a task."+ },+ "tag": {+ "type": "string",+ "enum": ["task_assigned"]+ }+ }+ }+ ],+ "description": "Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait."+ },"Notification": {"allOf": [{@@ -1254,6 +1573,7 @@},"NotificationBulkRequest": {"type": "object",+ "description": "the notification ids that we are bulk updating","required": ["notificationIds"],"properties": {"notificationIds": {diff --git a/justfile b/justfileindex fe6ed60812..6383baaff4 100644--- a/justfile+++ b/justfile@@ -52,7 +52,6 @@ stop-databases:import 'local_stack.just'# Sets up local database-# Assumes postgres is running locally via `just run_dbs`setup_local_dbs:# run dbs detachedjust run_dbs -ddiff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 957d931d21..16d58a9fa8 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -522,7 +522,6 @@ dependencies = ["macro_env","macro_env_var","macro_middleware",- "macro_notify","macro_user_id","macro_uuid","maud",@@ -534,6 +533,7 @@ dependencies = ["models_team","native_app_service","non_empty",+ "notification","notification_service_client","openssl","rand 0.9.0",@@ -1886,7 +1886,6 @@ dependencies = ["macro_env","macro_env_var","macro_middleware",- "macro_notify","macro_user_id","macro_uuid","model",@@ -1895,6 +1894,7 @@ dependencies = ["models_comms","models_opensearch","models_permissions",+ "notification","reqwest","secretsmanager_client","serde",@@ -2632,7 +2632,6 @@ dependencies = ["macro_entrypoint","macro_env","macro_middleware",- "macro_notify","macro_project_utils","macro_share_permissions","macro_user_id",@@ -2723,7 +2722,6 @@ dependencies = ["macro_env","macro_env_var","macro_middleware",- "macro_notify","macro_project_utils","macro_sha_count_client","macro_share_permissions",@@ -2740,6 +2738,7 @@ dependencies = ["models_permissions","models_properties","models_soup",+ "notification","opensearch_client","ordered-float","properties",@@ -3157,7 +3156,6 @@ dependencies = ["macro_env","macro_env_var","macro_middleware",- "macro_notify","macro_user_id","macro_uuid","mailparse",@@ -3171,6 +3169,7 @@ dependencies = ["models_pagination","models_permissions","models_properties",+ "notification","once_cell","redis","regex",@@ -5087,29 +5086,12 @@ dependencies = ["uuid",]-[[package]]-name = "macro_notify"-version = "0.1.0"-dependencies = [- "anyhow",- "aws-sdk-sqs",- "macro_aws_config",- "macro_uuid",- "model",- "model_notifications",- "serde",- "serde_json",- "tracing",- "uuid",-]-[[package]]name = "macro_project_utils"version = "0.1.0"dependencies = ["anyhow","macro_db_client",- "macro_notify","model","sqlx","tokio",@@ -5511,9 +5493,11 @@ dependencies = ["chrono","doppleganger","macro_user_id",+ "mention_utils","model-entity","models_comms","models_pagination",+ "notification","serde","serde_json","sqlx",@@ -5871,20 +5855,27 @@ dependencies = ["aws-sdk-sesv2","aws-sdk-sns","aws-sdk-sqs",+ "axum",+ "chrono","hex","itertools 0.14.0","macro_db_migrator","macro_user_id","model-entity",+ "model-error-response",+ "model_user",+ "models_pagination","redis","reqwest","rootcause","serde","serde_json",+ "sha2","sqlx","thiserror 2.0.17","tokio","tracing",+ "utoipa","uuid",]@@ -5902,6 +5893,7 @@ dependencies = ["model_notifications","models_pagination","serde",+ "serde_json","sqlx","tracing","uuid",@@ -5912,37 +5904,37 @@ name = "notification_service"version = "0.1.0"dependencies = ["anyhow",- "authentication_service_client","aws-sdk-secretsmanager","aws-sdk-sesv2","aws-sdk-sns","aws-sdk-sqs","axum","chrono",- "connection_gateway",- "document_cognition_service_client",- "document_storage_service_client","email_validator","futures","http-body-util","macro_auth","macro_aws_config",- "macro_cache_client","macro_cors","macro_entrypoint","macro_env",+ "macro_env_var","macro_middleware",- "macro_notify","macro_user_id","macro_uuid","mention_utils","model","model-entity",+ "model-error-response","model_file_type","model_notifications",+ "model_user","models_comms","models_pagination",+ "notification","notification_db_client",+ "paste",+ "redis","regex","secretsmanager_client","serde",@@ -6711,7 +6703,6 @@ dependencies = ["macro_db_client","macro_db_migrator","macro_middleware",- "macro_notify","macro_user_id","macro_uuid","mockall",@@ -6719,6 +6710,8 @@ dependencies = ["model_notifications","models_permissions","models_properties",+ "notification",+ "serde","serde_json","sqlx","system_properties",@@ -6755,6 +6748,7 @@ dependencies = ["anyhow","async-trait","aws-sdk-secretsmanager",+ "aws-sdk-sqs","axum","chrono","email_db_client",@@ -6765,11 +6759,11 @@ dependencies = ["macro_entrypoint","macro_env","macro_middleware",- "macro_notify","macro_uuid","model","models_permissions","models_properties",+ "notification","properties","properties_db_client","secretsmanager_client",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex be00a33427..38481bb279 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -54,7 +54,6 @@ members = ["macro_db_migrator","macro_env","macro_middleware",- "macro_notify","macro_project_utils","macro_redis","macro_sha_count_client",diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.tomlindex ef36154448..2654107cb1 100644--- a/rust/cloud-storage/authentication_service/Cargo.toml+++ b/rust/cloud-storage/authentication_service/Cargo.toml@@ -35,7 +35,6 @@ async-stripe = { workspace = true, default-features = false, features = [] }async-stripe-webhook = { version = "1.0.0-alpha.4", default-features = false }aws-sdk-secretsmanager = { workspace = true }-macro_aws_config = { path = "../macro_aws_config" }aws-sdk-sesv2 = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["macros"] }@@ -50,6 +49,7 @@ futures = { workspace = true }http-body-util = { workspace = true }jsonwebtoken = { workspace = true }macro_auth = { path = "../macro_auth" }+macro_aws_config = { path = "../macro_aws_config" }macro_cache_client = { path = "../macro_cache_client", default-features = false, features = ["auth","auth_rate_limit",@@ -69,7 +69,6 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"tracking","user_permissions",] }-macro_notify = { path = "../macro_notify" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }maud = { version = "0.27.0" }@@ -81,6 +80,7 @@ model_user = { path = "../model_user", features = ["axum"] }models_team = { path = "../models_team" }native_app_service = { path = "../native_app_service" }non_empty = { path = "../non_empty" }+notification = { path = "../notification" }notification_service_client = { path = "../notification_service_client" }openssl = { workspace = true }rand = { workspace = true }diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 92b2f8f09e..cc094f77b3 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -7,6 +7,8 @@ use macro_env::Environment;use macro_env_var::env_var;use macro_middleware::auth::internal_access::InternalApiSecretKey;use native_app_service::{domain::service::NativeAppServiceImpl, outbound::DefaultBundleFetcher};+use notification::domain::service::NotificationIngressService;+use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};use remote_env_var::LocalOrRemoteSecret;use roles_and_permissions::{domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,@@ -27,7 +29,8 @@ pub(crate) struct ApiContext {Arc<document_storage_service_client::DocumentStorageServiceClient>,pub notification_service_client: Arc<notification_service_client::NotificationServiceClient>,pub ses_client: Arc<ses_client::Ses>,- pub macro_notify_client: Arc<macro_notify::MacroNotify>,+ pub notification_ingress_service:+ Arc<NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>>,pub sqs_client: Arc<sqs_client::SQS>,pub environment: Environment,pub jwt_args: JwtValidationArgs,diff --git a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rsindex b31c64fc49..db82d355d0 100644--- a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs+++ b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs@@ -1,3 +1,5 @@+use std::collections::HashSet;+use axum::{Extension, Json,extract::{self, Path, State},@@ -9,6 +11,8 @@ use macro_user_id::{};use model_entity::EntityType;use model_user::axum_extractor::MacroUserExtractor;+use notification::domain::models::SendNotificationRequestBuilder;+use notification::domain::service::NotificationIngress;use teams::domain::{model::{InviteUsersToTeamError, TeamInvite},team_repo::TeamService,@@ -22,11 +26,10 @@ use crate::api::{},team::TeamPathParam,};+use model_notifications::InviteToTeamMetadata;use model::{response::ErrorResponse, tracking::IPContext};-use model_notifications::{InviteToTeamMetadata, NotificationQueueMessage};-/// The request body to invite a user to a team#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]pub struct InviteToTeamRequest {@@ -145,13 +148,13 @@ pub async fn handler(// Send the invitestokio::spawn({let db = ctx.db.clone();- let macro_notify_client = ctx.macro_notify_client.clone();+ let notification_ingress_service = ctx.notification_ingress_service.clone();let team_invites = team_invites.clone();let invited_by = user_context.macro_user_id;async move {let _ = notify_team_invite(&db,- ¯o_notify_client,+ &*notification_ingress_service,&team_id,team_invites,invited_by,@@ -166,32 +169,38 @@ pub async fn handler(pub(in crate::api::team) async fn notify_team_invite(db: &sqlx::Pool<sqlx::Postgres>,- macro_notify_client: ¯o_notify::MacroNotify,+ notification_ingress_service: &impl NotificationIngress,team_id: &uuid::Uuid,team_invites: Vec<TeamInvite<'_>>,invited_by: MacroUserIdStr<'static>,) -> anyhow::Result<()> {let team_name = macro_db_client::team::get::get_team_name(db, team_id).await?;- let notification_metadata = InviteToTeamMetadata {- invited_by: invited_by.clone(),- team_name: team_name.clone(),- team_id: team_id.to_string(),- role: None,- };-for team_invite in team_invites {- let notification_queue_message = NotificationQueueMessage {- notification_entity: EntityType::Team- .with_entity_string(team_invite.team_invite_id.to_string()),- notification_event: notification_metadata.clone().into(),- sender_id: Some(invited_by.clone()),- recipient_ids: Some(vec![format!("macro|{}", team_invite.email.as_ref())]),+ let notification = InviteToTeamMetadata {+ invited_by: invited_by.clone(),+ team_name: team_name.clone(),+ team_id: team_id.to_string(),+ role: None,};- macro_notify_client- .send_notification(notification_queue_message)- .await?;+ let recipient = MacroUserIdStr::try_from_email(team_invite.email.as_ref())+ .map_err(|e| anyhow::anyhow!("failed to parse email as macro user id: {}", e))?;++ let entity_id = team_invite.team_invite_id.to_string();+ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Team.with_entity_str(&entity_id),+ notification,+ sender_id: Some(invited_by.clone()),+ recipient_ids: HashSet::from([recipient]),+ }+ .into_request()+ .with_conn_gateway();++ notification_ingress_service+ .send_notification(request)+ .await+ .map_err(|e| anyhow::anyhow!("failed to send notification: {}", e))?;}Ok(())diff --git a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rsindex 4203ffdc50..e9b3cd5f31 100644--- a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs+++ b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs@@ -1,3 +1,5 @@+use std::collections::HashSet;+use axum::{Extension, Json,extract::{Path, State},@@ -6,12 +8,14 @@ use axum::{};use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;-use model_notifications::{InviteToTeamMetadata, NotificationQueueMessage};+use notification::domain::models::SendNotificationRequestBuilder;+use notification::domain::service::NotificationIngress;use crate::api::{context::ApiContext,middleware::team_access::{AdminRole, TeamAccessRoleExtractor},};+use model_notifications::InviteToTeamMetadata;use model::{response::{EmptyResponse, ErrorResponse},@@ -101,14 +105,14 @@ pub async fn handler(tokio::spawn({let db = ctx.db.clone();- let macro_notify_client = ctx.macro_notify_client.clone();+ let notification_ingress_service = ctx.notification_ingress_service.clone();let normalized_email = team_invite.email;let invited_by = user_context.macro_user_id;let team_invite_id = team_invite.id;async move {let _ = notify_team_invite(&db,- ¯o_notify_client,+ &*notification_ingress_service,&team_id,&team_invite_id,invited_by,@@ -124,7 +128,7 @@ pub async fn handler(async fn notify_team_invite(db: &sqlx::Pool<sqlx::Postgres>,- macro_notify_client: ¯o_notify::MacroNotify,+ notification_ingress_service: &impl NotificationIngress,team_id: &uuid::Uuid,team_invite_id: &uuid::Uuid,invited_by: MacroUserIdStr<'static>,@@ -132,23 +136,30 @@ async fn notify_team_invite() -> anyhow::Result<()> {let team_name = macro_db_client::team::get::get_team_name(db, team_id).await?;- let notification_metadata = InviteToTeamMetadata {+ let notification = InviteToTeamMetadata {invited_by: invited_by.clone(),team_name: team_name.clone(),team_id: team_id.to_string(),role: None,};- let notification_queue_message = NotificationQueueMessage {- notification_entity: EntityType::Team.with_entity_string(team_invite_id.to_string()),- notification_event: notification_metadata.into(),+ let recipient = MacroUserIdStr::try_from_email(normalized_email)+ .map_err(|e| anyhow::anyhow!("failed to parse email as macro user id: {}", e))?;++ let entity_id = team_invite_id.to_string();+ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Team.with_entity_str(&entity_id),+ notification,sender_id: Some(invited_by),- recipient_ids: Some(vec![format!("macro|{normalized_email}")]),- };+ recipient_ids: HashSet::from([recipient]),+ }+ .into_request()+ .with_conn_gateway();- macro_notify_client- .send_notification(notification_queue_message)- .await?;+ notification_ingress_service+ .send_notification(request)+ .await+ .map_err(|e| anyhow::anyhow!("failed to send notification: {}", e))?;Ok(())}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex e948f3f3ce..c90b1f839f 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -8,6 +8,9 @@ use native_app_service::{domain::{models::PlatformData, service::NativeAppServiceImpl},outbound::DefaultBundleFetcher,};+use notification::domain::service::NotificationIngressService;+use notification::outbound::queue::SqsNotificationQueue;+use notification::outbound::repository::DbNotificationRepository;use notification_service_client::NotificationServiceClient;use roles_and_permissions::{domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,@@ -162,12 +165,14 @@ async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;- let macro_notify_client = macro_notify::MacroNotify::new(+ let notification_repository = DbNotificationRepository::new(db.clone());+ let notification_queue = SqsNotificationQueue::new(+ aws_sdk_sqs::Client::new(¯o_aws_config::get_macro_aws_config().await),config.notification_queue.clone(),- "authentication_service".to_string(),- )- .await;- tracing::trace!("initialized macro_notify client");+ );+ let notification_ingress_service =+ NotificationIngressService::new(notification_repository, notification_queue);+ tracing::trace!("initialized notification ingress service");let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(¯o_aws_config::get_macro_aws_config().await,@@ -200,7 +205,7 @@ async fn main() -> anyhow::Result<()> {document_storage_service_client: Arc::new(document_storage_service_client),notification_service_client: Arc::new(notification_service_client),ses_client: Arc::new(ses_client),- macro_notify_client: Arc::new(macro_notify_client),+ notification_ingress_service: Arc::new(notification_ingress_service),sqs_client: Arc::new(sqs_client),environment: config.environment,jwt_args,diff --git a/rust/cloud-storage/comms_service/Cargo.toml b/rust/cloud-storage/comms_service/Cargo.tomlindex c370e1bb25..09ae25ce6c 100644--- a/rust/cloud-storage/comms_service/Cargo.toml+++ b/rust/cloud-storage/comms_service/Cargo.toml@@ -36,7 +36,6 @@ chrono = { workspace = true }comms = { path = "../comms", features = ["inbound", "outbound"] }comms_db_client = { path = "../comms_db_client", optional = true }connection_gateway = { path = "../connection_gateway" }-macro_db_client = { path = "../macro_db_client" }doppleganger = { workspace = true }frecency = { path = "../frecency", features = ["postgres"] }futures = { workspace = true }@@ -46,6 +45,7 @@ macro_auth = { path = "../macro_auth" }macro_aws_config = { path = "../macro_aws_config" }macro_axum_utils = { path = "../macro_axum_utils" }macro_cors = { path = "../macro_cors" }+macro_db_client = { path = "../macro_db_client" }macro_entrypoint = { path = "../macro_entrypoint" }macro_env = { path = "../macro_env" }macro_env_var = { path = "../macro_env_var" }@@ -53,15 +53,15 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"auth","cloud_storage",] }-macro_uuid = { path = "../macro_uuid" }-macro_notify = { path = "../macro_notify" }macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }models_comms = { path = "../models_comms" }models_opensearch = { path = "../models_opensearch" }models_permissions = { path = "../models_permissions" }+notification_hex = { path = "../notification", package = "notification" }reqwest.workspace = truesecretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }diff --git a/rust/cloud-storage/comms_service/README.md b/rust/cloud-storage/comms_service/README.mdindex 0ccba7b79a..1ddeca0c5a 100644--- a/rust/cloud-storage/comms_service/README.md+++ b/rust/cloud-storage/comms_service/README.md@@ -51,13 +51,6 @@ If required, you can just point to a local instance of comms.Please see the [comms_db_client](../comms_db_client) for more details.-## Interactions with `macro_notify`--The `macro_notify` crate is used to send notifications to the client.--While this also uses the `connection_gateway`, notifications are seperate from the websocket updates the comms service send directly to the gateway.--# Technical Documentation## Creating Channelsdiff --git a/rust/cloud-storage/comms_service/src/api/context.rs b/rust/cloud-storage/comms_service/src/api/context.rsindex 5b839c6bba..62d8cfa61e 100644--- a/rust/cloud-storage/comms_service/src/api/context.rs+++ b/rust/cloud-storage/comms_service/src/api/context.rs@@ -8,10 +8,17 @@ use connection_gateway_client::client::ConnectionGatewayClient;use frecency::outbound::postgres::FrecencyPgStorage;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;+use notification_hex::domain::service::NotificationIngressService;+use notification_hex::outbound::{+ queue::SqsNotificationQueue, repository::DbNotificationRepository,+};use secretsmanager_client::LocalOrRemoteSecret;use sqlx::PgPool;use std::sync::Arc;+pub type NotificationIngressType =+ NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+env_var! {#[derive(Clone)]pub struct DocumentPermissionJwtSecretKey;@@ -22,7 +29,7 @@ pub struct AppState {pub jwt_validation_args: JwtValidationArgs,pub db: PgPool,pub connection_gateway_client: Arc<ConnectionGatewayClient>,- pub macro_notify_client: Arc<macro_notify::MacroNotify>,+ pub notification_ingress_service: Arc<NotificationIngressType>,pub sqs_client: Arc<sqs_client::SQS>,pub permissions_token_secret: LocalOrRemoteSecret<DocumentPermissionJwtSecretKey>,pub frecency_storage: FrecencyPgStorage,diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rsindex 301403ad81..d13ef48b73 100644--- a/rust/cloud-storage/comms_service/src/notification.rs+++ b/rust/cloud-storage/comms_service/src/notification.rs@@ -14,6 +14,8 @@ use model_notifications::{ChannelMessageSendMetadata, ChannelReplyMetadata, CommonChannelMetadata,DocumentMentionMetadata, NotificationEvent, NotificationQueueMessage,};+use notification_hex::domain::models::SendNotificationRequestBuilder;+use notification_hex::domain::service::NotificationIngress;use std::{collections::HashSet, iter::once};use uuid::Uuid;@@ -194,6 +196,107 @@ impl ChannelMessageEvent<'_> {}}+async fn send_notification_queue_message(+ ingress: &impl NotificationIngress,+ msg: NotificationQueueMessage,+) -> anyhow::Result<()> {+ let entity = msg.notification_entity;+ let sender_id = msg.sender_id;+ let recipient_ids: HashSet<MacroUserIdStr<'_>> = msg+ .recipient_ids+ .unwrap_or_default()+ .into_iter()+ .filter_map(|id| {+ MacroUserIdStr::parse_from_str(&id)+ .ok()+ .map(|u| u.into_owned())+ })+ .collect();++ match msg.notification_event {+ NotificationEvent::ChannelInvite(metadata) => {+ let req = SendNotificationRequestBuilder {+ notification_entity: entity,+ notification: metadata,+ sender_id,+ recipient_ids,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();+ ingress+ .send_notification(req)+ .await+ .map_err(|e| anyhow::anyhow!("{e}"))?;+ }+ NotificationEvent::ChannelMessageSend(metadata) => {+ let req = SendNotificationRequestBuilder {+ notification_entity: entity,+ notification: metadata,+ sender_id,+ recipient_ids,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();+ ingress+ .send_notification(req)+ .await+ .map_err(|e| anyhow::anyhow!("{e}"))?;+ }+ NotificationEvent::ChannelMention(metadata) => {+ let req = SendNotificationRequestBuilder {+ notification_entity: entity,+ notification: metadata,+ sender_id,+ recipient_ids,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();+ ingress+ .send_notification(req)+ .await+ .map_err(|e| anyhow::anyhow!("{e}"))?;+ }+ NotificationEvent::ChannelMessageReply(metadata) => {+ let req = SendNotificationRequestBuilder {+ notification_entity: entity,+ notification: metadata,+ sender_id,+ recipient_ids,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();+ ingress+ .send_notification(req)+ .await+ .map_err(|e| anyhow::anyhow!("{e}"))?;+ }+ NotificationEvent::ChannelMessageDocument(ChannelMessageDocumentMetadata(metadata)) => {+ let req = SendNotificationRequestBuilder {+ notification_entity: entity,+ notification: metadata,+ sender_id,+ recipient_ids,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();+ ingress+ .send_notification(req)+ .await+ .map_err(|e| anyhow::anyhow!("{e}"))?;+ }+ other => {+ tracing::warn!(?other, "unhandled notification event type in comms_service");+ }+ }++ Ok(())+}+pub async fn dispatch_notifications_for_invite(api_context: &AppState,channel_id: &Uuid,@@ -211,9 +314,7 @@ pub async fn dispatch_notifications_for_invite(let notifications = event.generate_notifications();for notification in notifications {- api_context- .macro_notify_client- .send_notification(notification)+ send_notification_queue_message(&*api_context.notification_ingress_service, notification).await?;}@@ -286,9 +387,7 @@ pub async fn dispatch_notifications_for_message(let notifications = channel_message_event.generate_notifications();for notification in notifications {- api_context- .macro_notify_client- .send_notification(notification)+ send_notification_queue_message(&*api_context.notification_ingress_service, notification).await?;}diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex db55fa40bb..0f7694bff4 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -61,7 +61,6 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"cloud_storage","user_permissions",] }-macro_notify = { path = "../macro_notify" }macro_project_utils = { path = "../macro_project_utils" }macro_share_permissions = { path = "../macro_share_permissions" }macro_user_id = { path = "../macro_user_id" }diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rsindex 86f5293a33..72fe42f900 100644--- a/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs@@ -167,7 +167,6 @@ pub async fn create_user_chat_v2(macro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: req.project_id.clone(),old_project_id: None,diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/delete_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/delete_chat.rsindex 36998e8ed7..da43140049 100644--- a/rust/cloud-storage/document_cognition_service/src/api/chats/delete_chat.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/delete_chat.rs@@ -55,7 +55,6 @@ pub async fn delete_chat_handler(macro_project_utils::update_project_modified(&state.db,- &state.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: chat.project_id.clone(),old_project_id: None,diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rsindex 4b88c39cd9..81ed60ea29 100644--- a/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs@@ -108,7 +108,6 @@ async fn patch_chat_v2(macro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: req.project_id.clone(),old_project_id: chat_context.project_id.clone(),diff --git a/rust/cloud-storage/document_cognition_service/src/api/context.rs b/rust/cloud-storage/document_cognition_service/src/api/context.rsindex cb70db793c..5e64125146 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context.rs@@ -21,7 +21,6 @@ pub struct ApiContext {pub db: PgPool,pub sqs_client: Arc<sqs_client::SQS>,pub document_storage_client: Arc<DocumentStorageServiceClient>,- pub macro_notify_client: Arc<macro_notify::MacroNotify>,pub comms_service_client: Arc<comms_service_client::CommsServiceClient>,pub search_service_client: Arc<SearchServiceClient>,pub scribe: Arc<DcsScribe>,@@ -49,7 +48,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Aruse frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;use lexical_client::LexicalClient;- use macro_notify::MacroNotifyClient;use scribe::ScribeClient;use search_service_client::SearchServiceClient;use soup::domain::service::SoupImpl;@@ -69,8 +67,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar"dummy_auth_key".into(),"http://localhost".into(),));- let macro_notify_client =- MacroNotifyClient::new("dummy_queue".into(), "dummy_service".into()).await;let comms_service_client = Arc::new(CommsServiceClient::new("http://localhost".into()));let search_service_client =SearchServiceClient::new("dummy_auth_key".into(), "http://localhost".into());@@ -135,7 +131,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ardb: pool.clone(),sqs_client: Arc::new(sqs_client),document_storage_client,- macro_notify_client: Arc::new(macro_notify_client),comms_service_client,search_service_client: Arc::new(search_service_client),scribe: Arc::new(content_client),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex f2a40e8c32..ad36d91920 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -76,13 +76,6 @@ async fn main() -> anyhow::Result<()> {InternalApiSecretKey::new().context("failed to create internal auth key")?,);- let macro_notify_client = macro_notify::MacroNotify::new(- config.notification_queue.clone(),- "document_cognition_service".to_string(),- )- .await;- tracing::info!("initialized macro_notify client");-let document_storage_client = DocumentStorageServiceClient::new(internal_auth_key.as_ref().to_string(),config.document_storage_service_url.clone(),@@ -200,7 +193,6 @@ async fn main() -> anyhow::Result<()> {),sqs_client: Arc::new(sqs_client),document_storage_client: Arc::new(document_storage_client),- macro_notify_client: Arc::new(macro_notify_client),comms_service_client: Arc::new(comms_service_client),search_service_client: Arc::new(search_service_client),jwt_args,diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 1416bc459a..52dd57e508 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -68,7 +68,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"cloud_storage","user_permissions",] }-macro_notify = { path = "../macro_notify" }+notification = { path = "../notification" }macro_project_utils = { path = "../macro_project_utils" }macro_sha_count_client = { path = "../macro_sha_count_client" }macro_share_permissions = { path = "../macro_share_permissions" }diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rsindex 606192304b..1501392e5c 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs@@ -24,6 +24,8 @@ use model::{response::ErrorResponse,user::UserContext,};+use notification::domain::service::{NotificationIngress, NotificationIngressService};+use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};use sqlx::PgPool;use super::comment_error_response;@@ -51,7 +53,9 @@ pub struct Params {)]#[axum::debug_handler(state = ApiContext)]pub async fn create_comment_handler(- State(macro_notify_client): State<Arc<macro_notify::MacroNotify>>,+ State(notification_ingress_service): State<+ Arc<NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>>,+ >,State(db): State<PgPool>,State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,Extension(UserContext { user_id, .. }): Extension<UserContext>,@@ -71,7 +75,7 @@ pub async fn create_comment_handler(match create_document_comment(&db, &document_id, &user_id, &req).await {Ok(res) => {if let Some(Mentions { users, mention_id }) = &req.mentions {- let notif = build_mention_notif(+ let request = build_mention_notif(NotifLocationType::CreateComment,req.text,res.comment_thread.comments.first(),@@ -83,11 +87,15 @@ pub async fn create_comment_handler(user_id.clone().try_into().ok(),document_id.to_string(),mention_id,- );- _ = macro_notify_client- .send_notification(notif)+ )+ .into_request()+ .with_apns()+ .with_conn_gateway();++ _ = notification_ingress_service+ .send_notification(request).await- .inspect_err(|e| tracing::error!(error =? e, "coundn't send document mention notification"));+ .inspect_err(|e| tracing::error!(error =? e, "couldn't send document mention notification"));}update_live_comment_state(&conn_gateway_client,diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rsindex cc6b554534..36abf15f7f 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs@@ -20,6 +20,8 @@ use model::{response::ErrorResponse,user::UserContext,};+use notification::domain::service::{NotificationIngress, NotificationIngressService};+use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};use sqlx::PgPool;use super::comment_error_response;@@ -46,7 +48,9 @@ pub struct Params {)]pub async fn edit_comment_handler(State(db): State<PgPool>,- State(macro_notify_client): State<Arc<macro_notify::MacroNotify>>,+ State(notification_ingress_service): State<+ Arc<NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>>,+ >,State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,Extension(UserContext { user_id, .. }): Extension<UserContext>,Path(Params { comment_id }): Path<Params>,@@ -56,7 +60,7 @@ pub async fn edit_comment_handler(match edit_document_comment(&db, comment_id, &user_id, &req).await {Ok(res) => {if let Some(Mentions { users, mention_id }) = req.mentions {- let notif = build_mention_notif(+ let request = build_mention_notif(NotifLocationType::EditComment,req.text.clone().unwrap_or_else(|| "".to_string()),Some(&res.comment),@@ -68,11 +72,15 @@ pub async fn edit_comment_handler(user_id.clone().try_into().ok(),res.document_id.to_string(),&mention_id,- );- _ = macro_notify_client- .send_notification(notif)+ )+ .into_request()+ .with_apns()+ .with_conn_gateway();++ _ = notification_ingress_service+ .send_notification(request).await- .inspect_err(|e| tracing::error!(error =? e, "coundn't send document mention notification"));+ .inspect_err(|e| tracing::error!(error =? e, "couldn't send document mention notification"));}update_live_comment_state(&conn_gateway_client,diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rsindex 4ba6794adc..3886f8eda6 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rs@@ -6,7 +6,7 @@ pub mod edit_anchor;pub mod edit_comment;pub mod get;-use std::fmt::Display;+use std::{collections::HashSet, fmt::Display};use super::context::ApiContext;use axum::{@@ -16,11 +16,17 @@ use axum::{routing::{delete, get, patch, post},};use macro_db_client::annotations::CommentError;+use macro_user_id::email::ReadEmailParts;use macro_user_id::user_id::MacroUserIdStr;use model::{annotations::Comment, response::ErrorResponse};+use model_entity::Entity;use model_entity::EntityType;-use model_notifications::{DocumentMentionMetadata, NotificationQueueMessage};-use serde::Serialize;+use notification::domain::models::{+ NotifCollapseKey, Notification, NotificationExtIos, RateLimitConfig, RateLimitKey,+ SendNotificationRequestBuilder,+ apple::{APNSPushNotification, AlertDictionary, Aps},+};+use serde::{Deserialize, Serialize};use tower::ServiceBuilder;use utoipa::ToSchema;@@ -123,7 +129,7 @@ pub fn comment_error_response(e: anyhow::Error, default_msg: &str) -> Result<Res}}-#[derive(ToSchema)]+#[derive(Debug, Clone, Deserialize, ToSchema)]pub enum NotifLocationType {CreateComment,EditComment,@@ -151,60 +157,112 @@ impl Display for NotifLocationType {}}-#[derive(Serialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]-struct Location {+pub(in crate::api) struct Location {r#type: NotifLocationType,comment_id: Option<i64>,thread_id: i64,text: String,}-// TODO: This is consumed in the frontend. It should be shared.-#[derive(Serialize)]+/// Notification sent when a user is mentioned in a document comment.+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]-struct Metadata {- mention_id: String,- location: Location,+pub struct DocumentMentionNotification {+ /// The name of the document.+ pub document_name: String,+ /// The owner of the document.+ pub owner: MacroUserIdStr<'static>,+ /// The file type of the document.+ pub file_type: Option<String>,+ /// The mention ID.+ pub mention_id: String,+ /// The location metadata for the mention.+ pub location: Location,+}++impl Notification for DocumentMentionNotification {+ const TYPE_NAME: &'static str = "document_mention";++ fn rate_limit_config() -> Option<RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<RateLimitKey> {+ None+ }+}++impl NotificationExtIos for DocumentMentionNotification {+ type NotifData = ();++ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {+ let entity_type: &'static str = entity.entity_type.into();+ NotifCollapseKey::new(entity_type).append(&entity.entity_id)+ }++ fn into_apns<'a>(+ self,+ sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let sender = sender_id?;+ let file_type = self.file_type.as_ref()?;+ let title = sender.0.email_part().email_str().to_string();+ let body = format!("You were mentioned in {}.{}", self.document_name, file_type);+ Some(APNSPushNotification {+ aps: Aps {+ alert: Some(notification::domain::models::apple::Alert::Dictionary(+ AlertDictionary {+ title: Some(title),+ body: Some(body),+ ..Default::default()+ },+ )),+ ..Default::default()+ },+ push_notification_data: (),+ })+ }}#[expect(clippy::too_many_arguments)]-fn build_mention_notif(+fn build_mention_notif<'a>(notif_location_type: NotifLocationType,text: String,comment: Option<&Comment>,thread_id: i64,- mentions: &[String],+ mentions: &'a [String],document_name: String,owner: MacroUserIdStr<'static>,file_type: Option<String>,sender_id: Option<MacroUserIdStr<'static>>,document_id: String,mention_id: &str,-) -> NotificationQueueMessage {- let metadata = DocumentMentionMetadata {+) -> SendNotificationRequestBuilder<'a, DocumentMentionNotification> {+ let notification = DocumentMentionNotification {document_name,owner,file_type,- metadata: Some(- serde_json::to_value(Metadata {- mention_id: mention_id.to_string(),- location: Location {- r#type: notif_location_type,- comment_id: comment.map(|c| c.comment_id),- thread_id,- text,- },- })- .expect("always works"),- ),+ mention_id: mention_id.to_string(),+ location: Location {+ r#type: notif_location_type,+ comment_id: comment.map(|c| c.comment_id),+ thread_id,+ text,+ },};- NotificationQueueMessage {+ let recipient_ids: HashSet<MacroUserIdStr<'a>> = mentions+ .iter()+ .filter_map(|id| MacroUserIdStr::parse_from_str(id).ok())+ .collect();++ SendNotificationRequestBuilder {notification_entity: EntityType::Document.with_entity_string(document_id),- notification_event: metadata.into(),+ notification,sender_id,- recipient_ids: Some(mentions.to_vec()),+ recipient_ids,}}@@ -224,7 +282,10 @@ mod tests {}#[test]fn check_ser_meta() -> Result<(), Box<dyn std::error::Error>> {- let m = Metadata {+ let m = DocumentMentionNotification {+ document_name: "test".to_string(),+ owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ file_type: None,mention_id: "xxx".to_string(),location: Location {r#type: NotifLocationType::EditComment,diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 753a0ef169..67234e6896 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -13,6 +13,8 @@ use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::Fuse macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;use macro_sha_count_client::Redis;+use notification::domain::service::NotificationIngressService;+use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};use opensearch_client::OpensearchClient;use properties::{NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,@@ -45,8 +47,13 @@ type DssSoupState = SoupRouterState<>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;-type PropertiesService =- PropertiesServiceImpl<PropertiesPgRepo, PermissionServiceImpl, NotificationServiceImpl>;+type NotificationIngressType =+ NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+type PropertiesService = PropertiesServiceImpl<+ PropertiesPgRepo,+ PermissionServiceImpl,+ NotificationServiceImpl<NotificationIngressType>,+>;/// Type alias for the ChannelServiceImpl used by commspub(crate) type CommsChannelService =@@ -64,7 +71,7 @@ pub(crate) struct ApiContext {pub dynamo_db: aws_sdk_dynamodb::Client,pub soup_router_state: DssSoupState,pub sqs_client: Arc<sqs_client::SQS>,- pub macro_notify_client: Arc<macro_notify::MacroNotify>,+ pub notification_ingress_service: Arc<NotificationIngressType>,pub conn_gateway_client: Arc<ConnectionGatewayClient>,pub sync_service_client: Arc<SyncServiceClient>,pub system_properties_service: Arc<SystemPropertiesService>,@@ -121,7 +128,7 @@ impl From<&ApiContext> for CommsHandlerState {jwt_validation_args: ctx.jwt_validation_args.clone(),db: ctx.db.clone(),connection_gateway_client: ctx.conn_gateway_client.clone(),- macro_notify_client: ctx.macro_notify_client.clone(),+ notification_ingress_service: ctx.notification_ingress_service.clone(),sqs_client: ctx.sqs_client.clone(),permissions_token_secret: ctx.permissions_token_secret.clone(),frecency_storage: ctx.frecency_storage.clone(),diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rsindex 1a38de4cec..09f31364b7 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs@@ -160,7 +160,6 @@ pub async fn create_document(// update project modified if necessarymacro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id,old_project_id: None,diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rsindex 7d4738948a..c1aab5bb81 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs@@ -80,7 +80,6 @@ pub async fn delete_document_handler(macro_project_utils::update_project_modified(&state.db,- &state.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: doc.project_id.clone(),old_project_id: None,diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rsindex 229ee83fc5..e7e235195a 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/edit_document/edit_document_v2.rs@@ -70,7 +70,6 @@ pub async fn edit_document(// update project modified if necessarymacro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: req.project_id,old_project_id: document_context.project_id,diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rs b/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rsindex 1e45f76987..10b639d111 100644--- a/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rs+++ b/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rs@@ -82,7 +82,6 @@ async fn create_project_v2(tracing::trace!("updating project modified date");macro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: None,old_project_id: Some(project_id.to_string()),diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/delete_project.rs b/rust/cloud-storage/document_storage_service/src/api/projects/delete_project.rsindex 30c2e41969..fb25cc71c5 100644--- a/rust/cloud-storage/document_storage_service/src/api/projects/delete_project.rs+++ b/rust/cloud-storage/document_storage_service/src/api/projects/delete_project.rs@@ -80,7 +80,6 @@ pub async fn delete_project_handler();macro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: None,old_project_id: Some(parent_id),diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rs b/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rsindex c02362527d..a5d388f9e2 100644--- a/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rs+++ b/rust/cloud-storage/document_storage_service/src/api/projects/edit_project.rs@@ -168,7 +168,6 @@ async fn edit_project_v2(// Update the project you are edittingmacro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: Some(id.clone()), // The project you editedold_project_id: None,@@ -180,7 +179,6 @@ async fn edit_project_v2(// Update the project you moved from and moved tomacro_project_utils::update_project_modified(&ctx.db,- &ctx.macro_notify_client,macro_project_utils::ProjectModifiedArgs {project_id: req.project_parent_id, // The new project you've placed your item inold_project_id: project_context.parent_id.clone(), // The old project you've moved your item fromdiff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 3ab5f19873..f6f134a8fd 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -20,6 +20,8 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_middleware::auth::internal_access::InternalApiSecretKey;use macro_sha_count_client::Redis;+use notification::domain::service::NotificationIngressService;+use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};use opensearch_client::OpensearchClient;use properties::{NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,@@ -131,13 +133,6 @@ async fn main() -> anyhow::Result<()> {.get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?).await?;- let macro_notify_client = macro_notify::MacroNotify::new(- config.vars.notification_queue.as_ref().to_string(),- "document_storage_service".to_string(),- )- .await;- tracing::trace!("initialized macro_notify client");-let dss_auth_key = DocumentStorageServiceAuthKey::new()?;let conn_gateway_client = ConnectionGatewayClient::new(@@ -205,8 +200,19 @@ async fn main() -> anyhow::Result<()> {EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());let system_properties_service =SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));+ let make_notification_ingress = || {+ let notification_repository = DbNotificationRepository::new(db.clone());+ let notification_queue = SqsNotificationQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.vars.notification_queue.as_ref().to_string(),+ );+ NotificationIngressService::new(notification_repository, notification_queue)+ };+ let notification_ingress_service = Arc::new(make_notification_ingress());+ tracing::trace!("initialized notification ingress service");+let permission_checker = PermissionServiceImpl::new(db.clone());- let notification_service = NotificationServiceImpl::new(Arc::new(macro_notify_client.clone()));+ let notification_service = NotificationServiceImpl::new(make_notification_ingress());let properties_service = PropertiesServiceImpl::new(PropertiesPgRepo::new(db.clone()),Some(permission_checker),@@ -255,7 +261,7 @@ async fn main() -> anyhow::Result<()> {dynamodb_client: Arc::new(dynamodb_client),dynamo_db,sqs_client: Arc::new(sqs_client),- macro_notify_client: Arc::new(macro_notify_client),+ notification_ingress_service,conn_gateway_client: Arc::new(conn_gateway_client),sync_service_client: Arc::new(sync_service_client),system_properties_service: Arc::new(system_properties_service),diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex f4f7a7e337..558933cc13 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -100,7 +100,7 @@ macro_env_var = { path = "../macro_env_var" }macro_middleware = { path = "../macro_middleware", default-features = false, features = ["auth",] }-macro_notify = { path = "../macro_notify" }+notification = { path = "../notification" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }mime_guess = "2.0.5"diff --git a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/database.rs b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/database.rsindex 254680276e..69348fc2de 100644--- a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/database.rs+++ b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/database.rs@@ -217,7 +217,7 @@ pub async fn fetch_unique_attachments(}let mut result: Vec<AttachmentUploadMetadata> = unique_attachments.into_values().collect();- result.sort_by(|a, b| b.internal_date_ts.cmp(&a.internal_date_ts));+ result.sort_by_key(|b| std::cmp::Reverse(b.internal_date_ts));println!("Total unique rows: {}", result.len());diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rsindex afb3a93e8a..c36ca64005 100644--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs@@ -4,6 +4,8 @@ use email_service::config::{Config, EmailServiceCloudfrontSignerPrivateKey};use macro_entrypoint::MacroEntrypoint;use macro_env::Environment;use macro_middleware::auth::internal_access::InternalApiSecretKey;+use notification::domain::service::NotificationIngressService;+use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};use secretsmanager_client::SecretManager;use sqlx::postgres::PgPoolOptions;use static_file_service_client::StaticFileServiceClient;@@ -82,11 +84,13 @@ async fn main() -> anyhow::Result<()> {.contacts_queue(&config.contacts_queue).email_link_manager_queue(&config.link_manager_queue);- let macro_notify_client = macro_notify::MacroNotify::new(- config.notification_queue.clone(),- "email_service".to_string(),- )- .await;+ let notification_ingress_service = Arc::new(NotificationIngressService::new(+ DbNotificationRepository::new(db.clone()),+ SqsNotificationQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ config.notification_queue.clone(),+ ),+ ));let link_manager_worker = sqs_worker::SQSWorker::new(aws_sdk_sqs::Client::new(&gmail_queue_aws_config),@@ -207,7 +211,7 @@ async fn main() -> anyhow::Result<()> {let gmail_client_inbox_sync = gmail_client.clone();let auth_service_client_inbox_sync = auth_service_client.clone();let redis_client_inbox_sync = redis_client.clone();- let macro_notify_client_inbox_sync = macro_notify_client.clone();+ let notification_ingress_service_inbox_sync = notification_ingress_service.clone();let sfs_client_inbox_sync = sfs_client.clone();let connection_gateway_client_inbox_sync = connection_gateway_client.clone();let dss_client_inbox_sync = dss_client.clone();@@ -220,7 +224,7 @@ async fn main() -> anyhow::Result<()> {gmail_client_inbox_sync,auth_service_client_inbox_sync,redis_client_inbox_sync,- macro_notify_client_inbox_sync,+ notification_ingress_service_inbox_sync,sfs_client_inbox_sync,connection_gateway_client_inbox_sync,dss_client_inbox_sync,@@ -243,7 +247,7 @@ async fn main() -> anyhow::Result<()> {let gmail_client_inbox_sync = gmail_client.clone();let auth_service_client_inbox_sync = auth_service_client.clone();let redis_client_inbox_sync = redis_client.clone();- let macro_notify_client_inbox_sync = macro_notify_client.clone();+ let notification_ingress_service_inbox_sync = notification_ingress_service.clone();let sfs_client_inbox_sync = sfs_client.clone();let connection_gateway_client_inbox_sync = connection_gateway_client.clone();let dss_client_inbox_sync = dss_client.clone();@@ -256,7 +260,7 @@ async fn main() -> anyhow::Result<()> {gmail_client_inbox_sync,auth_service_client_inbox_sync,redis_client_inbox_sync,- macro_notify_client_inbox_sync,+ notification_ingress_service_inbox_sync,sfs_client_inbox_sync,connection_gateway_client_inbox_sync,dss_client_inbox_sync,@@ -279,7 +283,7 @@ async fn main() -> anyhow::Result<()> {let gmail_client_backfill = gmail_client.clone();let auth_service_client_backfill = auth_service_client.clone();let redis_client_backfill = redis_client.clone();- let macro_notify_client_backfill = macro_notify_client.clone();+ let notification_ingress_service_backfill = notification_ingress_service.clone();let sfs_client_backfill = sfs_client.clone();let connection_gateway_client_backfill = connection_gateway_client.clone();let dss_client_backfill = dss_client.clone();@@ -292,7 +296,7 @@ async fn main() -> anyhow::Result<()> {gmail_client_backfill,auth_service_client_backfill,redis_client_backfill,- macro_notify_client_backfill,+ notification_ingress_service_backfill,sfs_client_backfill,connection_gateway_client_backfill,dss_client_backfill,diff --git a/rust/cloud-storage/email_service/src/convert/thread.rs b/rust/cloud-storage/email_service/src/convert/thread.rsindex abd115257d..5cd52f1db8 100644--- a/rust/cloud-storage/email_service/src/convert/thread.rs+++ b/rust/cloud-storage/email_service/src/convert/thread.rs@@ -55,7 +55,7 @@ pub async fn map_thread_resource_to_service(.collect::<Result<Vec<_>, _>>().context("Mapping one or more messages failed")?;- service_messages.sort_by(|a, b| a.internal_date_ts.cmp(&b.internal_date_ts));+ service_messages.sort_by_key(|a| a.internal_date_ts);// if any messages in the thread are in the inbox, the thread is visible in the inbox.let inbox_visible = service_messages.iter().any(|msg| {diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rsindex f1fec07252..6ea189ebd5 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/worker.rs@@ -1,11 +1,10 @@use crate::pubsub::backfill::process;-use crate::pubsub::context::PubSubContext;+use crate::pubsub::context::{NotificationIngressType, PubSubContext};use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;-use macro_notify::MacroNotifyClient;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};@@ -19,7 +18,7 @@ pub async fn run_worker(gmail_client: gmail_client::GmailClient,auth_service_client: AuthServiceClient,redis_client: RedisClient,- macro_notify_client: MacroNotifyClient,+ notification_ingress_service: Arc<NotificationIngressType>,sfs_client: StaticFileServiceClient,connection_gateway_client: ConnectionGatewayClient,dss_client: DocumentStorageServiceClient,@@ -33,7 +32,7 @@ pub async fn run_worker(gmail_client,auth_service_client,redis_client,- macro_notify_client,+ notification_ingress_service,sfs_client,connection_gateway_client,dss_client,diff --git a/rust/cloud-storage/email_service/src/pubsub/context.rs b/rust/cloud-storage/email_service/src/pubsub/context.rsindex f236598265..364d63feeb 100644--- a/rust/cloud-storage/email_service/src/pubsub/context.rs+++ b/rust/cloud-storage/email_service/src/pubsub/context.rs@@ -3,12 +3,17 @@ use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;use document_storage_service_client::DocumentStorageServiceClient;use gmail_client::GmailClient;-use macro_notify::MacroNotifyClient;+use notification::domain::service::NotificationIngressService;+use notification::outbound::{queue::SqsNotificationQueue, repository::DbNotificationRepository};use sqlx::PgPool;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};+/// The concrete notification ingress service type.+pub type NotificationIngressType =+ NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+#[derive(Clone)]pub struct PubSubContext {pub db: PgPool,@@ -17,7 +22,7 @@ pub struct PubSubContext {pub gmail_client: GmailClient,pub auth_service_client: AuthServiceClient,pub redis_client: RedisClient,- pub macro_notify_client: MacroNotifyClient,+ pub notification_ingress_service: Arc<NotificationIngressType>,pub sfs_client: StaticFileServiceClient,pub connection_gateway_client: ConnectionGatewayClient,pub dss_client: DocumentStorageServiceClient,diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rsindex 3c61d92b70..7eca63cc73 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs@@ -11,7 +11,7 @@ use email_utils::dedupe_emails;use macro_user_id::user_id::MacroUserIdStr;use model::contacts::ConnectionsMessage;use model_entity::EntityType;-use model_notifications::{NewEmailMetadata, NotificationQueueMessage};+use model_notifications::NewEmailMetadata;use models_email::db::address::EmailRecipientType;use models_email::email::service;use models_email::email::service::link;@@ -21,6 +21,8 @@ use models_email::gmail::operations::GmailApiOperation;use models_email::service::attachment::{AttachmentUploadArgs, AttachmentUploadDestination};use models_email::service::message::{Message, is_spam_or_trash};use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};+use notification::domain::models::SendNotificationRequestBuilder;+use notification::domain::service::NotificationIngress;use std::collections::HashSet;use std::result;use uuid::Uuid;@@ -505,7 +507,7 @@ async fn send_notifications(let sender_id =sender_contact.and_then(|contact| MacroUserIdStr::try_from_email(&contact.email).ok());- let notification_metadata = NewEmailMetadata {+ let notification = NewEmailMetadata {sender,to_email: link.email_address.0.as_ref().to_string(),thread_id: message.thread_db_id.to_string(),@@ -513,16 +515,26 @@ async fn send_notifications(snippet: message.snippet.unwrap_or_default(),};- let notification_queue_message = NotificationQueueMessage {+ let macro_id_str = link.macro_id.to_string();+ let recipient = MacroUserIdStr::parse_from_str(¯o_id_str).map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::InvalidData,+ source: anyhow::anyhow!("failed to parse macro user id: {}", e),+ })+ })?;++ let request = SendNotificationRequestBuilder {notification_entity: EntityType::Email.with_entity_string(message.db_id.to_string()),- notification_event: notification_metadata.into(),+ notification,sender_id,- recipient_ids: Some(vec![link.macro_id.to_string()]),- };+ recipient_ids: HashSet::from([recipient]),+ }+ .into_request()+ .with_conn_gateway();if let Err(e) = ctx- .macro_notify_client- .send_notification(notification_queue_message)+ .notification_ingress_service+ .send_notification(request).await{tracing::error!(error=?e, "unable to send notification");diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rsindex dd425e6dd7..69dc58ce1e 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/worker.rs@@ -1,11 +1,10 @@-use crate::pubsub::context::PubSubContext;+use crate::pubsub::context::{NotificationIngressType, PubSubContext};use crate::pubsub::inbox_sync::process;use crate::util::redis::RedisClient;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;use document_storage_service_client::DocumentStorageServiceClient;use futures::StreamExt;-use macro_notify::MacroNotifyClient;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};@@ -19,7 +18,7 @@ pub async fn run_worker(gmail_client: gmail_client::GmailClient,auth_service_client: AuthServiceClient,redis_client: RedisClient,- macro_notify_client: MacroNotifyClient,+ notification_ingress_service: Arc<NotificationIngressType>,sfs_client: StaticFileServiceClient,connection_gateway_client: ConnectionGatewayClient,dss_client: DocumentStorageServiceClient,@@ -34,7 +33,7 @@ pub async fn run_worker(gmail_client,auth_service_client,redis_client,- macro_notify_client,+ notification_ingress_service,sfs_client,connection_gateway_client,dss_client,diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.json b/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.jsonindex aa9502aa59..a1c4c0d402 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-0e124775055015b822196bac04d7421635befe41752d32bceaf5ab66e9215cc8.json@@ -37,9 +37,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.jsonnew file mode 100644index 0000000000..d2b084cf10--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.json b/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.jsonindex 4860ae3ec1..6c17e2c89d 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-18d2885f4c7a6ffd835a5d661ec5e81dd143cd4a51873e92050a0beedbbb86cb.json@@ -22,9 +22,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.json b/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.jsonindex 69cb81d4c7..602ce4228d 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-270c1f7ab00df1095282625b0766522d883948bc3589eb9a70fffa7787710bbf.json@@ -15,9 +15,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.json b/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.jsonindex daf0b4f790..51a42b64cb 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-530ba9c14f6f9e857023f66fa06cf632d4f2122183631ee8ae15902cd870cac3.json@@ -37,9 +37,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.jsonnew file mode 100644index 0000000000..6d97183829--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.jsonnew file mode 100644index 0000000000..9d717fa5f9--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "values",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.json b/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.jsonindex 78eac67010..4235a97747 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-b4edf0877afce79c1811f30b172520e11c357ef671da3ae1a651be27d01984a3.json@@ -37,9 +37,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.json b/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.jsonindex a427d7bdea..12ed677b43 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-d1d1519e0bdb30ddcbaa6d602bc04617613bb21df0e7728150e74b4125d28a59.json@@ -13,9 +13,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.jsonnew file mode 100644index 0000000000..182e0858ba--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.json b/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.jsonindex 6c9131a493..02598512d9 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-fab2fcdcfa7c81426ffddfb934b7c5eade3811d3ec8b5ab962c3dc9fd7886e9b.json@@ -37,9 +37,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.json b/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.jsonindex a3c1720287..055f08f556 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-fef80a0b809980ea8efbf49087aff2dd8c12edd081ad759855474fd9a4d1916d.json@@ -13,9 +13,9 @@"kind": {"Enum": ["view",+ "comment","edit",- "owner",- "comment"+ "owner"]}}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260202190211_notification_metadata_not_null.sql b/rust/cloud-storage/macro_db_client/migrations/20260202190211_notification_metadata_not_null.sqlnew file mode 100644index 0000000000..7a40d9dec1--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260202190211_notification_metadata_not_null.sql@@ -0,0 +1,5 @@+-- Make notification.metadata non-nullable.+-- Existing NULL rows get an empty JSON object as a default.+UPDATE notification SET metadata = '{}' WHERE metadata IS NULL;+ALTER TABLE notification ALTER COLUMN metadata SET DEFAULT '{}';+ALTER TABLE notification ALTER COLUMN metadata SET NOT NULL;diff --git a/rust/cloud-storage/macro_notify/Cargo.toml b/rust/cloud-storage/macro_notify/Cargo.tomldeleted file mode 100644index dbd329204b..0000000000--- a/rust/cloud-storage/macro_notify/Cargo.toml+++ /dev/null@@ -1,21 +0,0 @@-[package]-edition = "2024"-exclude = ["examples/"]-name = "macro_notify"-publish = false-version = "0.1.0"--[features]-local_queue = []--[dependencies]-anyhow = { workspace = true }-aws-sdk-sqs = { workspace = true }-macro_aws_config = { path = "../macro_aws_config" }-macro_uuid = { path = "../macro_uuid" }-model = { path = "../model" }-model_notifications = { path = "../model_notifications" }-serde = { workspace = true }-serde_json = { workspace = true }-tracing = { workspace = true }-uuid = { workspace = true }diff --git a/rust/cloud-storage/macro_notify/README.md b/rust/cloud-storage/macro_notify/README.mddeleted file mode 100644index 31be00e617..0000000000--- a/rust/cloud-storage/macro_notify/README.md+++ /dev/null@@ -1,56 +0,0 @@-# Macro Notify--This crate is a utility crate that is used to send notifications in macro.-If you need to send a notification in rust this should be the only way you do so.--## IaC Requirements--Each service will need to import the notification queue arn and name. You will also need to ensure the role for the service has a policy that allows sending messages to the queue.--```typescript-import * as pulumi from "@pulumi/pulumi";-// Get the stack from the shared package-import { getMacroNotify, stack } from '@macro-cloud-infra/shared';--const { notificationQueueName, notificationQueueArn } = getMacroNotify();--// Example policy and role (These would go inside of your specific services class file)-const queuePolicy = new aws.iam.Policy(- `${BASE_NAME}-sqs-policy`,- {- name: `${BASE_NAME}-sqs-policy-${stack}`,- policy: {- Version: '2012-10-17',- Statement: [- {- Action: ['sqs:SendMessage'],- Resource: [pulumi.interpolate`${notificationQueueArn}`],- Effect: 'Allow',- },- ],- },- },-);--// This is the role that would get attached to your service-const role = new aws.iam.Role(- `${BASE_NAME}-role`,- {- name: `${BASE_NAME}-role-${stack}`,- assumeRolePolicy: {- Version: '2012-10-17',- Statement: [- {- Action: 'sts:AssumeRole',- Principal: {- Service: 'ecs-tasks.amazonaws.com',- },- Effect: 'Allow',- Sid: '',- },- ],- },- tags: this.tags,- managedPolicyArns: [queuePolicy.arn],- },-);```diff --git a/rust/cloud-storage/macro_notify/src/enqueue.rs b/rust/cloud-storage/macro_notify/src/enqueue.rsdeleted file mode 100644index 230fdaadcb..0000000000--- a/rust/cloud-storage/macro_notify/src/enqueue.rs+++ /dev/null@@ -1,20 +0,0 @@-use std::collections::HashMap;--/// Enqueues a message to the queue.-#[tracing::instrument(skip(sqs_client))]-pub(crate) async fn enqueue(- sqs_client: &aws_sdk_sqs::Client,- queue_url: &str,- message_attributes: Option<HashMap<String, aws_sdk_sqs::types::MessageAttributeValue>>,- message_body: &str,-) -> anyhow::Result<()> {- sqs_client- .send_message()- .queue_url(queue_url)- .set_message_attributes(message_attributes)- .message_body(message_body)- .send()- .await?;-- Ok(())-}diff --git a/rust/cloud-storage/macro_notify/src/lib.rs b/rust/cloud-storage/macro_notify/src/lib.rsdeleted file mode 100644index 45db77e601..0000000000--- a/rust/cloud-storage/macro_notify/src/lib.rs+++ /dev/null@@ -1,94 +0,0 @@-mod enqueue;-mod message_attribute;--use std::collections::HashMap;-use std::fmt::Debug;--use message_attribute::build_string_message_attribute;-use model_notifications::{NotificationEventType, NotificationQueueMessage};--/// Maximum number of messages that can be sent out in a single batch.-pub const MAX_BATCH_SIZE: usize = 10;--use uuid::Uuid;--pub use MacroNotifyClient as MacroNotify;--#[derive(Clone, Debug)]-pub struct MacroNotifyClient {- /// The SQS client to use for sending notifications- inner: aws_sdk_sqs::Client,- /// The notification queue to send notification messages to- notification_queue: String,- /// The service that initialized the client- service: String,-}--impl MacroNotifyClient {- pub async fn new(notification_queue: String, service: String) -> Self {- let config = macro_aws_config::get_macro_aws_config().await;-- Self {- inner: aws_sdk_sqs::Client::new(&config),- notification_queue,- service,- }- }-- pub async fn send_notification(- &self,- message: NotificationQueueMessage,- ) -> anyhow::Result<Uuid> {- // Generate a the notification id- let notification_id = macro_uuid::generate_uuid_v7();-- let NotificationMessageAttributes(message_attributes) =- NotificationMessageAttributes::from_message(- ¬ification_id.to_string(),- &message,- self.service.as_str(),- );-- let body = serde_json::to_string(&message)?;- enqueue::enqueue(- &self.inner,- &self.notification_queue,- Some(message_attributes),- &body,- )- .await?;-- Ok(notification_id)- }-}--struct NotificationMessageAttributes(- pub HashMap<String, aws_sdk_sqs::types::MessageAttributeValue>,-);--impl NotificationMessageAttributes {- fn from_message(- notification_id: &str,- message: &NotificationQueueMessage,- service: &str,- ) -> Self {- const ATTRIBUTES: &[&str] = &[- "notification_id",- "notification_event_type",- "service_sender",- ];-- let event_type: NotificationEventType = (&message.notification_event).into();- let event_type_str = event_type.to_string();-- let values = [notification_id, &event_type_str, service];-- let attributes = ATTRIBUTES- .iter()- .zip(values.iter())- .map(|(key, value)| (key.to_string(), build_string_message_attribute(value)))- .collect::<HashMap<_, _>>();-- Self(attributes)- }-}diff --git a/rust/cloud-storage/macro_notify/src/message_attribute.rs b/rust/cloud-storage/macro_notify/src/message_attribute.rsdeleted file mode 100644index c76061ddcb..0000000000--- a/rust/cloud-storage/macro_notify/src/message_attribute.rs+++ /dev/null@@ -1,13 +0,0 @@-/// Builds a string message attribute-// TODO this would only fail from programmer error: when "data_type" not set.-// it should not return a result.-#[tracing::instrument]-pub(crate) fn build_string_message_attribute(- attr: &str,-) -> aws_sdk_sqs::types::MessageAttributeValue {- aws_sdk_sqs::types::MessageAttributeValue::builder()- .data_type("String")- .string_value(attr)- .build()- .expect("only fails when `data_type` is not set. it is set above")-}diff --git a/rust/cloud-storage/macro_project_utils/Cargo.toml b/rust/cloud-storage/macro_project_utils/Cargo.tomlindex 2494fed29c..be0c1709d6 100644--- a/rust/cloud-storage/macro_project_utils/Cargo.toml+++ b/rust/cloud-storage/macro_project_utils/Cargo.toml@@ -7,7 +7,6 @@ version = "0.1.0"[dependencies]anyhow = { workspace = true }macro_db_client = { path = "../macro_db_client" }-macro_notify = { path = "../macro_notify" }model = { path = "../model" }sqlx = { workspace = true }tokio = { workspace = true }diff --git a/rust/cloud-storage/macro_project_utils/src/lib.rs b/rust/cloud-storage/macro_project_utils/src/lib.rsindex 407b7c57d1..cc706b32ee 100644--- a/rust/cloud-storage/macro_project_utils/src/lib.rs+++ b/rust/cloud-storage/macro_project_utils/src/lib.rs@@ -11,10 +11,9 @@ wherepub user_id: String,}-#[tracing::instrument(skip(db, macro_notify_client))]-pub async fn update_project_modified<'a, T>(- db: &'a sqlx::Pool<sqlx::Postgres>,- macro_notify_client: &'a macro_notify::MacroNotifyClient,+#[tracing::instrument(skip(db))]+pub async fn update_project_modified<T>(+ db: &sqlx::Pool<sqlx::Postgres>,project_modified_args: ProjectModifiedArgs<T>,) whereT: Clone + std::fmt::Debug + ToString + std::marker::Send + Sync,@@ -30,14 +29,8 @@ pub async fn update_project_modified<'a, T>(.as_ref().map(|s| s.to_string());- let user_id = project_modified_args.user_id.clone();-tokio::spawn({let db = db.clone();- let _macro_notify_client = macro_notify_client.clone();- let project_id = project_id.clone();- let old_project_id = old_project_id.clone();- let _user_id = user_id.clone();async move {if let Some(old_project_id) = old_project_id&& !old_project_id.is_empty()@@ -46,24 +39,6 @@ pub async fn update_project_modified<'a, T>(let _ = macro_db_client::projects::update_project_modified_date(&db, &old_project_id).await.inspect_err(|e| {tracing::error!(error=?e, project_id=?old_project_id, "unable to update project modified date");});-- // TODO: [BAC-44] Should use connection gateway- // let _ = macro_notify_client- // .send_notification(- // NotificationEventType::ProjectModified,- // &MessageBodyWithParticipantInfo {- // event_item_id: old_project_id.clone(),- // event_item_type: "project".to_string(),- // sender_id: Some(user_id.clone()),- // recipient_ids: None,- // metadata: None,- // is_important_v0: Some(false),- // },- // )- // .await- // .inspect_err(|e| {- // tracing::error!(error=?e, "unable to send project update message");- // });}if let Some(project_id) = project_id@@ -74,24 +49,6 @@ pub async fn update_project_modified<'a, T>(let _ = macro_db_client::projects::update_project_modified_date(&db, &project_id).await.inspect_err(|e| {tracing::error!(error=?e, project_id=?project_id, "unable to update project modified date");});-- // TODO: [BAC-44] Should use connection gateway- // let _ = macro_notify_client- // .send_notification(- // NotificationEventType::ProjectModified,- // &MessageBodyWithParticipantInfo {- // event_item_id: project_id.clone(),- // event_item_type: "project".to_string(),- // sender_id: Some(user_id.clone()),- // recipient_ids: None,- // metadata: None,- // is_important_v0: Some(false),- // },- // )- // .await- // .inspect_err(|e| {- // tracing::error!(error=?e, "unable to send project update message");- // });}}});diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.tomlindex 9181483911..62ffb79f76 100644--- a/rust/cloud-storage/model_notifications/Cargo.toml+++ b/rust/cloud-storage/model_notifications/Cargo.toml@@ -9,7 +9,9 @@ anyhow = { workspace = true }chrono = { workspace = true }doppleganger = { workspace = true }macro_user_id = { path = "../macro_user_id" }+mention_utils = { path = "../mention_utils" }model-entity = { path = "../model-entity" }+notification = { path = "../notification" }models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination" }serde = { workspace = true }diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex ae99174092..987f691589 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -1,7 +1,15 @@use crate::NotificationEventType;use doppleganger::Doppleganger;-use macro_user_id::user_id::MacroUserIdStr;+use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};+use mention_utils::parse::{ParsedXmlText, XmlFormatter};+use model_entity::Entity;use model_entity::EntityType;+use notification::domain::models::RateLimitConfig;+use notification::domain::models::RateLimitKey;+use notification::domain::models::{+ NotifCollapseKey, NotificationExtIos,+ apple::{APNSPushNotification, AlertDictionary, Aps},+};use serde::{Deserialize, Serialize, de::DeserializeOwned};use utoipa::ToSchema;@@ -216,6 +224,90 @@ pub struct NewEmailMetadata {pub snippet: String,}+impl notification::domain::models::Notification for NewEmailMetadata {+ const TYPE_NAME: &'static str = "new_email";++ fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {+ None+ }+}++impl notification::domain::models::Notification for ChannelInviteMetadata {+ const TYPE_NAME: &'static str = "channel_invite";++ fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {+ None+ }+}++impl notification::domain::models::Notification for ChannelMessageSendMetadata {+ const TYPE_NAME: &'static str = "channel_message_send";++ fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {+ None+ }+}++impl notification::domain::models::Notification for ChannelMentionMetadata {+ const TYPE_NAME: &'static str = "channel_mention";++ fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {+ None+ }+}++impl notification::domain::models::Notification for ChannelReplyMetadata {+ const TYPE_NAME: &'static str = "channel_message_reply";++ fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {+ None+ }+}++impl notification::domain::models::Notification for DocumentMentionMetadata {+ const TYPE_NAME: &'static str = "document_mention";++ fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {+ None+ }+}++impl notification::domain::models::Notification for InviteToTeamMetadata {+ const TYPE_NAME: &'static str = "invite_to_team";++ fn rate_limit_config() -> Option<notification::domain::models::RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<notification::domain::models::RateLimitKey> {+ None+ }+}+/// Metadata for when a user is assigned to a task#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]@@ -279,3 +371,231 @@ impl_notification_metadata!();impl_notification_metadata!(NewEmailMetadata, NotificationEventType::NewEmail);impl_notification_metadata!(TaskAssignedMetadata, NotificationEventType::TaskAssigned);++// Plain text formatter for converting XML message content to plain text for APNS payloads.+struct PlainTextFormatter;++impl XmlFormatter for PlainTextFormatter {+ fn format_plain_text(s: &str, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", s)+ }++ fn format_link(+ link: &mention_utils::parse::ParsedLink<'_>,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "{}", link.text)+ }++ fn format_doc(+ doc: &mention_utils::parse::ParsedDocumentMention<'_>,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "{}", doc.document_name)+ }++ fn format_user(+ user: &mention_utils::parse::ParsedUserMention<'_>,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "{}", user.user_id.0.email_part().email_str())+ }++ fn format_contact(+ contact: &mention_utils::parse::ParsedContactMention<'_>,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "{}", contact.name)+ }++ fn format_date(+ date: &mention_utils::parse::ParsedDateMention<'_>,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "{}", date.display_format)+ }++ fn format_group(+ group: &mention_utils::parse::ParsedGroupMention<'_>,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ write!(f, "@{}", group.group_alias)+ }+}++/// Helper to parse XML message content to plain text, returning None on failure.+fn parse_message_plain_text(content: &str) -> Option<String> {+ let parsed = ParsedXmlText::parse(content).ok()?;+ Some(PlainTextFormatter::format_xml_text(parsed).0)+}++/// Helper to create an alert-style APNS notification with title and body.+fn alert_apns(title: String, body: String) -> APNSPushNotification<()> {+ APNSPushNotification {+ aps: Aps {+ alert: Some(notification::domain::models::apple::Alert::Dictionary(+ AlertDictionary {+ title: Some(title),+ body: Some(body),+ ..Default::default()+ },+ )),+ ..Default::default()+ },+ push_notification_data: (),+ }+}++impl NotificationExtIos for ChannelInviteMetadata {+ type NotifData = ();++ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {+ let entity_type: &'static str = entity.entity_type.into();+ NotifCollapseKey::new(entity_type).append(&entity.entity_id)+ }++ fn into_apns<'a>(+ self,+ _sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ Some(alert_apns(+ format!("{} Invite", self.common.channel_name),+ format!("{} invited you to join the channel", self.invited_by),+ ))+ }+}++impl NotificationExtIos for ChannelMessageSendMetadata {+ type NotifData = ();++ fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {+ NotifCollapseKey::new(&self.message_id)+ }++ fn into_apns<'a>(+ self,+ _sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let title = match self.common.channel_type {+ ChannelType::DirectMessage => self.sender.email_part().local_part().to_string(),+ _ => format!(+ "{} <{}>",+ self.sender.email_part().local_part(),+ self.common.channel_name+ ),+ };+ let body = parse_message_plain_text(&self.message_content)?;+ Some(alert_apns(title, body))+ }+}++impl NotificationExtIos for ChannelMentionMetadata {+ type NotifData = ();++ fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {+ NotifCollapseKey::new(&self.message_id)+ }++ fn into_apns<'a>(+ self,+ sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let sender = sender_id?;+ let title = match self.common.channel_type {+ ChannelType::DirectMessage => {+ format!("{} mentioned you", sender.email_part().local_part())+ }+ _ => format!(+ "{} mentioned you in #{}",+ sender.email_part().local_part(),+ self.common.channel_name+ ),+ };+ let body = parse_message_plain_text(&self.message_content)?;+ Some(alert_apns(title, body))+ }+}++impl NotificationExtIos for ChannelReplyMetadata {+ type NotifData = ();++ fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {+ NotifCollapseKey::new(&self.message_id)+ }++ fn into_apns<'a>(+ self,+ sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let sender = sender_id?;+ let title = format!("{} Replied", sender.0.email_part().email_str());+ let body = parse_message_plain_text(&self.message_content)?;+ Some(alert_apns(title, body))+ }+}++impl NotificationExtIos for DocumentMentionMetadata {+ type NotifData = ();++ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {+ let entity_type: &'static str = entity.entity_type.into();+ NotifCollapseKey::new(entity_type).append(&entity.entity_id)+ }++ fn into_apns<'a>(+ self,+ sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let sender = sender_id?;+ let file_type = self.file_type.as_ref()?;+ let title = sender.0.email_part().email_str().to_string();+ let body = format!("You were mentioned in {}.{}", self.document_name, file_type);+ Some(alert_apns(title, body))+ }+}++impl notification::domain::models::Notification for TaskAssignedMetadata {+ const TYPE_NAME: &'static str = "task_assigned";++ fn rate_limit_config() -> Option<RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<RateLimitKey> {+ None+ }+}++impl NotificationExtIos for TaskAssignedMetadata {+ type NotifData = ();++ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {+ let entity_type: &'static str = entity.entity_type.into();+ NotifCollapseKey::new(entity_type).append(&entity.entity_id)+ }++ fn into_apns<'a>(+ self,+ _sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let title = self.assigned_by.email_part().email_str().to_string();+ let body = if let Some(ref task_name) = self.task_name {+ format!("assigned you to {}", task_name)+ } else {+ "assigned you a task".to_string()+ };+ Some(APNSPushNotification {+ aps: Aps {+ alert: Some(notification::domain::models::apple::Alert::Dictionary(+ AlertDictionary {+ title: Some(title),+ body: Some(body),+ ..Default::default()+ },+ )),+ ..Default::default()+ },+ push_notification_data: (),+ })+ }+}diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rsindex 924ce18f1f..10cb20bfee 100644--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs@@ -36,6 +36,7 @@ pub enum FailureReason {OutdatedHistoryId,AttachmentParsingFailed,DSSUploadFailed,+ InvalidData,}/// The message we send from the email_refresh_handler lambda to the service via SQS to refreshdiff --git a/rust/cloud-storage/notification/.sqlx/query-01dd9435cfbfb5050e24e65f854fbe902364f0c8886a49feacd938f7ccf5291c.json b/rust/cloud-storage/notification/.sqlx/query-01dd9435cfbfb5050e24e65f854fbe902364f0c8886a49feacd938f7ccf5291c.jsonnew file mode 100644index 0000000000..12ca64bf33--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-01dd9435cfbfb5050e24e65f854fbe902364f0c8886a49feacd938f7ccf5291c.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM notification WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "01dd9435cfbfb5050e24e65f854fbe902364f0c8886a49feacd938f7ccf5291c"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json b/rust/cloud-storage/notification/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.jsonnew file mode 100644index 0000000000..e4a18ac5f0--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET done = $3\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-3b56482fd4025765cb40a4eec09614b1de6f8fec1cfd2a52d4bd1203790a45a0.json b/rust/cloud-storage/notification/.sqlx/query-3b56482fd4025765cb40a4eec09614b1de6f8fec1cfd2a52d4bd1203790a45a0.jsonnew file mode 100644index 0000000000..2ff05438c8--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-3b56482fd4025765cb40a4eec09614b1de6f8fec1cfd2a52d4bd1203790a45a0.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT sent FROM user_notification WHERE notification_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sent",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "3b56482fd4025765cb40a4eec09614b1de6f8fec1cfd2a52d4bd1203790a45a0"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-5ed9ce53ae62e9f7b951d91e63b01a67c76157d88abb22bbfb1f39d92ac5dcc1.json b/rust/cloud-storage/notification/.sqlx/query-5ed9ce53ae62e9f7b951d91e63b01a67c76157d88abb22bbfb1f39d92ac5dcc1.jsonnew file mode 100644index 0000000000..a924d6020c--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-5ed9ce53ae62e9f7b951d91e63b01a67c76157d88abb22bbfb1f39d92ac5dcc1.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT seen_at FROM user_notification WHERE notification_id = $1 AND user_id = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "seen_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "5ed9ce53ae62e9f7b951d91e63b01a67c76157d88abb22bbfb1f39d92ac5dcc1"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.json b/rust/cloud-storage/notification/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.jsonnew file mode 100644index 0000000000..34382e8725--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, apns_collapse_key as \"apns_collapse_key!: String\"\n FROM notification\n WHERE id = ANY($1) AND apns_collapse_key IS NOT NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "apns_collapse_key!: String",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1.json b/rust/cloud-storage/notification/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.jsonsimilarity index 61%rename from rust/cloud-storage/notification/.sqlx/query-55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1.jsonrename to rust/cloud-storage/notification/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.jsonindex 7ad415f82a..a166680895 100644--- a/rust/cloud-storage/notification/.sqlx/query-55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1.json+++ b/rust/cloud-storage/notification/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (id) DO NOTHING\n ",+ "query": "\n INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id, apns_collapse_key)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (id) DO NOTHING\n ","describe": {"columns": [],"parameters": {@@ -11,10 +11,11 @@"Text","Text","Jsonb",+ "Text","Text"]},"nullable": []},- "hash": "55d88928c73de7aa07a858d79c4e1b0ab25746c723e48a2aa5baba0fc13b21a1"+ "hash": "7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc"}diff --git a/rust/cloud-storage/notification/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.json b/rust/cloud-storage/notification/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.jsonnew file mode 100644index 0000000000..215280eac8--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.json@@ -0,0 +1,97 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($3::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($3, $4))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "notification_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "event_item_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "event_item_type",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "sent",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "done",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "viewed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "notification_metadata: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 11,+ "name": "notification_event_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 12,+ "name": "sender_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Int8",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ null,+ null,+ null,+ null,+ false,+ false,+ true+ ]+ },+ "hash": "7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1.json b/rust/cloud-storage/notification/.sqlx/query-94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1.jsonnew file mode 100644index 0000000000..4035617965--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET deleted_at = NOW()\n WHERE user_id = $1 AND notification_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json b/rust/cloud-storage/notification/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.jsonnew file mode 100644index 0000000000..7626c0a06b--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET seen_at = NOW()\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2.json b/rust/cloud-storage/notification/.sqlx/query-b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2.jsonnew file mode 100644index 0000000000..0b09fbeec2--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2.json@@ -0,0 +1,98 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND n.event_item_id = ANY($2)\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($4::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($4, $5))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $3\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "notification_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "event_item_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "event_item_type",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "sent",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "done",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "viewed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "notification_metadata: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 11,+ "name": "notification_event_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 12,+ "name": "sender_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "Int8",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ null,+ null,+ null,+ null,+ false,+ false,+ true+ ]+ },+ "hash": "b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-d7db871243688236109f3c665819a0772f2f010406e4f1e17433c310b53c57da.json b/rust/cloud-storage/notification/.sqlx/query-d7db871243688236109f3c665819a0772f2f010406e4f1e17433c310b53c57da.jsonnew file mode 100644index 0000000000..ba20677fc4--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-d7db871243688236109f3c665819a0772f2f010406e4f1e17433c310b53c57da.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO user_notification (user_id, notification_id, created_at) VALUES ($1, $2, '2025-01-01 00:00:00')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "d7db871243688236109f3c665819a0772f2f010406e4f1e17433c310b53c57da"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad.json b/rust/cloud-storage/notification/.sqlx/query-e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad.jsonnew file mode 100644index 0000000000..b36882b3ae--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad.json@@ -0,0 +1,95 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.notification_id = $2\n AND un.deleted_at IS NULL\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "notification_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "event_item_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "event_item_type",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "sent",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "done",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "viewed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "notification_metadata: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 11,+ "name": "notification_event_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 12,+ "name": "sender_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ null,+ null,+ null,+ null,+ false,+ false,+ true+ ]+ },+ "hash": "e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-e267af62eaa9b86a89b8c830122d47ab0252ac02a67ec0e7fa72c1ddc3791f04.json b/rust/cloud-storage/notification/.sqlx/query-e267af62eaa9b86a89b8c830122d47ab0252ac02a67ec0e7fa72c1ddc3791f04.jsonnew file mode 100644index 0000000000..9a417527bc--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-e267af62eaa9b86a89b8c830122d47ab0252ac02a67ec0e7fa72c1ddc3791f04.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT user_id FROM user_notification WHERE notification_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e267af62eaa9b86a89b8c830122d47ab0252ac02a67ec0e7fa72c1ddc3791f04"+}diff --git a/rust/cloud-storage/notification/.sqlx/query-f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b.json b/rust/cloud-storage/notification/.sqlx/query-f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b.jsonnew file mode 100644index 0000000000..39180b3b0f--- /dev/null+++ b/rust/cloud-storage/notification/.sqlx/query-f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET deleted_at = NOW()\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b"+}diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex a58d96fc78..569bd68028 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -4,23 +4,35 @@ name = "notification"publish = falseversion = "0.1.0"++[features]+axum = ["dep:axum", "dep:model-error-response", "dep:model_user", "models_pagination/axum", "schema"]+schema = ["dep:utoipa"]+[dependencies]aws-sdk-sesv2 = { workspace = true }aws-sdk-sns = { workspace = true }aws-sdk-sqs = { workspace = true }+axum = { workspace = true, optional = true }+chrono = { workspace = true }hex = { workspace = true }itertools = { workspace = true }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }+model-error-response = { path = "../model-error-response", optional = true }+model_user = { path = "../model_user", optional = true, features = ["axum"] }+models_pagination = { path = "../models_pagination" }redis = { workspace = true, features = ["tokio-native-tls-comp"] }reqwest = { workspace = true }rootcause = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }+sha2 = { workspace = true }sqlx = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true, features = ["time"] }tracing = { workspace = true }+utoipa = { workspace = true, optional = true }uuid = { workspace = true }[dev-dependencies]diff --git a/rust/cloud-storage/notification/fixtures/notifications_with_collapse_keys.sql b/rust/cloud-storage/notification/fixtures/notifications_with_collapse_keys.sqlnew file mode 100644index 0000000000..c117bfe80d--- /dev/null+++ b/rust/cloud-storage/notification/fixtures/notifications_with_collapse_keys.sql@@ -0,0 +1,14 @@+-- Notification with a collapse key+INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id, apns_collapse_key)+VALUES ('0193b1ea-a542-7589-893b-2b4a509c1e76', 'test', 'item-1', 'document', 'test_service', '{}', NULL, 'collapse-key-1');++-- Notification without a collapse key+INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id, apns_collapse_key)+VALUES ('0193b1ea-b642-7589-893b-2b4a509c1e76', 'test', 'item-2', 'document', 'test_service', '{}', NULL, NULL);++-- User notification records+INSERT INTO user_notification (user_id, notification_id, created_at)+VALUES ('macro|[email protected]', '0193b1ea-a542-7589-893b-2b4a509c1e76', '2025-01-01 00:00:00');++INSERT INTO user_notification (user_id, notification_id, created_at)+VALUES ('macro|[email protected]', '0193b1ea-b642-7589-893b-2b4a509c1e76', '2025-01-01 00:00:01');diff --git a/rust/cloud-storage/notification/fixtures/user_notifications.sql b/rust/cloud-storage/notification/fixtures/user_notifications.sqlindex 51a2435073..65728f59e5 100644--- a/rust/cloud-storage/notification/fixtures/user_notifications.sql+++ b/rust/cloud-storage/notification/fixtures/user_notifications.sql@@ -1,5 +1,5 @@INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)-VALUES ('0193b1ea-a542-7589-893b-2b4a509c1e76', 'test', 'item-1', 'document', 'test_service', NULL, NULL);+VALUES ('0193b1ea-a542-7589-893b-2b4a509c1e76', 'test', 'item-1', 'document', 'test_service', '{"message": "hello"}', NULL);INSERT INTO user_notification (user_id, notification_id, created_at)VALUES ('macro|[email protected]', '0193b1ea-a542-7589-893b-2b4a509c1e76', '2025-01-01 00:00:00');diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rsindex 7c419b2ea1..1373dd45a1 100644--- a/rust/cloud-storage/notification/src/domain/models.rs+++ b/rust/cloud-storage/notification/src/domain/models.rs@@ -1,38 +1,235 @@//! Domain models for the notification service.-use crate::domain::models::apple::APNSPushNotification;+use macro_user_id::user_id::MacroUserIdStr;use serde::{Serialize, de::DeserializeOwned};pub(crate) mod android;-pub(crate) mod apple;-pub(crate) mod mobile;+pub mod apple;+pub mod mobile;pub(crate) mod queue_message;pub mod rate_limit;pub mod recipient;pub mod request;-pub use mobile::DeviceEndpoint;+pub use mobile::{DeviceEndpoint, HashedCollapseKey, NotifCollapseKey};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};++/// Notification ID paired with its APNS collapse key, for push clearing.+#[derive(Debug, Clone)]+pub struct NotificationIdAndCollapseKey {+ /// The notification ID.+ pub id: uuid::Uuid,+ /// The APNS collapse key used to identify the push notification to clear.+ pub apns_collapse_key: String,+}++/// A row from the `user_notification` + `notification` join query.+///+/// The metadata field is generic so callers can deserialize it into+/// whatever type they need without this crate depending on the caller's models.+#[derive(Debug, Clone, Serialize)]+pub struct UserNotificationRow<T> {+ /// The user who owns this notification.+ pub owner_id: MacroUserIdStr<'static>,+ /// The notification ID.+ pub notification_id: uuid::Uuid,+ /// The notification event type string (e.g. "channel_mention").+ /// TODO make this a new type+ pub notification_event_type: String,+ /// The entity the notification is about.+ pub entity: Entity<'static>,+ /// Whether the notification has been sent.+ pub sent: bool,+ /// Whether the notification is marked as done.+ pub done: bool,+ /// When the notification was created.+ pub created_at: Option<DateTime<Utc>>,+ /// When the notification was viewed/seen.+ pub viewed_at: Option<DateTime<Utc>>,+ /// When the notification was last updated.+ pub updated_at: Option<DateTime<Utc>>,+ /// When the notification was deleted.+ pub deleted_at: Option<DateTime<Utc>>,+ /// Deserialized notification metadata.+ pub notification_metadata: T,+ /// The user who triggered the notification.+ pub sender_id: Option<MacroUserIdStr<'static>>,+}++/// A notification metadata value tagged with the notification event type.+#[derive(Debug, Serialize)]+pub struct TaggedContent<T> {+ tag: String,+ content: T,+}++impl<T> UserNotificationRow<T> {+ /// Wrap the metadata in a [`TaggedContent`] using the notification event type as the tag.+ pub fn into_tagged(self) -> UserNotificationRow<TaggedContent<T>> {+ let UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ sender_id,+ } = self;++ UserNotificationRow {+ owner_id,+ notification_id,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata: TaggedContent {+ tag: notification_event_type.clone(),+ content: notification_metadata,+ },+ notification_event_type,+ sender_id,+ }+ }+}++impl<T: Serialize> UserNotificationRow<T> {+ /// Serialize the metadata into a [`serde_json::Value`].+ pub fn into_json(self) -> Result<UserNotificationRow<serde_json::Value>, serde_json::Error> {+ let UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ sender_id,+ } = self;++ let val = serde_json::to_value(notification_metadata)?;++ Ok(UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata: val,+ sender_id,+ })+ }+}++impl UserNotificationRow<serde_json::Value> {+ /// Deserialize the JSON metadata into a concrete type `T`.+ pub fn deserialize_json<T: DeserializeOwned>(+ self,+ ) -> Result<UserNotificationRow<T>, serde_json::Error> {+ let UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ sender_id,+ } = self;++ let val = serde_json::from_value(notification_metadata)?;++ Ok(UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata: val,+ sender_id,+ })+ }+}++impl<T> Identify for UserNotificationRow<T> {+ type Id = uuid::Uuid;+ fn id(&self) -> Self::Id {+ self.notification_id+ }+}++impl<T> SortOn<CreatedAt> for UserNotificationRow<T> {+ fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> CursorVal<CreatedAt> {+ move |v| {+ let last_val = v.created_at.unwrap_or(DateTime::UNIX_EPOCH);+ CursorVal {+ sort_type: sort,+ last_val,+ }+ }+ }+}+/// Trait that all notification types must implement.pub trait Notification: Serialize + DeserializeOwned + Send + Sync {/// The type name of this notification.const TYPE_NAME: &'static str;- /// The user visible title of the notification.- fn title(&self) -> String;- /// The user visible body of the notification.- fn body(&self) -> String;/// The configuration for how often the notification can be triggered on a certain key.fn rate_limit_config() -> Option<RateLimitConfig>;/// The actual key for the rate limit bucket.fn rate_limit_key(&self) -> Option<RateLimitKey>;}-/// Trait for notifications that can build APNS push payloads.-pub trait BuildApnsNotification<T>: Notification {- /// Build an APNS push notification from this notification.- fn build_apns(&self) -> APNSPushNotification<T>;+/// Extension trait for notifications that can be delivered via email.+pub trait NotificationExtEmail: Notification {+ /// Convert this notification into email content.+ fn into_email(self) -> EmailContent;+}++/// Extension trait for notifications that can be delivered via iOS push (APNS).+pub trait NotificationExtIos: Notification {+ /// The custom data type included in the APNS push notification payload.+ type NotifData: Send;+ /// Build the collapse key for this push notification.+ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey;+ /// Convert this notification into an APNS push notification.+ fn into_apns<'a>(+ self,+ sender_id: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>>;}diff --git a/rust/cloud-storage/notification/src/domain/models/apple.rs b/rust/cloud-storage/notification/src/domain/models/apple.rsindex 6a170be6af..b90de95824 100644--- a/rust/cloud-storage/notification/src/domain/models/apple.rs+++ b/rust/cloud-storage/notification/src/domain/models/apple.rs@@ -1,129 +1,139 @@-use serde::{Deserialize, Serialize};+//! Apple Push Notification Service (APNS) payload models.-use crate::domain::models::Notification;+use serde::{Deserialize, Serialize};+/// The APNS payload container.#[derive(Serialize, Debug, Default, Deserialize)]#[serde(rename_all = "kebab-case")]pub struct Aps {+ /// The alert content.#[serde(skip_serializing_if = "Option::is_none")]pub alert: Option<Alert>,+ /// The badge number to display on the app icon.#[serde(skip_serializing_if = "Option::is_none")]pub badge: Option<u32>,+ /// The notification sound.#[serde(skip_serializing_if = "Option::is_none")]pub sound: Option<Sound>,- /// Set to 1 for background/silent notifications+ /// Set to 1 for background/silent notifications.#[serde(skip_serializing_if = "Option::is_none")]pub content_available: Option<u8>,- /// Set to 1 to allow Notification Service Extension to modify+ /// Set to 1 to allow Notification Service Extension to modify.#[serde(skip_serializing_if = "Option::is_none")]pub mutable_content: Option<u8>,- /// Category identifier for actionable notifications+ /// Category identifier for actionable notifications.#[serde(skip_serializing_if = "Option::is_none")]pub category: Option<String>,- /// Identifier for grouping notifications+ /// Identifier for grouping notifications.#[serde(skip_serializing_if = "Option::is_none")]pub thread_id: Option<String>,- /// Relevance score for notification summary (0.0 to 1.0)+ /// Relevance score for notification summary (0.0 to 1.0).#[serde(skip_serializing_if = "Option::is_none")]pub relevance_score: Option<f64>,- /// Interruption level: passive, active, time-sensitive, critical+ /// Interruption level: passive, active, time-sensitive, critical.#[serde(skip_serializing_if = "Option::is_none")]pub interruption_level: Option<InterruptionLevel>,}+/// The alert content of an APNS notification.#[derive(Serialize, Debug, Deserialize)]#[serde(untagged)]pub enum Alert {+ /// A simple string alert.Simple(String),+ /// A dictionary-based alert with title, body, etc.Dictionary(AlertDictionary),}+/// Dictionary-based alert with structured fields.#[derive(Serialize, Debug, Default, Deserialize)]#[serde(rename_all = "kebab-case")]pub struct AlertDictionary {+ /// The title of the notification.#[serde(skip_serializing_if = "Option::is_none")]pub title: Option<String>,+ /// The subtitle of the notification.#[serde(skip_serializing_if = "Option::is_none")]pub subtitle: Option<String>,+ /// The body text of the notification.#[serde(skip_serializing_if = "Option::is_none")]pub body: Option<String>,- /// Localization key for title+ /// Localization key for title.#[serde(skip_serializing_if = "Option::is_none")]pub title_loc_key: Option<String>,+ /// Localization arguments for title.#[serde(skip_serializing_if = "Option::is_none")]pub title_loc_args: Option<Vec<String>>,- /// Localization key for body+ /// Localization key for body.#[serde(skip_serializing_if = "Option::is_none")]pub loc_key: Option<String>,+ /// Localization arguments for body.#[serde(skip_serializing_if = "Option::is_none")]pub loc_args: Option<Vec<String>>,- /// Custom launch image filename+ /// Custom launch image filename.#[serde(skip_serializing_if = "Option::is_none")]pub launch_image: Option<String>,}+/// Notification sound configuration.#[derive(Serialize, Debug, Deserialize)]#[serde(untagged)]pub enum Sound {- Default(String), // Usually "default"+ /// Default sound (usually "default").+ Default(String),+ /// Critical sound with volume control.Critical(CriticalSound),}+/// Critical sound configuration with volume control.#[derive(Serialize, Debug, Deserialize)]pub struct CriticalSound {- pub critical: u8, // 1 for critical+ /// Set to 1 for critical sound.+ pub critical: u8,+ /// Sound file name.pub name: String,- pub volume: f64, // 0.0 to 1.0+ /// Volume level (0.0 to 1.0).+ pub volume: f64,}+/// The interruption level of a notification.#[derive(Serialize, Debug, Deserialize)]#[serde(rename_all = "kebab-case")]pub enum InterruptionLevel {+ /// Delivered silently.Passive,+ /// Default behavior.Active,+ /// Can break through Focus modes.TimeSensitive,+ /// Highest priority, requires entitlement.Critical,}+/// A complete APNS push notification with custom data.#[derive(Serialize, Debug, Deserialize)]#[serde(rename_all = "camelCase")]pub struct APNSPushNotification<T> {+ /// The APNS payload.pub aps: Aps,- /// custom data payload to send to the client.- /// This data has no effect on 'how' the notification is delivered+ /// Custom data payload to send to the client.+ /// This data has no effect on 'how' the notification is delivered.#[serde(flatten)]pub push_notification_data: T,}--impl APNSPushNotification<()> {- /// construct a simple apple notification using the input notifications title and body- pub fn default_new<T: Notification>(notif: &T) -> Self {- APNSPushNotification {- aps: Aps {- alert: Some(Alert::Dictionary(AlertDictionary {- title: Some(notif.title()),- body: Some(notif.body()),- ..Default::default()- })),- ..Default::default()- },- push_notification_data: (),- }- }-}diff --git a/rust/cloud-storage/notification/src/domain/models/mobile.rs b/rust/cloud-storage/notification/src/domain/models/mobile.rsindex 604b01981b..0ff43ed081 100644--- a/rust/cloud-storage/notification/src/domain/models/mobile.rs+++ b/rust/cloud-storage/notification/src/domain/models/mobile.rs@@ -1,28 +1,42 @@+//! Mobile push notification models for SNS delivery.+use serde::{Deserialize, Serialize, Serializer};+use sha2::{Digest, Sha256};use crate::domain::models::{android::FCMMessage,apple::{APNSPushNotification, Alert},};+/// SNS target platform for push notifications.#[derive(Debug)]pub enum SnsTarget<'a, T> {+ /// iOS target via APNS.Ios(&'a APNSPushNotification<T>),+ /// Android target via FCM.Android(&'a FCMMessage<T>),}+/// SNS payload formatted for platform-specific delivery.#[derive(Debug, Serialize)]#[serde(bound = "T: Serialize", untagged)]-pub enum SnsPayload<'a, T> {+pub(crate) enum SnsPayload<'a, T> {+ /// iOS payload with APNS and APNS_SANDBOX keys.Ios {+ /// Default message text.default: String,+ /// Production APNS payload.#[serde(rename = "APNS", serialize_with = "stringified_json")]apns: &'a APNSPushNotification<T>,+ /// Sandbox APNS payload.#[serde(rename = "APNS_SANDBOX", serialize_with = "stringified_json")]apns_sandbox: &'a APNSPushNotification<T>,},+ /// Android payload with GCM key.Android {+ /// Default message text.default: String,+ /// FCM payload.#[serde(rename = "GCM", serialize_with = "stringified_json")]gcm: &'a FCMMessage<T>,},@@ -84,15 +98,70 @@ impl<T: Serialize> SnsTarget<'_, T> {}}+/// Used to build up the data to construct a [`HashedCollapseKey`].+///+/// Uses SHA-256 internally for stable hashing across Rust compiler versions.+pub struct NotifCollapseKey(Sha256);++/// Contains the string representation of a notification collapse key.+/// This is used to uniquely identify notifications delivered to an iOS device.+#[derive(Debug, Clone)]+pub struct HashedCollapseKey(String);++impl AsRef<str> for HashedCollapseKey {+ fn as_ref(&self) -> &str {+ &self.0+ }+}++impl HashedCollapseKey {+ /// Create from an already-hashed string.+ pub fn from_hashed(s: String) -> Self {+ Self(s)+ }++ /// Consume and return the inner string.+ pub fn into_inner(self) -> String {+ self.0+ }+}++impl NotifCollapseKey {+ /// Create a new collapse key seeded with the given string.+ pub fn new(s: &str) -> Self {+ let mut hasher = Sha256::new();+ hasher.update(s.as_bytes());+ NotifCollapseKey(hasher)+ }++ /// Append additional data to the collapse key.+ pub fn append(mut self, s: &str) -> Self {+ self.0.update(s.as_bytes());+ self+ }++ /// Finalize the key into a hex-encoded SHA-256 hash string.+ pub fn into_hashed(self) -> HashedCollapseKey {+ let hash = self.0.finalize();+ HashedCollapseKey(hex::encode(hash))+ }+}++/// APNS message attributes for SNS delivery.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct MessageAttributes {+ /// The push notification type (alert or background).pub push_type: PushType,+ /// The collapse key for grouping/replacing notifications.pub collapse_key: String,}+/// The type of push notification.#[derive(Debug, Clone, Serialize, Deserialize)]pub enum PushType {+ /// Background/silent notification.Background,+ /// Alert notification with visible content.Alert,}diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rsindex ffd8815435..42601bd3b9 100644--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs@@ -43,9 +43,9 @@ pub struct ConnGatewayNotification<'a, T> {/// The delivery channel variants.#[derive(Debug, Serialize, Deserialize)]-pub enum NotificationChannel<'a, T> {+pub enum NotificationChannel<'a, T, U> {/// Delivering to an iOS device with APNS.- Ios(Box<APNSTargets<T>>),+ Ios(Box<APNSTargets<U>>),/// Delivering to a user's email inbox.Email(EmailNotification<'a>),/// Delivering a foreground notification via connection gateway.@@ -54,17 +54,17 @@ pub enum NotificationChannel<'a, T> {/// A delivery node with optional fallback on failure.#[derive(Debug, Serialize, Deserialize)]-pub struct Node<'a, T> {+pub struct Node<'a, T, U> {/// The channel of notification we are delivering on.- pub notif: NotificationChannel<'a, T>,+ pub notif: NotificationChannel<'a, T, U>,/// The optional next channel we will attempt to deliver on if this method fails.- pub on_failure: Option<Box<Node<'a, T>>>,+ pub on_failure: Option<Box<Node<'a, T, U>>>,}/// Message published to SQS after DB persistence./// Contains everything needed for delivery.#[derive(Debug, Serialize, Deserialize)]-pub struct QueueMessage<'a, T> {+pub struct QueueMessage<'a, T, U> {/// The notification type name (e.g., "channel_message_send").pub message_type: String,/// The rate limit key for this notification.@@ -72,14 +72,22 @@ pub struct QueueMessage<'a, T> {pub rate_limit: Option<(RateLimitKey, RateLimitConfig)>,/// The methods on which we will attempt to deliver./// This is an ALL relationship.- pub content: Node<'a, T>,+ pub content: Node<'a, T, U>,+}++/// Custom data payload for a silent background push that clears a previously+/// delivered notification from the user's device.+#[derive(Debug, Serialize, Deserialize)]+pub struct ClearPushIdentifier {+ /// The collapse key identifier used to match the notification to clear.+ pub identifier: String,}/// Raw message received from SQS.#[derive(Debug)]pub struct RawQueueMessage {/// The deserialized queue message body.- pub body: QueueMessage<'static, serde_json::Value>,+ pub body: QueueMessage<'static, serde_json::Value, serde_json::Value>,/// The receipt handle for deleting the message after processing.pub receipt_handle: String,}diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rsindex 177b951d80..130b06ff1c 100644--- a/rust/cloud-storage/notification/src/domain/models/request.rs+++ b/rust/cloud-storage/notification/src/domain/models/request.rs@@ -2,13 +2,15 @@use crate::domain::{models::{- Notification, RateLimitConfig, RateLimitKey, apple::APNSPushNotification,+ ExclusionReason, FilteredRecipient, Notification, NotificationExtEmail, NotificationExtIos,+ RateLimitConfig, RateLimitKey, RecipientExclusion, apple::APNSPushNotification, mobile,mobile::MessageAttributes, queue_message::EmailContent,},service::SendNotificationError,};-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::Entity;+use itertools::Itertools;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_entity::{Entity, as_owned::IntoOwned};use rootcause::{Report, report};use serde::{Deserialize, Serialize};use std::collections::HashSet;@@ -33,7 +35,7 @@ pub struct SendNotificationRequestBuilder<'a, T> {impl<'a, T> SendNotificationRequestBuilder<'a, T> {/// Convert this builder into a full request with optional delivery customizers.- pub fn into_request(self) -> SendNotificationRequest<'a, T> {+ pub fn into_request(self) -> SendNotificationRequest<'a, T, ()> {SendNotificationRequest {req: self,build_apns: None,@@ -43,47 +45,128 @@ impl<'a, T> SendNotificationRequestBuilder<'a, T> {}}-type BuildApns<T> = Box<dyn FnMut(T) -> (APNSPushNotification<T>, MessageAttributes)>;+type BuildApns<T, U> =+ Box<dyn FnMut(T) -> Option<(APNSPushNotification<U>, MessageAttributes)> + Send>;/// Full notification request with optional delivery channel builders.////// Created from [`SendNotificationRequestBuilder::into_request`] and can be/// customized with APNS and email builders.-pub struct SendNotificationRequest<'a, T> {+pub struct SendNotificationRequest<'a, T, U> {pub(crate) req: SendNotificationRequestBuilder<'a, T>,/// define how to turn t into an APNSPushNotitication T to be sent to ios- pub(crate) build_apns: Option<BuildApns<T>>,+ pub(crate) build_apns: Option<BuildApns<T, U>>,/// define how to turn T into an email content to be sent as an email- pub(crate) build_email: Option<Box<dyn FnMut(T) -> EmailContent>>,+ pub(crate) build_email: Option<Box<dyn FnMut(T) -> EmailContent + Send>>,/// connection gateway accepts arbitrary json so we just ask if its enabled or notpub(crate) send_conn_gateway: bool,}-impl<'a, T> SendNotificationRequest<'a, T> {+impl<'a, T: NotificationExtIos, U> SendNotificationRequest<'a, T, U> {/// Add a custom APNS notification builder.- pub fn with_apns(- mut self,- cb: Box<dyn FnMut(T) -> (APNSPushNotification<T>, MessageAttributes)>,- ) -> Self {- self.build_apns.replace(cb);- self+ pub fn with_apns(self) -> SendNotificationRequest<'a, T, T::NotifData> {+ let SendNotificationRequest {+ req,+ build_apns: _,+ build_email,+ send_conn_gateway,+ } = self;++ let sender = req.sender_id.clone().map(CowLike::into_owned);+ let entity = req.notification_entity.clone().into_owned();++ SendNotificationRequest {+ req,+ build_apns: Some(Box::new(move |notif: T| {+ let collapse_key = notif.collapse_key(&entity).into_hashed().into_inner();+ let attrs = MessageAttributes {+ push_type: mobile::PushType::Alert,+ collapse_key,+ };+ let apns = notif.into_apns(sender.clone())?;++ Some((apns, attrs))+ })),+ build_email,+ send_conn_gateway,+ }}+}+impl<'a, T: NotificationExtEmail, U> SendNotificationRequest<'a, T, U> {/// Add a custom email content builder.- pub fn with_email(mut self, cb: Box<dyn FnMut(T) -> EmailContent>) -> Self {- self.build_email.replace(cb);+ pub fn with_email(mut self) -> Self {+ self.build_email = Some(Box::new(|notif: T| notif.into_email()));self}+}+impl<'a, T: Notification, U> SendNotificationRequest<'a, T, U> {/// Enable delivery via connection gateway (WebSocket).pub fn with_conn_gateway(mut self) -> Self {self.send_conn_gateway = true;self}+}- pub(crate) fn update_recipients(mut self, recipients: HashSet<MacroUserIdStr<'a>>) -> Self {- self.req.recipient_ids = recipients;- self+impl<'a, T, U> SendNotificationRequest<'a, T, U> {+ pub(crate) fn update_recipients(+ mut self,+ muted_users: HashSet<MacroUserIdStr<'a>>,+ unsubscribed_users: HashSet<MacroUserIdStr<'a>>,+ ) -> (Self, Vec<RecipientExclusion<'a>>) {+ let recipient_is_sender = |id: FilteredRecipient<'a>| match (id, &self.req.sender_id) {+ (FilteredRecipient::Allowed(macro_user_id_str), Some(sender))+ if sender == ¯o_user_id_str =>+ {+ FilteredRecipient::Excluded(RecipientExclusion {+ user_id: macro_user_id_str,+ reason: ExclusionReason::IsSender,+ })+ }+ (x, _) => x,+ };++ let user_muted_notifs = |id: FilteredRecipient<'a>| match id {+ FilteredRecipient::Allowed(macro_user_id_str)+ if muted_users.contains(¯o_user_id_str) =>+ {+ FilteredRecipient::Excluded(RecipientExclusion {+ user_id: macro_user_id_str,+ reason: ExclusionReason::MutedNotifications,+ })+ }+ x => x,+ };++ let notif_type_is_ignored = |id: FilteredRecipient<'a>| match id {+ FilteredRecipient::Allowed(macro_user_id_str)+ if unsubscribed_users.contains(¯o_user_id_str) =>+ {+ FilteredRecipient::Excluded(RecipientExclusion {+ user_id: macro_user_id_str,+ reason: ExclusionReason::UnsubscribedFromItem,+ })+ }+ x => x,+ };++ let recipients = std::mem::take(&mut self.req.recipient_ids);++ let (allowed, excluded): (HashSet<_>, Vec<_>) = recipients+ .into_iter()+ .map(FilteredRecipient::Allowed)+ .map(recipient_is_sender)+ .map(user_muted_notifs)+ .map(notif_type_is_ignored)+ .partition_map(|r| match r {+ FilteredRecipient::Allowed(a) => itertools::Either::Left(a),+ FilteredRecipient::Excluded(b) => itertools::Either::Right(b),+ });++ self.req.recipient_ids = allowed;++ (self, excluded)}}@@ -119,3 +202,47 @@ pub struct NotificationResult<'a> {/// The users who were actually notified (after filtering).pub notified_recipients: HashSet<MacroUserIdStr<'a>>,}++/// the status the user is requesting to set on the notification+#[derive(Debug)]+pub enum NotificationStatus {+ /// the notification has been seen+ Seen,+ /// the notification is either done or _not_ done+ Done(bool),+}++impl NotificationStatus {+ /// returns true if we should be clearing the relevant push notifications+ /// for this notification+ pub(crate) fn should_clear_push_notifs(&self) -> bool {+ match self {+ NotificationStatus::Seen => true,+ NotificationStatus::Done(x) => *x,+ }+ }+}++/// Request to update the status of one or more notifications for a user.+#[derive(Debug)]+pub struct UpdateNotificationsRequest<'a> {+ /// The user whose notifications are being updated.+ pub user_id: MacroUserIdStr<'a>,+ /// The notification IDs to update.+ pub notification_ids: &'a [Uuid],+ /// The status to set on the notifications.+ pub status: NotificationStatus,+}++/// Request to get a user's notifications filtered by event item IDs.+#[derive(Debug)]+pub struct GetNotificationsByEventItemIdsRequest<'a> {+ /// The user whose notifications to retrieve.+ pub user_id: &'a str,+ /// The event item IDs to filter by.+ pub event_item_ids: &'a [Uuid],+ /// Maximum number of results per page (default 20, max 500).+ pub limit: Option<u32>,+ /// Cursor for pagination.+ pub cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+}diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex 0b56887e22..2918d0d333 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -9,16 +9,19 @@ use std::future::Future;use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;use serde::Serialize;+use serde::de::DeserializeOwned;use uuid::Uuid;+use models_pagination::{CreatedAt, Query};+use crate::domain::models::{- DeviceEndpoint, Notification, RateLimitConfig, RateLimitKey, RateLimitResult,- SendNotificationRequestBuilder, android::FCMMessage, apple::APNSPushNotification,- mobile::MessageAttributes,+ DeviceEndpoint, Notification, NotificationIdAndCollapseKey, RateLimitConfig, RateLimitKey,+ RateLimitResult, SendNotificationRequestBuilder, UserNotificationRow, android::FCMMessage,+ apple::APNSPushNotification, mobile::MessageAttributes,};/// Port for sending mobile push notifications (iOS/Android via SNS).-pub trait NotificationSender {+pub trait NotificationSender: Send + Sync + 'static {/// Send an iOS push notification via APNS.fn send_ios_push_notification<T: Serialize + Send + Sync>(&self,@@ -37,7 +40,7 @@ pub trait NotificationSender {}/// Port for rate limiting operations.-pub trait RateLimitPort {+pub trait RateLimitPort: Send + Sync + 'static {/// Check if the action is allowed and increment the counter.////// The `RateLimitKey` is a hashed value - callers control what gets rate@@ -50,7 +53,7 @@ pub trait RateLimitPort {}/// Port for notification persistence operations.-pub trait NotificationRepository {+pub trait NotificationRepository: Send + Sync + 'static {/// Get users who have muted notifications.fn get_muted_users<'a>(&self,@@ -73,7 +76,7 @@ pub trait NotificationRepository {request: &SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_sender: &str,- recipient_ids: &[MacroUserIdStr<'a>],+ apns_collapse_key: Option<&str>,) -> impl Future<Output = Result<Option<Uuid>, Report>> + Send;/// Update the sent status for users who received the notification.@@ -88,10 +91,76 @@ pub trait NotificationRepository {&self,user_ids: &[MacroUserIdStr<'a>],) -> impl Future<Output = Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report>> + Send;++ /// Mark notifications as seen for a user.+ fn mark_notifications_seen(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Mark notifications as done or undone for a user.+ fn mark_notifications_done(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ done: bool,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Get basic notification data (collapse keys) needed for push clearing.+ fn get_basic_notifications(+ &self,+ notification_ids: &[Uuid],+ ) -> impl Future<Output = Result<Vec<NotificationIdAndCollapseKey>, Report>> + Send;++ /// Get a user's active (not deleted, not done) notifications with cursor-based pagination.+ ///+ /// The metadata JSON column is deserialized into `T`.+ fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;++ /// Get a user's active notifications filtered by event item IDs, with cursor-based pagination.+ ///+ /// Only returns notifications that are not deleted and not done,+ /// matching one of the provided `event_item_ids`.+ fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ event_item_ids: &[Uuid],+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;++ /// Get a single user notification by ID.+ ///+ /// 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,+ 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,+ notification_id: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Soft-delete multiple user notifications.+ fn bulk_delete_user_notifications(+ &self,+ user_id: &str,+ notification_ids: &[Uuid],+ ) -> impl Future<Output = Result<(), Report>> + Send;}/// Port for WebSocket delivery via connection gateway.-pub trait WebSocketSender {+pub trait WebSocketSender: Send + Sync + 'static {/// Send notifications to users via WebSocket.////// Returns the set of users who successfully received the notification@@ -106,7 +175,7 @@ pub trait WebSocketSender {use crate::domain::models::queue_message::EmailContent;/// Port for email delivery.-pub trait EmailSender {+pub trait EmailSender: Send + Sync + 'static {/// Send an email with pre-built content to a user.fn send_email(&self,@@ -115,14 +184,14 @@ pub trait EmailSender {) -> impl Future<Output = Result<(), Report>> + Send;}-use crate::domain::models::queue_message::{QueueMessage, RawQueueMessage};+use crate::domain::models::queue_message::{DeliverySuccess, QueueMessage, RawQueueMessage};/// Port for publishing notifications to delivery queue and receiving them.-pub trait NotificationQueue {+pub trait NotificationQueue: Send + Sync + 'static {/// Publish notifications for async delivery (after DB persistence).- fn publish<T: Serialize + Send + Sync>(+ fn publish<T: Serialize + Send + Sync, U: Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T>],+ messages: &[QueueMessage<'_, T, U>],) -> impl Future<Output = Result<(), Report>> + Send;/// Receive messages from the queue (for worker).@@ -135,3 +204,16 @@ pub trait NotificationQueue {receipt_handle: &str,) -> impl Future<Output = Result<(), Report>> + Send;}++/// Port for delivering notifications from the queue.+///+/// This trait defines the egress (outbound delivery) side of the notification+/// system. Implementations poll the queue and deliver via WebSocket, push, and email.+pub trait NotificationEgress: Send + Sync + 'static {+ /// Poll the queue and attempt to deliver notifications.+ ///+ /// Returns results for each delivery attempt across all messages received.+ /// Messages are automatically deleted from the queue after successful delivery.+ fn poll_and_deliver(&self)+ -> impl Future<Output = Vec<Result<DeliverySuccess, Report>>> + Send;+}diff --git a/rust/cloud-storage/notification/src/domain/service.rs b/rust/cloud-storage/notification/src/domain/service.rsindex 806fd01cdf..e4fd29096d 100644--- a/rust/cloud-storage/notification/src/domain/service.rs+++ b/rust/cloud-storage/notification/src/domain/service.rs@@ -12,14 +12,12 @@ mod test;use thiserror::Error;pub use egress::NotificationEgressService;+pub use ingress::NotificationIngress;pub use ingress::NotificationIngressService;/// Error returned when sending a notification fails.#[derive(Debug, Error)]pub enum SendNotificationError {- /// Rate limit was exceeded.- #[error("Rate limit exceeded")]- RateLimitExceeded,/// Invalid rate limit config, either a key was provided but a key was not, or vice versa.#[error("Rate limit config error")]RateLimitConfigErr,diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rsindex 7b17ffdb06..cbfae10f6a 100644--- a/rust/cloud-storage/notification/src/domain/service/egress.rs+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs@@ -8,7 +8,8 @@ use crate::domain::models::queue_message::{NotificationChannel, QueueMessage,};use crate::domain::ports::{- EmailSender, NotificationRepository, NotificationSender, RateLimitPort, WebSocketSender,+ EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,+ RateLimitPort, WebSocketSender,};use rootcause::prelude::ResultExt;use rootcause::{Report, report};@@ -16,7 +17,8 @@ use rootcause::{Report, report};/// Service for delivering notifications (egress side).////// Handles consuming from queue and delivering via WebSocket, push, and email.-pub struct NotificationEgressService<N, W, M, E, R> {+pub struct NotificationEgressService<Q, N, W, M, E, R> {+ queue: Q,#[allow(dead_code)]repository: N,websocket: W,@@ -25,8 +27,9 @@ pub struct NotificationEgressService<N, W, M, E, R> {rate_limiter: R,}-impl<N, W, M, E, R> NotificationEgressService<N, W, M, E, R>+impl<Q, N, W, M, E, R> NotificationEgressService<Q, N, W, M, E, R>where+ Q: NotificationQueue,N: NotificationRepository,W: WebSocketSender,M: NotificationSender,@@ -34,8 +37,16 @@ whereR: RateLimitPort,{/// Create a new egress service.- pub fn new(repository: N, websocket: W, mobile: M, email: E, rate_limiter: R) -> Self {+ pub fn new(+ queue: Q,+ repository: N,+ websocket: W,+ mobile: M,+ email: E,+ rate_limiter: R,+ ) -> Self {Self {+ queue,repository,websocket,mobile,@@ -52,7 +63,7 @@ where/// If a rate limit is configured and exceeded, returns an empty list (no delivery).pub async fn deliver_notification(&self,- message: QueueMessage<'static, serde_json::Value>,+ message: QueueMessage<'static, serde_json::Value, serde_json::Value>,) -> Vec<Result<DeliverySuccess, Report<DeliveryFailure>>> {// Check rate limit if configuredif let Some((key, config)) = message.rate_limit {@@ -78,7 +89,7 @@ whereasync fn deliver_notification_inner(&self,message_type: &str,- node: Node<'static, serde_json::Value>,+ node: Node<'static, serde_json::Value, serde_json::Value>,mut recursion_tail: Vec<Result<DeliverySuccess, Report>>,) -> Vec<Result<DeliverySuccess, Report>> {let result = match &node.notif {@@ -144,3 +155,48 @@ whereOk(DeliverySuccess::Email)}}++impl<Q, N, W, M, E, R> NotificationEgress for NotificationEgressService<Q, N, W, M, E, R>+where+ Q: NotificationQueue,+ N: NotificationRepository,+ W: WebSocketSender,+ M: NotificationSender,+ E: EmailSender,+ R: RateLimitPort,+{+ #[tracing::instrument(ret, skip(self))]+ async fn poll_and_deliver(&self) -> Vec<Result<DeliverySuccess, Report>> {+ let messages = match self.queue.receive_messages().await {+ Ok(msgs) => msgs,+ Err(e) => {+ return vec![Err(e)];+ }+ };++ let mut results = Vec::new();++ for message in messages {+ let receipt_handle = message.receipt_handle.clone();++ // Deliver the notification (body is already parsed as QueueMessage)+ let delivery_results = self.deliver_notification(message.body).await;++ // Check if all deliveries succeeded+ let all_succeeded = delivery_results.iter().all(Result::is_ok);++ // Add results (stripping the DeliveryFailure context for the trait return type)+ for result in delivery_results {+ results.push(result.map_err(Report::from));+ }++ // Delete from queue only if all deliveries succeeded+ if all_succeeded && let Err(e) = self.queue.delete_message(&receipt_handle).await {+ // if delete queue fails push it into the results+ results.push(Err(e))+ }+ }++ results+ }+}diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex 61b58e8383..bab5957cb6 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -3,26 +3,82 @@//! This service handles the caller-facing side of notifications://! filtering recipients, persisting to DB, and publishing to the queue.+use crate::domain::models::apple::{APNSPushNotification, Aps};+use crate::domain::models::mobile::{MessageAttributes, PushType};use crate::domain::models::queue_message::{- APNSTargets, ConnGatewayNotification, EmailNotification, Node, NotificationChannel,- QueueMessage,+ APNSTargets, ClearPushIdentifier, ConnGatewayNotification, EmailNotification, Node,+ NotificationChannel, QueueMessage,+};+use crate::domain::models::request::{+ GetNotificationsByEventItemIdsRequest, NotificationStatus, UpdateNotificationsRequest,};-use crate::domain::models::recipient::FilteredRecipient;use crate::domain::models::{- DeviceEndpoint, ExclusionReason, Notification, NotificationResult, RecipientExclusion,- SendNotificationRequest,+ DeviceEndpoint, Notification, NotificationResult, SendNotificationRequest, UserNotificationRow,};use crate::domain::ports::{NotificationQueue, NotificationRepository};use crate::domain::service::SendNotificationError;-use itertools::Itertools;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;use serde::Serialize;+use serde::de::DeserializeOwned;use std::collections::HashSet;use uuid::Uuid;+/// Trait for sending notifications through the ingress service.+pub trait NotificationIngress: Send + Sync + 'static {+ /// Send a notification to the specified recipients.+ fn send_notification<'a, T: Notification + Clone, U: Serialize + Send + Sync>(+ &self,+ req: SendNotificationRequest<'a, T, U>,+ ) -> impl Future<Output = Result<Option<NotificationResult<'a>>, Report<SendNotificationError>>> + Send;++ /// Mark notifications as seen for a user and enqueue push notification clearing.+ fn update_notifications(+ &self,+ req: UpdateNotificationsRequest,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Get a user's active notifications, paginated.+ ///+ /// Returns at most `limit` (default 20, max 500) notifications that are+ /// not deleted and not done, ordered by creation time descending.+ fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: Option<u32>,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send;++ /// Get a user's active notifications filtered by event item IDs, paginated.+ fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ req: GetNotificationsByEventItemIdsRequest<'_>,+ ) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send;++ /// Get a single user notification by ID.+ fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ 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,+ notification_id: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Soft-delete multiple user notifications.+ fn bulk_delete_user_notifications(+ &self,+ user_id: &str,+ notification_ids: &[Uuid],+ ) -> impl Future<Output = Result<(), Report>> + Send;+}+/// Service for sending notifications (ingress side).////// Handles recipient filtering, DB persistence, and queue publishing.@@ -30,21 +86,105 @@ use uuid::Uuid;pub struct NotificationIngressService<N, Q> {repository: N,queue: Q,- service_name: String,+ service_name: &'static str,}-impl<N, Q> NotificationIngressService<N, Q>+impl<N, Q> NotificationIngress for NotificationIngressService<N, Q>whereN: NotificationRepository,Q: NotificationQueue,{- /// Create a new ingress service.- pub fn new(repository: N, queue: Q, service_name: impl Into<String>) -> Self {- Self {- repository,- queue,- service_name: service_name.into(),+ /// Update notification status for a user and optionally enqueue push notification clearing.+ ///+ /// This method performs the following steps:+ /// 1. Update the notification status in the database (seen/done/undone)+ /// 2. If the status change should clear push notifications:+ /// a. Look up collapse keys for the given notifications+ /// b. Look up the user's iOS device endpoints+ /// c. Publish silent background push messages to clear badges on devices+ #[tracing::instrument(err, skip(self))]+ async fn update_notifications(+ &self,+ req: UpdateNotificationsRequest<'_>,+ ) -> Result<(), Report> {+ match &req.status {+ NotificationStatus::Seen => {+ self.repository+ .mark_notifications_seen(&req.user_id, req.notification_ids)+ .await?;+ }+ NotificationStatus::Done(done) => {+ self.repository+ .mark_notifications_done(&req.user_id, req.notification_ids, *done)+ .await?;+ }}++ if !req.status.should_clear_push_notifs() {+ return Ok(());+ }++ let notifications_with_keys = self+ .repository+ .get_basic_notifications(req.notification_ids)+ .await?;++ if notifications_with_keys.is_empty() {+ return Ok(());+ }++ let device_endpoints = self+ .repository+ .get_device_endpoints(&[req.user_id.copied()])+ .await?;++ let ios_endpoints: Vec<String> = device_endpoints+ .values()+ .flatten()+ .filter_map(|e| match e {+ DeviceEndpoint::Ios(arn) => Some(arn.clone()),+ DeviceEndpoint::Android(_) => None,+ })+ .collect();++ if ios_endpoints.is_empty() {+ return Ok(());+ }++ let messages: Vec<QueueMessage<'_, ClearPushIdentifier, ClearPushIdentifier>> =+ notifications_with_keys+ .into_iter()+ .map(|n| {+ let collapse_key = n.apns_collapse_key;+ QueueMessage {+ message_type: "clear_push_notification".to_string(),+ rate_limit: None,+ content: Node {+ notif: NotificationChannel::Ios(Box::new(APNSTargets {+ notif: APNSPushNotification {+ aps: Aps {+ content_available: Some(1),+ ..Default::default()+ },+ push_notification_data: ClearPushIdentifier {+ identifier: collapse_key.clone(),+ },+ },+ attributes: MessageAttributes {+ push_type: PushType::Background,+ collapse_key,+ },+ ios_device_endpoints: ios_endpoints.clone(),+ })),+ on_failure: None,+ },+ }+ })+ .collect();++ self.queue.publish(&messages).await?;++ Ok(())}/// Send a notification to the specified recipients.@@ -54,38 +194,33 @@ where/// 2. Create notification in the database/// 3. Build and publish QueueMessage to SQS/// 4. Return result (delivery happens async via worker)- pub async fn send_notification<'a, T: Notification + Serialize + Clone + Send + Sync>(+ async fn send_notification<'a, T: Notification + Clone, U: Serialize + Send + Sync>(&self,- request: SendNotificationRequest<'a, T>,+ request: SendNotificationRequest<'a, T, U>,) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {- let recipients: Vec<_> = request.req.recipient_ids.iter().cloned().collect();- let (allowed, _excluded): (Vec<_>, Vec<_>) = self- .filter_recipients(- request.req.sender_id.as_ref(),- &recipients,- &request.req.notification_entity.entity_id,- )+ let request = self+ .filter_recipients(request).await- .context(SendNotificationError::Other)?- .into_iter()- .partition_map(|r| match r {- FilteredRecipient::Allowed(macro_user_id_str) => {- itertools::Either::Left(macro_user_id_str)- }- FilteredRecipient::Excluded(recipient_exclusion) => {- itertools::Either::Right(recipient_exclusion)- }- });+ .context(SendNotificationError::Other)?;- if allowed.is_empty() {+ if request.req.recipient_ids.is_empty() {return Ok(None);}- // Create notification in DB+ // Build queue messages first so we can extract the APNS collapse key+ let mut request = request;+ let (queue_messages, apns_collapse_key) = self.build_queue_message(&mut request).await?;++ // Create notification in DB (with collapse key if APNS was built)let notification_id = Uuid::now_v7();let created = self.repository- .create_notification(&request.req, notification_id, &self.service_name, &allowed)+ .create_notification(+ &request.req,+ notification_id,+ self.service_name,+ apns_collapse_key.as_deref(),+ ).await.context(SendNotificationError::Other)?;@@ -97,12 +232,6 @@ where}));};- let mut req =- request.update_recipients(allowed.into_iter().map(CowLike::into_owned).collect());-- // Build and publish QueueMessage- let queue_messages = self.build_queue_message(&mut req).await?;-self.queue.publish(&queue_messages).await@@ -111,72 +240,126 @@ where// Return result (delivery happens async)Ok(Some(NotificationResult {notification_id,- notified_recipients: req.req.recipient_ids,+ notified_recipients: request.req.recipient_ids,}))}+ #[tracing::instrument(err, skip(self))]+ async fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: Option<u32>,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> Result<Paginated<UserNotificationRow<T>, String>, Report> {+ let limit = limit.unwrap_or(20).min(500);++ let rows = self+ .repository+ .get_user_notifications::<T>(user_id, limit, cursor)+ .await?;++ let paginated = rows+ .into_iter()+ .paginate_on(limit as usize, CreatedAt)+ .into_page()+ .type_erase();++ Ok(paginated)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ req: GetNotificationsByEventItemIdsRequest<'_>,+ ) -> Result<Paginated<UserNotificationRow<T>, String>, Report> {+ let limit = req.limit.unwrap_or(20).min(500);++ let rows = self+ .repository+ .get_user_notifications_by_event_item_ids::<T>(+ req.user_id,+ req.event_item_ids,+ limit,+ req.cursor,+ )+ .await?;++ let paginated = rows+ .into_iter()+ .paginate_on(limit as usize, CreatedAt)+ .into_page()+ .type_erase();++ Ok(paginated)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<Option<UserNotificationRow<T>>, Report> {+ self.repository+ .get_user_notification_by_id::<T>(user_id, notification_id)+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete_user_notification(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<(), Report> {+ self.repository+ .delete_user_notification(user_id, notification_id)+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn bulk_delete_user_notifications(+ &self,+ user_id: &str,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ self.repository+ .bulk_delete_user_notifications(user_id, notification_ids)+ .await+ }+}++impl<N, Q> NotificationIngressService<N, Q>+where+ N: NotificationRepository,+ Q: NotificationQueue,+{+ /// Create a new ingress service.+ pub fn new(repository: N, queue: Q) -> Self {+ Self {+ repository,+ queue,+ service_name: std::env!("CARGO_PKG_NAME"),+ }+ }+/// Filter recipients based on:/// - Sender (sender cannot receive their own notification)/// - Muted notifications/// - Unsubscribed from item- async fn filter_recipients<'a>(+ async fn filter_recipients<'a, T, U>(&self,- sender_id: Option<&MacroUserIdStr<'a>>,- recipient_ids: &'a [MacroUserIdStr<'a>],- item_id: &str,- ) -> Result<Vec<FilteredRecipient<'a>>, Report> {+ req: SendNotificationRequest<'a, T, U>,+ ) -> Result<SendNotificationRequest<'a, T, U>, Report> {+ let recipient_ids: Vec<_> = req.req.recipient_ids.iter().map(CowLike::copied).collect();+// Fetch all filter data upfrontlet (muted_users, unsubscribed_users) = tokio::try_join!(- self.repository.get_muted_users(recipient_ids),+ self.repository.get_muted_users(&recipient_ids),self.repository- .get_unsubscribed_users(item_id, recipient_ids),+ .get_unsubscribed_users(&req.req.notification_entity.entity_id, &recipient_ids),)?;- let recipient_is_sender = |id: FilteredRecipient<'a>| match (id, sender_id) {- (FilteredRecipient::Allowed(macro_user_id_str), Some(sender))- if sender == ¯o_user_id_str =>- {- FilteredRecipient::Excluded(RecipientExclusion {- user_id: macro_user_id_str,- reason: ExclusionReason::IsSender,- })- }- (x, _) => x,- };-- let user_muted_notifs = |id: FilteredRecipient<'a>| match id {- FilteredRecipient::Allowed(macro_user_id_str)- if muted_users.contains(¯o_user_id_str) =>- {- FilteredRecipient::Excluded(RecipientExclusion {- user_id: macro_user_id_str,- reason: ExclusionReason::MutedNotifications,- })- }- x => x,- };-- let notif_type_is_ignored = |id: FilteredRecipient<'a>| match id {- FilteredRecipient::Allowed(macro_user_id_str)- if unsubscribed_users.contains(¯o_user_id_str) =>- {- FilteredRecipient::Excluded(RecipientExclusion {- user_id: macro_user_id_str,- reason: ExclusionReason::UnsubscribedFromItem,- })- }- x => x,- };-- // Build exclusion reasons for excluded recipients- Ok(recipient_ids- .iter()- .map(CowLike::copied)- .map(FilteredRecipient::Allowed)- .map(recipient_is_sender)- .map(user_muted_notifs)- .map(notif_type_is_ignored)- .collect())+ let (out, _excluded) = req.update_recipients(muted_users, unsubscribed_users);+ Ok(out)}/// Build queue messages for each delivery channel.@@ -184,13 +367,15 @@ where/// - `send_conn_gateway`: Creates a single message for all recipients (1:M)/// - `build_apns`: Creates one message per recipient with their device endpoints (1:1)/// - `build_email`: Creates one message per recipient (1:1)- async fn build_queue_message<'a, T: Notification + Serialize + Clone>(+ /// Returns `(queue_messages, apns_collapse_key)`.+ async fn build_queue_message<'a, T: Notification + Clone, U: Serialize + Send + Sync>(&self,- notification: &mut SendNotificationRequest<'a, T>,- ) -> Result<Vec<QueueMessage<'a, T>>, Report<SendNotificationError>> {+ notification: &mut SendNotificationRequest<'a, T, U>,+ ) -> Result<(Vec<QueueMessage<'a, T, U>>, Option<String>), Report<SendNotificationError>> {let rate_limit = notification.req.get_rate_limit()?;let message_type = T::TYPE_NAME.to_string();let mut messages = Vec::new();+ let mut apns_collapse_key = None;// Connection gateway: 1:M (single message for all recipients)if notification.send_conn_gateway {@@ -225,8 +410,11 @@ where}).collect();- if !ios_endpoints.is_empty() {- let (apns_notif, attributes) = build_apns(notification.req.notification.clone());+ if !ios_endpoints.is_empty()+ && let Some((apns_notif, attributes)) =+ build_apns(notification.req.notification.clone())+ {+ apns_collapse_key = Some(attributes.collapse_key.clone());messages.push(QueueMessage {message_type: message_type.clone(),rate_limit: rate_limit.clone(),@@ -260,6 +448,6 @@ where}}- Ok(messages)+ Ok((messages, apns_collapse_key))}}diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex 4b89d57ed0..f948f6c05f 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -1,20 +1,27 @@//! Unit tests for the notification services.+use crate::domain::models::apple::APNSPushNotification;+use crate::domain::models::mobile::NotifCollapseKey;use crate::domain::models::queue_message::{- ConnGatewayNotification, Node, NotificationChannel, QueueMessage, RawQueueMessage,+ ConnGatewayNotification, EmailContent, Node, NotificationChannel, QueueMessage, RawQueueMessage,};+use crate::domain::models::request::{NotificationStatus, UpdateNotificationsRequest};use crate::domain::models::{- DeviceEndpoint, Notification, RateLimitConfig, RateLimitExceeded, RateLimitKey,- RateLimitResult, SendNotificationRequestBuilder,+ DeviceEndpoint, Notification, NotificationExtEmail, NotificationExtIos,+ NotificationIdAndCollapseKey, RateLimitConfig, RateLimitExceeded, RateLimitKey,+ RateLimitResult, SendNotificationRequestBuilder, UserNotificationRow,};use crate::domain::ports::{EmailSender, NotificationQueue, NotificationRepository, NotificationSender, RateLimitPort,WebSocketSender,};-use crate::domain::service::{NotificationEgressService, NotificationIngressService};+use crate::domain::service::{+ NotificationEgressService, NotificationIngress, NotificationIngressService,+};use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;use rootcause::Report;+use serde::de::DeserializeOwned;use serde::{Deserialize, Serialize};use serde_json::json;use std::collections::{HashMap, HashSet};@@ -31,14 +38,6 @@ struct TestNotification {impl Notification for TestNotification {const TYPE_NAME: &'static str = "test_notification";- fn title(&self) -> String {- "Test".to_string()- }-- fn body(&self) -> String {- self.message.clone()- }-fn rate_limit_config() -> Option<RateLimitConfig> {None}@@ -48,6 +47,33 @@ impl Notification for TestNotification {}}+impl NotificationExtIos for TestNotification {+ type NotifData = TestNotification;++ fn collapse_key(&self, _entity: &model_entity::Entity<'_>) -> NotifCollapseKey {+ NotifCollapseKey::new("test")+ }++ fn into_apns<'a>(+ self,+ _sender: Option<MacroUserIdStr<'a>>,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ Some(APNSPushNotification {+ aps: Default::default(),+ push_notification_data: self,+ })+ }+}++impl NotificationExtEmail for TestNotification {+ fn into_email(self) -> crate::domain::models::queue_message::EmailContent {+ EmailContent {+ subject: "Test".to_string(),+ body: self.message,+ }+ }+}+/// Helper to create a test user ID.fn test_user_id(email: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from_email(email).unwrap()@@ -59,6 +85,10 @@ struct MockRepository {unsubscribed_users: HashSet<MacroUserIdStr<'static>>,device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>,created_notifications: Mutex<Vec<Uuid>>,+ stored_collapse_keys: Mutex<Vec<(Uuid, Option<String>)>>,+ basic_notifications: Vec<NotificationIdAndCollapseKey>,+ mark_seen_calls: Mutex<Vec<(String, Vec<Uuid>)>>,+ mark_done_calls: Mutex<Vec<(String, Vec<Uuid>, bool)>>,}impl MockRepository {@@ -68,9 +98,21 @@ impl MockRepository {unsubscribed_users: HashSet::new(),device_endpoints: HashMap::new(),created_notifications: Mutex::new(Vec::new()),+ stored_collapse_keys: Mutex::new(Vec::new()),+ basic_notifications: Vec::new(),+ mark_seen_calls: Mutex::new(Vec::new()),+ mark_done_calls: Mutex::new(Vec::new()),}}+ fn with_basic_notification(mut self, id: Uuid, collapse_key: String) -> Self {+ self.basic_notifications.push(NotificationIdAndCollapseKey {+ id,+ apns_collapse_key: collapse_key,+ });+ self+ }+fn with_muted_user(mut self, user_id: MacroUserIdStr<'static>) -> Self {self.muted_users.insert(user_id);self@@ -115,12 +157,16 @@ impl NotificationRepository for MockRepository {_request: &SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,_service_sender: &str,- _recipient_ids: &[MacroUserIdStr<'a>],+ apns_collapse_key: Option<&str>,) -> Result<Option<Uuid>, Report> {self.created_notifications.lock().unwrap().push(notification_id);+ self.stored_collapse_keys+ .lock()+ .unwrap()+ .push((notification_id, apns_collapse_key.map(String::from)));Ok(Some(notification_id))}@@ -138,6 +184,207 @@ impl NotificationRepository for MockRepository {) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {Ok(self.device_endpoints.clone())}++ async fn mark_notifications_seen(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ self.mark_seen_calls+ .lock()+ .unwrap()+ .push((user_id.to_string(), notification_ids.to_vec()));+ Ok(())+ }++ async fn mark_notifications_done(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ done: bool,+ ) -> Result<(), Report> {+ self.mark_done_calls.lock().unwrap().push((+ user_id.to_string(),+ notification_ids.to_vec(),+ done,+ ));+ Ok(())+ }++ async fn get_basic_notifications(+ &self,+ _notification_ids: &[Uuid],+ ) -> Result<Vec<NotificationIdAndCollapseKey>, Report> {+ Ok(self.basic_notifications.clone())+ }++ async fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ _user_id: &str,+ _limit: u32,+ _cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ Ok(vec![])+ }++ async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ _user_id: &str,+ _event_item_ids: &[Uuid],+ _limit: u32,+ _cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ Ok(vec![])+ }++ async fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ _user_id: &str,+ _notification_id: Uuid,+ ) -> Result<Option<UserNotificationRow<T>>, Report> {+ Ok(None)+ }++ async fn delete_user_notification(+ &self,+ _user_id: &str,+ _notification_id: Uuid,+ ) -> Result<(), Report> {+ Ok(())+ }++ async fn bulk_delete_user_notifications(+ &self,+ _user_id: &str,+ _notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ Ok(())+ }+}++impl NotificationRepository for std::sync::Arc<MockRepository> {+ async fn get_muted_users<'a>(+ &self,+ user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {+ (**self).get_muted_users(user_ids).await+ }++ async fn get_unsubscribed_users<'a>(+ &self,+ item_id: &str,+ user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {+ (**self).get_unsubscribed_users(item_id, user_ids).await+ }++ async fn create_notification<'a, T: Notification + Send + Sync>(+ &self,+ request: &SendNotificationRequestBuilder<'a, T>,+ notification_id: Uuid,+ service_sender: &str,+ apns_collapse_key: Option<&str>,+ ) -> Result<Option<Uuid>, Report> {+ (**self)+ .create_notification(request, notification_id, service_sender, apns_collapse_key)+ .await+ }++ async fn update_sent_status<'a>(+ &self,+ notification_id: Uuid,+ user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<(), Report> {+ (**self).update_sent_status(notification_id, user_ids).await+ }++ async fn get_device_endpoints<'a>(+ &self,+ user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {+ (**self).get_device_endpoints(user_ids).await+ }++ async fn mark_notifications_seen(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ (**self)+ .mark_notifications_seen(user_id, notification_ids)+ .await+ }++ async fn mark_notifications_done(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ done: bool,+ ) -> Result<(), Report> {+ (**self)+ .mark_notifications_done(user_id, notification_ids, done)+ .await+ }++ async fn get_basic_notifications(+ &self,+ notification_ids: &[Uuid],+ ) -> Result<Vec<NotificationIdAndCollapseKey>, Report> {+ (**self).get_basic_notifications(notification_ids).await+ }++ async fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: u32,+ cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ (**self)+ .get_user_notifications(user_id, limit, cursor)+ .await+ }++ async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ event_item_ids: &[Uuid],+ limit: u32,+ cursor: models_pagination::Query<Uuid, models_pagination::CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ (**self)+ .get_user_notifications_by_event_item_ids(user_id, event_item_ids, limit, cursor)+ .await+ }++ async fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<Option<UserNotificationRow<T>>, Report> {+ (**self)+ .get_user_notification_by_id(user_id, notification_id)+ .await+ }++ async fn delete_user_notification(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<(), Report> {+ (**self)+ .delete_user_notification(user_id, notification_id)+ .await+ }++ async fn bulk_delete_user_notifications(+ &self,+ user_id: &str,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ (**self)+ .bulk_delete_user_notifications(user_id, notification_ids)+ .await+ }}/// Mock queue that tracks published messages.@@ -159,9 +406,9 @@ impl MockQueue {}impl NotificationQueue for MockQueue {- async fn publish<T: serde::Serialize + Send + Sync>(+ async fn publish<T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T>],+ messages: &[QueueMessage<'_, T, U>],) -> Result<(), Report> {let mut published = self.published.lock().unwrap();for message in messages {@@ -181,9 +428,9 @@ impl NotificationQueue for MockQueue {}impl NotificationQueue for std::sync::Arc<MockQueue> {- async fn publish<T: serde::Serialize + Send + Sync>(+ async fn publish<T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T>],+ messages: &[QueueMessage<'_, T, U>],) -> Result<(), Report> {(**self).publish(messages).await}@@ -202,7 +449,7 @@ whereN: NotificationRepository,Q: NotificationQueue,{- NotificationIngressService::new(repository, queue, "test_service")+ NotificationIngressService::new(repository, queue)}#[tokio::test]@@ -299,8 +546,7 @@ async fn test_queue_message_conn_gateway_only() {use std::sync::Arc;let queue = Arc::new(MockQueue::new());- let service =- NotificationIngressService::new(MockRepository::new(), queue.clone(), "test_service");+ let service = NotificationIngressService::new(MockRepository::new(), queue.clone());let recipient = test_user_id("[email protected]");let request = SendNotificationRequestBuilder {@@ -326,12 +572,10 @@ async fn test_queue_message_conn_gateway_only() {#[tokio::test]async fn test_queue_message_email_per_recipient() {- use crate::domain::models::queue_message::EmailContent;use std::sync::Arc;let queue = Arc::new(MockQueue::new());- let service =- NotificationIngressService::new(MockRepository::new(), queue.clone(), "test_service");+ let service = NotificationIngressService::new(MockRepository::new(), queue.clone());let recipient1 = test_user_id("[email protected]");let recipient2 = test_user_id("[email protected]");@@ -344,10 +588,7 @@ async fn test_queue_message_email_per_recipient() {recipient_ids: HashSet::from([recipient1.clone(), recipient2.clone()]),}.into_request()- .with_email(Box::new(|notif| EmailContent {- subject: "Test".to_string(),- body: notif.message,- }));+ .with_email();service.send_notification(request).await.unwrap();@@ -363,9 +604,6 @@ async fn test_queue_message_email_per_recipient() {#[tokio::test]async fn test_queue_message_multiple_channels() {- use crate::domain::models::apple::APNSPushNotification;- use crate::domain::models::mobile::{MessageAttributes, PushType};- use crate::domain::models::queue_message::EmailContent;use std::sync::Arc;let recipient = test_user_id("[email protected]");@@ -374,7 +612,7 @@ async fn test_queue_message_multiple_channels() {recipient.clone(),DeviceEndpoint::Ios("arn:aws:sns:test".to_string()),);- let service = NotificationIngressService::new(repo, queue.clone(), "test_service");+ let service = NotificationIngressService::new(repo, queue.clone());let request = SendNotificationRequestBuilder {notification_entity: EntityType::Document.with_entity_str("entity_1"),@@ -386,22 +624,8 @@ async fn test_queue_message_multiple_channels() {}.into_request().with_conn_gateway()- .with_apns(Box::new(|notif| {- (- APNSPushNotification {- aps: Default::default(),- push_notification_data: notif,- },- MessageAttributes {- push_type: PushType::Alert,- collapse_key: "test".to_string(),- },- )- }))- .with_email(Box::new(|notif| EmailContent {- subject: "Test".to_string(),- body: notif.message,- }));+ .with_apns()+ .with_email();service.send_notification(request).await.unwrap();@@ -424,6 +648,181 @@ async fn test_queue_message_multiple_channels() {assert!(has_email, "Should have Email message");}+#[tokio::test]+async fn test_apns_enqueues_correct_data_for_multiple_users() {+ use std::sync::Arc;++ let user1 = test_user_id("[email protected]");+ let user2 = test_user_id("[email protected]");+ let user3 = test_user_id("[email protected]");++ let queue = Arc::new(MockQueue::new());+ let repo = MockRepository::new()+ .with_device_endpoint(+ user1.clone(),+ DeviceEndpoint::Ios(+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice-device".to_string(),+ ),+ )+ .with_device_endpoint(+ user2.clone(),+ DeviceEndpoint::Ios(+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device".to_string(),+ ),+ )+ .with_device_endpoint(+ user2.clone(),+ DeviceEndpoint::Ios(+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device-2".to_string(),+ ),+ )+ .with_device_endpoint(+ user3.clone(),+ DeviceEndpoint::Ios(+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/charlie-device".to_string(),+ ),+ );++ let service = NotificationIngressService::new(repo, queue.clone());++ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Document.with_entity_str("doc_123"),+ notification: TestNotification {+ message: "You were mentioned".to_string(),+ },+ sender_id: None,+ recipient_ids: HashSet::from([user1.clone(), user2.clone(), user3.clone()]),+ }+ .into_request()+ .with_apns();++ service.send_notification(request).await.unwrap();++ let published = queue.get_published();+ assert_eq!(+ published.len(),+ 1,+ "APNS produces a single queue message for all recipients"+ );++ let msg = &published[0];+ assert_eq!(msg["message_type"], "test_notification");++ // The message should be an Ios variant+ let ios = &msg["content"]["notif"]["Ios"];+ assert!(ios.is_object(), "Expected Ios notification channel");++ // Verify the APNS notification payload contains the notification data+ // push_notification_data is #[serde(flatten)]'d so fields appear directly on notif+ let apns_notif = &ios["notif"];+ assert_eq!(+ apns_notif["message"], "You were mentioned",+ "APNS payload should contain the flattened notification data"+ );++ // Verify message attributes+ let attrs = &ios["attributes"];+ assert_eq!(attrs["push_type"], "Alert");+ let expected_key = NotifCollapseKey::new("test").into_hashed().into_inner();+ assert_eq!(attrs["collapse_key"], expected_key);++ // Verify all device endpoints from all users are included+ let endpoints: Vec<&str> = ios["ios_device_endpoints"]+ .as_array()+ .expect("iosDeviceEndpoints should be an array")+ .iter()+ .map(|v| v.as_str().unwrap())+ .collect();++ assert_eq!(+ endpoints.len(),+ 4,+ "Should include all 4 device endpoints across 3 users"+ );+ assert!(+ endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice-device"),+ "Should include alice's device"+ );+ assert!(+ endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device"),+ "Should include bob's first device"+ );+ assert!(+ endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob-device-2"),+ "Should include bob's second device"+ );+ assert!(+ endpoints.contains(&"arn:aws:sns:us-east-1:111:endpoint/APNS/app/charlie-device"),+ "Should include charlie's device"+ );+}++#[tokio::test]+async fn test_apns_collapse_key_stored_on_create() {+ use std::sync::Arc;++ let user = test_user_id("[email protected]");++ let repo = Arc::new(MockRepository::new().with_device_endpoint(+ user.clone(),+ DeviceEndpoint::Ios("arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice".to_string()),+ ));+ let queue = Arc::new(MockQueue::new());+ let service = NotificationIngressService::new(repo.clone(), queue);++ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Document.with_entity_str("doc_1"),+ notification: TestNotification {+ message: "Hello".to_string(),+ },+ sender_id: None,+ recipient_ids: HashSet::from([user]),+ }+ .into_request()+ .with_apns();++ service.send_notification(request).await.unwrap();++ let collapse_keys = repo.stored_collapse_keys.lock().unwrap();+ assert_eq!(collapse_keys.len(), 1);+ assert_eq!(+ collapse_keys[0].1,+ Some(NotifCollapseKey::new("test").into_hashed().into_inner()),+ "APNS collapse key should be stored when creating the notification"+ );+}++#[tokio::test]+async fn test_no_apns_collapse_key_when_apns_not_enabled() {+ use std::sync::Arc;++ let user = test_user_id("[email protected]");++ let repo = Arc::new(MockRepository::new());+ let queue = Arc::new(MockQueue::new());+ let service = NotificationIngressService::new(repo.clone(), queue);++ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Document.with_entity_str("doc_1"),+ notification: TestNotification {+ message: "Hello".to_string(),+ },+ sender_id: None,+ recipient_ids: HashSet::from([user]),+ }+ .into_request()+ .with_conn_gateway();++ service.send_notification(request).await.unwrap();++ let collapse_keys = repo.stored_collapse_keys.lock().unwrap();+ assert_eq!(collapse_keys.len(), 1);+ assert_eq!(+ collapse_keys[0].1, None,+ "No APNS collapse key should be stored when APNS is not enabled"+ );+}+// ============================================================================// Egress Service Tests// ============================================================================@@ -517,6 +916,7 @@ impl RateLimitPort for MockRateLimiter {fn create_egress_service<R: RateLimitPort>(rate_limiter: R,) -> NotificationEgressService<+ MockQueue,MockRepository,MockWebSocketSender,MockMobileSender,@@ -524,6 +924,7 @@ fn create_egress_service<R: RateLimitPort>(R,> {NotificationEgressService::new(+ MockQueue::new(),MockRepository::new(),MockWebSocketSender,MockMobileSender,@@ -616,3 +1017,236 @@ async fn test_egress_no_rate_limit_configured() {assert_eq!(results.len(), 1);assert!(results[0].is_ok());}++// ============================================================================+// Mark Notifications Seen Tests+// ============================================================================++#[tokio::test]+async fn test_mark_seen_publishes_ios_clear_message() {+ use std::sync::Arc;++ let user = test_user_id("[email protected]");+ let notif_id = Uuid::now_v7();++ let repo = Arc::new(+ MockRepository::new()+ .with_basic_notification(notif_id, "collapse_key_1".to_string())+ .with_device_endpoint(+ user.clone(),+ DeviceEndpoint::Ios(+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice".to_string(),+ ),+ ),+ );+ let queue = Arc::new(MockQueue::new());+ let service = NotificationIngressService::new(repo.clone(), queue.clone());++ let notification_ids = [notif_id];+ service+ .update_notifications(UpdateNotificationsRequest {+ user_id: user.clone(),+ notification_ids: ¬ification_ids,+ status: NotificationStatus::Seen,+ })+ .await+ .unwrap();++ // Verify DB was updated+ let mark_seen_calls = repo.mark_seen_calls.lock().unwrap();+ assert_eq!(mark_seen_calls.len(), 1);+ assert_eq!(mark_seen_calls[0].1, vec![notif_id]);++ // Verify queue message was published+ let published = queue.get_published();+ assert_eq!(published.len(), 1);++ let msg = &published[0];+ assert_eq!(msg["message_type"], "clear_push_notification");++ // Should be an Ios variant with background push+ let ios = &msg["content"]["notif"]["Ios"];+ assert!(ios.is_object(), "Expected Ios notification channel");++ // Verify silent background push payload+ let aps = &ios["notif"]["aps"];+ assert_eq!(aps["content-available"], 1);+ assert!(aps.get("alert").is_none() || aps["alert"].is_null());++ // Verify collapse key in attributes+ let attrs = &ios["attributes"];+ assert_eq!(attrs["push_type"], "Background");+ assert_eq!(attrs["collapse_key"], "collapse_key_1");++ // Verify identifier in custom data+ assert_eq!(ios["notif"]["identifier"], "collapse_key_1");++ // Verify device endpoint+ let endpoints = ios["ios_device_endpoints"].as_array().unwrap();+ assert_eq!(endpoints.len(), 1);+ assert_eq!(+ endpoints[0],+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice"+ );+}++#[tokio::test]+async fn test_mark_seen_skips_push_when_no_collapse_key() {+ use std::sync::Arc;++ let user = test_user_id("[email protected]");+ let notif_id = Uuid::now_v7();++ // No basic notifications with collapse keys (DB query filters them out)+ let repo = Arc::new(MockRepository::new().with_device_endpoint(+ user.clone(),+ DeviceEndpoint::Ios("arn:aws:sns:us-east-1:111:endpoint/APNS/app/bob".to_string()),+ ));+ let queue = Arc::new(MockQueue::new());+ let service = NotificationIngressService::new(repo.clone(), queue.clone());++ let notification_ids = [notif_id];+ service+ .update_notifications(UpdateNotificationsRequest {+ user_id: user.clone(),+ notification_ids: ¬ification_ids,+ status: NotificationStatus::Seen,+ })+ .await+ .unwrap();++ // DB should still be updated+ let mark_seen_calls = repo.mark_seen_calls.lock().unwrap();+ assert_eq!(mark_seen_calls.len(), 1);++ // But no queue message should be published+ let published = queue.get_published();+ assert!(+ published.is_empty(),+ "Should not publish when no collapse keys"+ );+}++#[tokio::test]+async fn test_mark_seen_skips_push_when_no_device_endpoints() {+ use std::sync::Arc;++ let user = test_user_id("[email protected]");+ let notif_id = Uuid::now_v7();++ let repo = Arc::new(+ MockRepository::new().with_basic_notification(notif_id, "collapse_key_1".to_string()),+ // No device endpoints registered+ );+ let queue = Arc::new(MockQueue::new());+ let service = NotificationIngressService::new(repo.clone(), queue.clone());++ let notification_ids = [notif_id];+ service+ .update_notifications(UpdateNotificationsRequest {+ user_id: user.clone(),+ notification_ids: ¬ification_ids,+ status: NotificationStatus::Seen,+ })+ .await+ .unwrap();++ // DB should still be updated+ let mark_seen_calls = repo.mark_seen_calls.lock().unwrap();+ assert_eq!(mark_seen_calls.len(), 1);++ // But no queue message should be published+ let published = queue.get_published();+ assert!(+ published.is_empty(),+ "Should not publish when no device endpoints"+ );+}++#[tokio::test]+async fn test_mark_done_updates_db_and_clears_push() {+ use std::sync::Arc;++ let user = test_user_id("[email protected]");+ let notif_id = Uuid::now_v7();++ let repo = Arc::new(+ MockRepository::new()+ .with_basic_notification(notif_id, "collapse_key_1".to_string())+ .with_device_endpoint(+ user.clone(),+ DeviceEndpoint::Ios(+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice".to_string(),+ ),+ ),+ );+ let queue = Arc::new(MockQueue::new());+ let service = NotificationIngressService::new(repo.clone(), queue.clone());++ let notification_ids = [notif_id];+ service+ .update_notifications(UpdateNotificationsRequest {+ user_id: user.clone(),+ notification_ids: ¬ification_ids,+ status: NotificationStatus::Done(true),+ })+ .await+ .unwrap();++ // Verify done was called (not seen)+ let mark_seen_calls = repo.mark_seen_calls.lock().unwrap();+ assert!(mark_seen_calls.is_empty(), "Should not call mark_seen");++ let mark_done_calls = repo.mark_done_calls.lock().unwrap();+ assert_eq!(mark_done_calls.len(), 1);+ assert_eq!(mark_done_calls[0].1, vec![notif_id]);+ assert!(mark_done_calls[0].2, "Should mark as done=true");++ // Verify push clearing was published (Done(true) should clear push)+ let published = queue.get_published();+ assert_eq!(published.len(), 1);+ assert_eq!(published[0]["message_type"], "clear_push_notification");+}++#[tokio::test]+async fn test_mark_undone_updates_db_no_push_clear() {+ use std::sync::Arc;++ let user = test_user_id("[email protected]");+ let notif_id = Uuid::now_v7();++ let repo = Arc::new(+ MockRepository::new()+ .with_basic_notification(notif_id, "collapse_key_1".to_string())+ .with_device_endpoint(+ user.clone(),+ DeviceEndpoint::Ios(+ "arn:aws:sns:us-east-1:111:endpoint/APNS/app/alice".to_string(),+ ),+ ),+ );+ let queue = Arc::new(MockQueue::new());+ let service = NotificationIngressService::new(repo.clone(), queue.clone());++ let notification_ids = [notif_id];+ service+ .update_notifications(UpdateNotificationsRequest {+ user_id: user.clone(),+ notification_ids: ¬ification_ids,+ status: NotificationStatus::Done(false),+ })+ .await+ .unwrap();++ // Verify done was called with false+ let mark_done_calls = repo.mark_done_calls.lock().unwrap();+ assert_eq!(mark_done_calls.len(), 1);+ assert!(!mark_done_calls[0].2, "Should mark as done=false");++ // Verify NO push clearing was published (Done(false) should not clear push)+ let published = queue.get_published();+ assert!(+ published.is_empty(),+ "Should not clear push when marking undone"+ );+}diff --git a/rust/cloud-storage/notification/src/inbound/http.rs b/rust/cloud-storage/notification/src/inbound/http.rsindex bf430c6f0d..8dbc6e8c41 100644--- a/rust/cloud-storage/notification/src/inbound/http.rs+++ b/rust/cloud-storage/notification/src/inbound/http.rs@@ -1,62 +1,449 @@-//! HTTP handlers for notification endpoints.-//!-//! These handlers expose the notification service via HTTP for internal-//! service-to-service communication.+//! This module exposes the http adapter for inbound http requests via an axum router+use axum::{+ Json, Router,+ extract::{Path, Query, State},+ routing::patch,+};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;+use models_pagination::{CreatedAt, CursorExtractor};+use reqwest::StatusCode;+use serde::{Deserialize, Serialize, de::DeserializeOwned};use std::sync::Arc;+use utoipa::ToSchema;+use uuid::Uuid;-use rootcause::Report;-use serde::Serialize;+use crate::domain::{+ models::{+ UserNotificationRow,+ request::{+ GetNotificationsByEventItemIdsRequest, NotificationStatus, UpdateNotificationsRequest,+ },+ },+ service::NotificationIngress,+};-use crate::domain::models::{Notification, NotificationResult, SendNotificationRequest};-use crate::domain::ports::{NotificationQueue, NotificationRepository};-use crate::domain::service::{NotificationIngressService, SendNotificationError};+/// Path parameter for a single event item ID.+#[derive(Deserialize)]+pub struct EventItemIdPath {+ /// The event item ID.+ pub event_item_id: Uuid,+}++/// Path parameter for a single notification ID.+#[derive(Deserialize)]+pub struct NotificationIdPath {+ /// The notification ID.+ pub notification_id: Uuid,+}-/// Client for sending notifications.-///-/// This is the main entry point for other services to send notifications.-/// It wraps the `NotificationIngressService` and provides a convenient API.-pub struct NotificationClient<N, Q> {- service: Arc<NotificationIngressService<N, Q>>,+/// the router state for a notification router+pub struct NotificationRouterState<S> {+ inner: Arc<S>,}-impl<N, Q> Clone for NotificationClient<N, Q> {+impl<S> Clone for NotificationRouterState<S> {fn clone(&self) -> Self {Self {- service: Arc::clone(&self.service),+ inner: Arc::clone(&self.inner),}}}-impl<N, Q> NotificationClient<N, Q>-where- N: NotificationRepository + Send + Sync,- Q: NotificationQueue + Send + Sync,-{- /// Create a new notification client.- pub fn new(service: NotificationIngressService<N, Q>) -> Self {- Self {- service: Arc::new(service),+impl<S: NotificationIngress> NotificationRouterState<S> {+ /// create a new instance of self+ pub fn new(val: S) -> Self {+ NotificationRouterState {+ inner: Arc::new(val),}}+}- /// Send a notification to the specified recipients.- ///- /// This method performs recipient filtering before persisting the notification- /// and publishing it to the queue for async delivery.- ///- /// # Arguments- ///- /// * `request` - The notification request containing recipients and content- ///- /// # Returns- ///- /// Returns the notification result including the ID and notified recipients,- /// or `None` if no valid recipients remain after filtering.- pub async fn send<'a, T: Notification + Serialize + Clone + Send + Sync>(- &self,- request: SendNotificationRequest<'a, T>,- ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {- self.service.send_notification(request).await- }+/// construct the router+pub fn router<S: NotificationIngress, 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))+}++/// the params for pagination+#[derive(serde::Deserialize)]+pub struct Params {+ /// the limit on the number of items to return in a page+ pub limit: Option<u32>,+}++/// the response from listing the users notifications+#[derive(Debug, Serialize)]+pub struct GetAllUserNotificationsResponse<T> {+ /// the list of items returned+ pub items: Vec<UserNotificationRow<T>>,+ /// the next page cursor if it exists+ pub next_cursor: Option<String>,+}++/// List user notifications with generic metadata type `T`.+pub async fn list_user_notifications<+ S: NotificationIngress,+ T: Serialize + DeserializeOwned + Send,+>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Query(Params { limit }): Query<Params>,+ cursor: CursorExtractor<Uuid, CreatedAt, ()>,+) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {+ let query = cursor.into_query(CreatedAt, ());+ let result = service+ .inner+ .get_user_notifications::<T>(macro_user.macro_user_id.as_ref(), limit, query)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get user notifications");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to get notifications",+ }),+ )+ })?;++ Ok(Json(GetAllUserNotificationsResponse {+ items: result.items,+ next_cursor: result.next_cursor,+ }))+}++/// Request body for bulk-fetching notifications by event item IDs.+#[derive(Serialize, Deserialize, Debug, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct BulkGetByEventItemIdsRequest {+ /// The event item IDs to filter notifications by.+ pub event_item_ids: Vec<Uuid>,+}++/// Get user notifications filtered by event item IDs.+#[utoipa::path(+ post,+ operation_id = "bulk_get_user_notifications_by_event_item_ids",+ path = "/v2/user_notifications/item/bulk",+ params(+ ("limit" = Option<u32>, Query, description = "Size limit per page. Default 20, max 500."),+ ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),+ ),+ request_body = BulkGetByEventItemIdsRequest,+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn bulk_get_by_event_item_ids<+ S: NotificationIngress,+ T: Serialize + DeserializeOwned + Send,+>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Query(Params { limit }): Query<Params>,+ cursor: CursorExtractor<Uuid, CreatedAt, ()>,+ Json(req): Json<BulkGetByEventItemIdsRequest>,+) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {+ let result = service+ .inner+ .get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {+ user_id: macro_user.macro_user_id.as_ref(),+ event_item_ids: &req.event_item_ids,+ limit,+ cursor: cursor.into_query(CreatedAt, ()),+ })+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get user notifications by event item ids");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to get notifications",+ }),+ )+ })?;++ Ok(Json(GetAllUserNotificationsResponse {+ items: result.items,+ next_cursor: result.next_cursor,+ }))+}++/// the notification ids that we are bulk updating+#[derive(Serialize, Deserialize, Debug, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct NotificationBulkRequest {+ /// The ids of the notifications to handle+ pub notification_ids: Vec<uuid::Uuid>,+}++/// Mark notifications as seen.+#[utoipa::path(+ patch,+ operation_id = "bulk_mark_notifications_seen",+ path = "/v2/user_notifications/bulk/seen",+ request_body = NotificationBulkRequest,+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn bulk_mark_seen<S: NotificationIngress>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Json(req): Json<NotificationBulkRequest>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ bulk_update(&service, ¯o_user, &req, NotificationStatus::Seen).await+}++/// Mark notifications as done.+#[utoipa::path(+ patch,+ operation_id = "bulk_mark_notifications_done",+ path = "/v2/user_notifications/bulk/done",+ request_body = NotificationBulkRequest,+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn bulk_mark_done<S: NotificationIngress>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Json(req): Json<NotificationBulkRequest>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ bulk_update(&service, ¯o_user, &req, NotificationStatus::Done(true)).await+}++/// Mark notifications as not done.+#[utoipa::path(+ patch,+ operation_id = "bulk_mark_notifications_undone",+ path = "/v2/user_notifications/bulk/undone",+ request_body = NotificationBulkRequest,+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn bulk_mark_undone<S: NotificationIngress>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Json(req): Json<NotificationBulkRequest>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ bulk_update(&service, ¯o_user, &req, NotificationStatus::Done(false)).await+}++async fn bulk_update<S: NotificationIngress>(+ service: &NotificationRouterState<S>,+ macro_user: &MacroUserExtractor,+ req: &NotificationBulkRequest,+ status: NotificationStatus,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ service+ .inner+ .update_notifications(UpdateNotificationsRequest {+ user_id: macro_user.macro_user_id.clone(),+ notification_ids: &req.notification_ids,+ status,+ })+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to update notifications");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to update notifications",+ }),+ )+ })?;++ Ok(Json(()))+}++/// Get user notifications for a single event item ID.+#[utoipa::path(+ get,+ operation_id = "get_user_notifications_by_event_item_id",+ path = "/v2/user_notifications/item/{event_item_id}",+ params(+ ("event_item_id" = Uuid, Path, description = "The event item ID"),+ ("limit" = Option<u32>, Query, description = "Size limit per page. Default 20, max 500."),+ ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn get_by_event_item_id<+ S: NotificationIngress,+ T: Serialize + DeserializeOwned + Send,+>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,+ Query(Params { limit }): Query<Params>,+ cursor: CursorExtractor<Uuid, CreatedAt, ()>,+) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {+ let result = service+ .inner+ .get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {+ user_id: macro_user.macro_user_id.as_ref(),+ event_item_ids: &[event_item_id],+ limit,+ cursor: cursor.into_query(CreatedAt, ()),+ })+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get user notifications by event item id");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to get notifications",+ }),+ )+ })?;++ Ok(Json(GetAllUserNotificationsResponse {+ items: result.items,+ next_cursor: result.next_cursor,+ }))+}++/// Get a single user notification by ID.+#[utoipa::path(+ get,+ operation_id = "get_user_notification_by_id_v2",+ path = "/v2/user_notifications/{notification_id}",+ params(+ ("notification_id" = Uuid, Path, description = "ID of the notification"),+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn get_notification_by_id<+ S: NotificationIngress,+ T: Serialize + DeserializeOwned + Send,+>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,+) -> 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)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to get user notification by id");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to get notification",+ }),+ )+ })?;++ let Some(notification) = result else {+ return Err((+ StatusCode::NOT_FOUND,+ Json(ErrorResponse {+ message: "notification not found",+ }),+ ));+ };++ Ok(Json(notification))+}++/// Soft-delete a single user notification.+#[utoipa::path(+ delete,+ operation_id = "delete_user_notification_v2",+ path = "/v2/user_notifications/{notification_id}",+ params(+ ("notification_id" = Uuid, Path, description = "ID of the notification"),+ ),+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn delete_notification<S: NotificationIngress>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ service+ .inner+ .delete_user_notification(macro_user.macro_user_id.as_ref(), notification_id)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to delete user notification");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to delete notification",+ }),+ )+ })?;++ Ok(Json(()))+}++/// Soft-delete multiple user notifications.+#[utoipa::path(+ delete,+ operation_id = "bulk_delete_user_notifications_v2",+ path = "/v2/user_notifications/bulk",+ request_body = NotificationBulkRequest,+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn bulk_delete_notifications<S: NotificationIngress>(+ State(service): State<NotificationRouterState<S>>,+ macro_user: MacroUserExtractor,+ Json(req): Json<NotificationBulkRequest>,+) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {+ service+ .inner+ .bulk_delete_user_notifications(macro_user.macro_user_id.as_ref(), &req.notification_ids)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "failed to delete user notifications");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "failed to delete notifications",+ }),+ )+ })?;++ Ok(Json(()))}diff --git a/rust/cloud-storage/notification/src/inbound/worker.rs b/rust/cloud-storage/notification/src/inbound/worker.rsindex cdd6aced1b..40e4115d34 100644--- a/rust/cloud-storage/notification/src/inbound/worker.rs+++ b/rust/cloud-storage/notification/src/inbound/worker.rs@@ -4,71 +4,41 @@//! and persisted. The main work (rate limiting, filtering) is done pre-queue,//! so this worker focuses on delivery.-use rootcause::Report;-use tracing::instrument;--use crate::domain::ports::{- EmailSender, NotificationQueue, NotificationRepository, NotificationSender, RateLimitPort,- WebSocketSender,-};-use crate::domain::service::NotificationEgressService;+use crate::domain::ports::NotificationEgress;/// Worker that processes notifications from the queue and delivers them.-pub struct NotificationWorker<Q, N, W, M, E, R> {- queue: Q,- egress: NotificationEgressService<N, W, M, E, R>,+///+/// This is a thin wrapper around a `NotificationEgress` implementation that+/// runs the poll loop continuously.+pub struct NotificationWorker<S> {+ service: S,}-impl<Q, N, W, M, E, R> NotificationWorker<Q, N, W, M, E, R>+impl<S> NotificationWorker<S>where- Q: NotificationQueue,- N: NotificationRepository,- W: WebSocketSender,- M: NotificationSender,- E: EmailSender,- R: RateLimitPort,+ S: NotificationEgress,{/// Create a new notification worker.- pub fn new(queue: Q, egress: NotificationEgressService<N, W, M, E, R>) -> Self {- Self { queue, egress }+ pub fn new(service: S) -> Self {+ Self { service }}/// Run a single iteration of the worker loop.///- /// Receives messages from the queue, processes each one, and deletes- /// successfully processed messages.- ///- /// Returns the number of messages successfully processed.- #[instrument(skip(self), err)]- pub async fn poll_and_process(&self) -> Result<usize, Report> {- let messages = self.queue.receive_messages().await?;- let count = messages.len();-- for message in messages {- let receipt_handle = message.receipt_handle.clone();-- // Process the message through egress service- let results = self.egress.deliver_notification(message.body).await;-- // Check if any delivery failed- let has_failure = results.iter().any(|r| r.is_err());-- if has_failure {- // Log failures - message will be retried via visibility timeout- for result in &results {- if let Err(e) = result {- tracing::error!(error = ?e, "failed to deliver notification");- }- }- } else {- // All deliveries succeeded, delete from queue- if let Err(e) = self.queue.delete_message(&receipt_handle).await {- tracing::error!(error = ?e, "failed to delete message from queue");- }+ /// Polls the queue and delivers notifications. Returns the number of+ /// delivery results (may include failures).+ async fn poll_and_process(&self) -> usize {+ let results = self.service.poll_and_deliver().await;+ let count = results.len();++ // Log any failures+ for result in &results {+ if let Err(e) = result {+ tracing::error!(error = ?e, "failed to deliver notification");}}- Ok(count)+ count}/// Run the worker loop continuously.@@ -77,19 +47,13 @@ where/// It includes a small delay between empty polls to avoid hammering the queue.pub async fn run(&self) -> ! {loop {- match self.poll_and_process().await {- Ok(0) => {- // No messages, wait a bit before next poll- tokio::time::sleep(std::time::Duration::from_secs(1)).await;- }- Ok(count) => {- tracing::debug!(count, "processed messages");- }- Err(e) => {- tracing::error!(error = ?e, "worker poll failed");- // Wait before retrying after error- tokio::time::sleep(std::time::Duration::from_secs(5)).await;- }+ let count = self.poll_and_process().await;++ if count == 0 {+ // No messages, wait a bit before next poll+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;+ } else {+ tracing::debug!(count, "processed delivery results");}}}diff --git a/rust/cloud-storage/notification/src/lib.rs b/rust/cloud-storage/notification/src/lib.rsindex 00bf72f29d..dd8e42a394 100644--- a/rust/cloud-storage/notification/src/lib.rs+++ b/rust/cloud-storage/notification/src/lib.rs@@ -7,7 +7,8 @@/// Domain layer containing core business logic, models, and port definitions.pub mod domain;-/// Inbound adapters (HTTP handlers, clients).+/// Inbound adapters (HTTP handlers, queue worker).+#[cfg(feature = "axum")]pub mod inbound;-/// Outbound adapters (database, Redis, WebSocket gateway, SNS, SES).+/// Outbound adapters (database, queue, Redis, WebSocket gateway, SNS, SES).pub mod outbound;diff --git a/rust/cloud-storage/notification/src/outbound/email.rs b/rust/cloud-storage/notification/src/outbound/email.rsindex 4d3e4b9e45..dd80a8f2df 100644--- a/rust/cloud-storage/notification/src/outbound/email.rs+++ b/rust/cloud-storage/notification/src/outbound/email.rs@@ -77,7 +77,7 @@ impl EmailServiceOps for aws_sdk_sesv2::Client {}}-impl<E: EmailServiceOps + Send + Sync> EmailSender for EmailAdapter<E> {+impl<E: EmailServiceOps + Send + Sync + 'static> EmailSender for EmailAdapter<E> {async fn send_email(&self,recipient: MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/notification/src/outbound/mobile.rs b/rust/cloud-storage/notification/src/outbound/mobile.rsindex b514c39b29..64274ae178 100644--- a/rust/cloud-storage/notification/src/outbound/mobile.rs+++ b/rust/cloud-storage/notification/src/outbound/mobile.rs@@ -16,12 +16,12 @@ use crate::domain::ports::NotificationSender;/// and FCM (Android) through SNS.pub struct MobilePushAdapter<P> {push_service: P,- apns_bundle_id: &'static str,+ apns_bundle_id: String,}impl<P> MobilePushAdapter<P> {/// Create a new mobile push adapter.- pub fn new(push_service: P, apns_bundle_id: &'static str) -> Self {+ pub fn new(push_service: P, apns_bundle_id: String) -> Self {Self {push_service,apns_bundle_id,@@ -63,7 +63,7 @@ impl MobilePushOps for aws_sdk_sns::Client {}}-impl<P: MobilePushOps + Send + Sync> NotificationSender for MobilePushAdapter<P> {+impl<P: MobilePushOps + Send + Sync + 'static> NotificationSender for MobilePushAdapter<P> {async fn send_ios_push_notification<T: Serialize + Send + Sync>(&self,endpoint_arn: &str,@@ -71,7 +71,7 @@ impl<P: MobilePushOps + Send + Sync> NotificationSender for MobilePushAdapter<P>attributes: &MessageAttributes,) -> Result<(), Report> {let target = SnsTarget::Ios(notification);- let sns_attributes = build_sns_attributes(self.apns_bundle_id, attributes);+ let sns_attributes = build_sns_attributes(&self.apns_bundle_id, attributes);self.push_service.push_notification(endpoint_arn, &target, sns_attributes).await@@ -84,7 +84,7 @@ impl<P: MobilePushOps + Send + Sync> NotificationSender for MobilePushAdapter<P>attributes: &MessageAttributes,) -> Result<(), Report> {let target = SnsTarget::Android(notification);- let sns_attributes = build_sns_attributes(self.apns_bundle_id, attributes);+ let sns_attributes = build_sns_attributes(&self.apns_bundle_id, attributes);self.push_service.push_notification(endpoint_arn, &target, sns_attributes).awaitdiff --git a/rust/cloud-storage/notification/src/outbound/queue.rs b/rust/cloud-storage/notification/src/outbound/queue.rsindex 50a55f5dcb..fa0e3f1d83 100644--- a/rust/cloud-storage/notification/src/outbound/queue.rs+++ b/rust/cloud-storage/notification/src/outbound/queue.rs@@ -8,6 +8,7 @@ use crate::domain::models::queue_message::{QueueMessage, RawQueueMessage};use crate::domain::ports::NotificationQueue;/// SQS-backed implementation of the notification queue port.+#[derive(Clone)]pub struct SqsNotificationQueue {client: SqsClient,queue_url: String,@@ -21,9 +22,9 @@ impl SqsNotificationQueue {}impl NotificationQueue for SqsNotificationQueue {- async fn publish<T: Serialize + Send + Sync>(+ async fn publish<T: Serialize + Send + Sync, U: Serialize + Send + Sync>(&self,- messages: &[QueueMessage<'_, T>],+ messages: &[QueueMessage<'_, T, U>],) -> Result<(), Report> {for message in messages {let body = serde_json::to_string(message)?;@@ -75,3 +76,88 @@ impl NotificationQueue for SqsNotificationQueue {Ok(())}}++/// File-based queue for local development across multiple processes.+/// Each message is stored as a separate JSON file in a directory.+pub struct FileQueue {+ dir: std::path::PathBuf,+}++impl FileQueue {+ /// Create a new file-based queue at the given directory path.+ /// Creates the directory if it doesn't exist.+ pub fn new(dir: impl Into<std::path::PathBuf>) -> Result<Self, Report> {+ let dir = dir.into();+ std::fs::create_dir_all(&dir)?;+ tracing::info!(path = ?dir, "initialized file queue");+ Ok(Self { dir })+ }++ /// Create a new file-based queue in /tmp.+ pub fn new_in_temp() -> Result<Self, Report> {+ Self::new("/tmp/macro-notification-queue")+ }+}++impl NotificationQueue for FileQueue {+ async fn publish<T: Serialize + Send + Sync, U: Serialize + Send + Sync>(+ &self,+ messages: &[QueueMessage<'_, T, U>],+ ) -> Result<(), Report> {+ for message in messages {+ let id = uuid::Uuid::new_v4();+ let filename = format!("{}.json", id);+ let path = self.dir.join(&filename);+ let content = serde_json::to_string_pretty(message)?;+ tokio::fs::write(&path, content).await?;+ }+ Ok(())+ }++ async fn receive_messages(&self) -> Result<Vec<RawQueueMessage>, Report> {+ let mut messages = Vec::new();+ let mut entries = tokio::fs::read_dir(&self.dir).await?;++ while let Some(entry) = entries.next_entry().await? {+ if messages.len() >= 10 {+ break;+ }++ let path = entry.path();+ if path.extension().is_some_and(|ext| ext == "json") {+ let filename = path+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or_default()+ .to_string();++ match tokio::fs::read_to_string(&path).await {+ Ok(content) => match serde_json::from_str(&content) {+ Ok(body) => {+ messages.push(RawQueueMessage {+ body,+ receipt_handle: filename,+ });+ }+ Err(e) => {+ tracing::warn!(error = ?e, path = ?path, "failed to parse queue message");+ }+ },+ Err(e) => {+ tracing::warn!(error = ?e, path = ?path, "failed to read queue message");+ }+ }+ }+ }++ Ok(messages)+ }++ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Report> {+ let path = self.dir.join(receipt_handle);+ if path.exists() {+ tokio::fs::remove_file(&path).await?;+ }+ Ok(())+ }+}diff --git a/rust/cloud-storage/notification/src/outbound/rate_limit.rs b/rust/cloud-storage/notification/src/outbound/rate_limit.rsindex 02b18f0ce9..587b167504 100644--- a/rust/cloud-storage/notification/src/outbound/rate_limit.rs+++ b/rust/cloud-storage/notification/src/outbound/rate_limit.rs@@ -63,7 +63,7 @@ impl RedisRateLimitOps for redis::Client {}}-impl<R: RedisRateLimitOps + Send + Sync> RateLimitPort for RedisRateLimitAdapter<R> {+impl<R: RedisRateLimitOps + Send + Sync + 'static> RateLimitPort for RedisRateLimitAdapter<R> {async fn check_and_increment(&self,key: RateLimitKey,diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rsindex a3f8781c89..b24f0eeafe 100644--- a/rust/cloud-storage/notification/src/outbound/repository.rs+++ b/rust/cloud-storage/notification/src/outbound/repository.rs@@ -3,13 +3,20 @@#[cfg(test)]mod test;-use crate::domain::models::{DeviceEndpoint, Notification, SendNotificationRequestBuilder};+use crate::domain::models::{+ DeviceEndpoint, Notification, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,+ UserNotificationRow,+};use crate::domain::ports::NotificationRepository;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use models_pagination::{CreatedAt, Query};use rootcause::Report;+use serde::de::DeserializeOwned;use sqlx::PgPool;use std::collections::{HashMap, HashSet};+use std::str::FromStr;use uuid::Uuid;/// Local representation of the `notification_device_type_option` Postgres enum@@ -42,7 +49,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 {+pub trait NotificationDbOps: Send + Sync + 'static {/// Get users who have muted all notifications.fn get_muted_users<'a>(&self,@@ -72,7 +79,7 @@ pub trait NotificationDbOps {request: &SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_name: &str,- recipient_ids: &[MacroUserIdStr<'a>],+ apns_collapse_key: Option<&str>,) -> impl std::future::Future<Output = Result<Option<Uuid>, Report>> + Send;/// Update the sent status for recipients who received the notification.@@ -81,6 +88,67 @@ pub trait NotificationDbOps {notification_id: Uuid,user_ids: &[MacroUserIdStr<'a>],) -> impl std::future::Future<Output = Result<(), Report>> + Send;++ /// Mark notifications as seen for a user.+ fn mark_notifications_seen(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;++ /// Mark notifications as done or undone for a user.+ fn mark_notifications_done(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ done: bool,+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;++ /// Get basic notification data (collapse keys) for push clearing.+ fn get_basic_notifications(+ &self,+ notification_ids: &[Uuid],+ ) -> impl std::future::Future<Output = Result<Vec<NotificationIdAndCollapseKey>, Report>> + Send;++ /// Get a user's active (not deleted, not done) notifications with cursor-based pagination.+ ///+ /// The metadata JSON column is deserialized into `T`.+ fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> impl std::future::Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;++ /// 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,+ event_item_ids: &[Uuid],+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> impl std::future::Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;++ /// Get a single user notification by ID.+ fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ 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,+ 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,+ notification_ids: &[Uuid],+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;}impl NotificationDbOps for PgPool {@@ -187,7 +255,7 @@ impl NotificationDbOps for PgPool {request: &SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_name: &str,- recipient_ids: &[MacroUserIdStr<'a>],+ apns_collapse_key: Option<&str>,) -> Result<Option<Uuid>, Report> {let entity_type: &str = request.notification_entity.entity_type.into();let metadata = serde_json::to_value(&request.notification).ok();@@ -197,10 +265,10 @@ impl NotificationDbOps for PgPool {let sender_id = request.sender_id.as_ref().map(|id| id.to_string());// Insert notification- sqlx::query!(+ let result = sqlx::query!(r#"- INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)- VALUES ($1, $2, $3, $4, $5, $6, $7)+ INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id, apns_collapse_key)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)ON CONFLICT (id) DO NOTHING"#,notification_id,@@ -209,13 +277,23 @@ impl NotificationDbOps for PgPool {entity_type,service_name,metadata as Option<serde_json::Value>,- sender_id+ sender_id,+ apns_collapse_key).execute(&mut *tx).await?;+ // Return None early if notification already exists (conflict)+ if result.rows_affected() == 0 {+ return Ok(None);+ }+// Insert user notifications- let user_ids: Vec<String> = recipient_ids.iter().map(|id| id.to_string()).collect();+ let user_ids: Vec<String> = request+ .recipient_ids+ .iter()+ .map(|id| id.to_string())+ .collect();sqlx::query!(r#"@@ -255,6 +333,352 @@ impl NotificationDbOps for PgPool {Ok(())}++ async fn mark_notifications_seen(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ let user_id_str = user_id.to_string();++ sqlx::query!(+ r#"+ UPDATE user_notification+ SET seen_at = NOW()+ WHERE user_id = $1 AND notification_id = ANY($2)+ "#,+ user_id_str,+ notification_ids+ )+ .execute(self)+ .await?;++ Ok(())+ }++ async fn mark_notifications_done(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ done: bool,+ ) -> Result<(), Report> {+ let user_id_str = user_id.to_string();++ sqlx::query!(+ r#"+ UPDATE user_notification+ SET done = $3+ WHERE user_id = $1 AND notification_id = ANY($2)+ "#,+ user_id_str,+ notification_ids,+ done+ )+ .execute(self)+ .await?;++ Ok(())+ }++ async fn get_basic_notifications(+ &self,+ notification_ids: &[Uuid],+ ) -> Result<Vec<NotificationIdAndCollapseKey>, Report> {+ let rows = sqlx::query!(+ r#"+ SELECT id, apns_collapse_key as "apns_collapse_key!: String"+ FROM notification+ WHERE id = ANY($1) AND apns_collapse_key IS NOT NULL+ "#,+ notification_ids+ )+ .fetch_all(self)+ .await?;++ Ok(rows+ .into_iter()+ .map(|row| NotificationIdAndCollapseKey {+ id: row.id,+ apns_collapse_key: row.apns_collapse_key,+ })+ .collect())+ }++ async fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ let query_limit = limit as i64;+ let (cursor_id, cursor_timestamp) = cursor.vals();++ let rows = sqlx::query!(+ r#"+ SELECT+ un.user_id as owner_id,+ un.notification_id,+ n.event_item_id,+ n.event_item_type,+ un.sent,+ un.done,+ un.created_at::timestamptz,+ un.seen_at::timestamptz as viewed_at,+ un.created_at::timestamptz as updated_at,+ un.deleted_at::timestamptz,+ n.metadata as "notification_metadata: serde_json::Value",+ n.notification_event_type as notification_event_type,+ n.sender_id as sender_id+ FROM user_notification un+ JOIN notification n ON n.id = un.notification_id+ WHERE un.user_id = $1+ AND un.deleted_at IS NULL+ AND un.done = false+ AND (($3::timestamptz IS NULL)+ OR (un.created_at, un.notification_id) < ($3, $4))+ ORDER BY un.created_at DESC, un.notification_id DESC+ LIMIT $2+ "#,+ user_id,+ query_limit,+ cursor_timestamp,+ cursor_id as _,+ )+ .fetch_all(self)+ .await?;++ rows.into_iter()+ .map(|row| {+ let entity = EntityType::from_str(&row.event_item_type)+ .map_err(|e| rootcause::report!(e))?+ .with_entity_string(row.event_item_id);++ let sender_id = row+ .sender_id+ .map(|s| MacroUserIdStr::parse_from_str(&s).map(CowLike::into_owned))+ .transpose()+ .map_err(|e| rootcause::report!(e))?;++ let owner_id = MacroUserIdStr::parse_from_str(&row.owner_id)+ .map(CowLike::into_owned)+ .map_err(|e| rootcause::report!(e))?;++ let notification_metadata = serde_json::from_value::<T>(row.notification_metadata)+ .map_err(|e| rootcause::report!(e))?;++ Ok(UserNotificationRow {+ owner_id,+ notification_id: row.notification_id,+ notification_event_type: row.notification_event_type,+ entity,+ sent: row.sent,+ done: row.done,+ created_at: row.created_at,+ viewed_at: row.viewed_at,+ updated_at: row.updated_at,+ deleted_at: row.deleted_at,+ notification_metadata,+ sender_id,+ })+ })+ .collect()+ }++ async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ event_item_ids: &[Uuid],+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ let query_limit = limit as i64;+ let (cursor_id, cursor_timestamp) = cursor.vals();+ let event_item_ids: Vec<String> = event_item_ids.iter().map(|id| id.to_string()).collect();++ let rows = sqlx::query!(+ r#"+ SELECT+ un.user_id as owner_id,+ un.notification_id,+ n.event_item_id,+ n.event_item_type,+ un.sent,+ un.done,+ un.created_at::timestamptz,+ un.seen_at::timestamptz as viewed_at,+ un.created_at::timestamptz as updated_at,+ un.deleted_at::timestamptz,+ n.metadata as "notification_metadata: serde_json::Value",+ n.notification_event_type as notification_event_type,+ n.sender_id as sender_id+ FROM user_notification un+ JOIN notification n ON n.id = un.notification_id+ WHERE un.user_id = $1+ AND n.event_item_id = ANY($2)+ AND un.deleted_at IS NULL+ AND un.done = false+ AND (($4::timestamptz IS NULL)+ OR (un.created_at, un.notification_id) < ($4, $5))+ ORDER BY un.created_at DESC, un.notification_id DESC+ LIMIT $3+ "#,+ user_id,+ &event_item_ids,+ query_limit,+ cursor_timestamp,+ cursor_id as _,+ )+ .fetch_all(self)+ .await?;++ rows.into_iter()+ .map(|row| {+ let entity = EntityType::from_str(&row.event_item_type)+ .map_err(|e| rootcause::report!(e))?+ .with_entity_string(row.event_item_id);++ let sender_id = row+ .sender_id+ .map(|s| MacroUserIdStr::parse_from_str(&s).map(CowLike::into_owned))+ .transpose()+ .map_err(|e| rootcause::report!(e))?;++ let owner_id = MacroUserIdStr::parse_from_str(&row.owner_id)+ .map(CowLike::into_owned)+ .map_err(|e| rootcause::report!(e))?;++ let notification_metadata = serde_json::from_value::<T>(row.notification_metadata)+ .map_err(|e| rootcause::report!(e))?;++ Ok(UserNotificationRow {+ owner_id,+ notification_id: row.notification_id,+ notification_event_type: row.notification_event_type,+ entity,+ sent: row.sent,+ done: row.done,+ created_at: row.created_at,+ viewed_at: row.viewed_at,+ updated_at: row.updated_at,+ deleted_at: row.deleted_at,+ notification_metadata,+ sender_id,+ })+ })+ .collect()+ }++ async fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<Option<UserNotificationRow<T>>, Report> {+ let row = sqlx::query!(+ r#"+ SELECT+ un.user_id as owner_id,+ un.notification_id,+ n.event_item_id,+ n.event_item_type,+ un.sent,+ un.done,+ un.created_at::timestamptz,+ un.seen_at::timestamptz as viewed_at,+ un.created_at::timestamptz as updated_at,+ un.deleted_at::timestamptz,+ n.metadata as "notification_metadata: serde_json::Value",+ n.notification_event_type as notification_event_type,+ n.sender_id as sender_id+ FROM user_notification un+ JOIN notification n ON n.id = un.notification_id+ WHERE un.user_id = $1+ AND un.notification_id = $2+ AND un.deleted_at IS NULL+ LIMIT 1+ "#,+ user_id,+ notification_id,+ )+ .fetch_optional(self)+ .await?;++ let Some(row) = row else {+ return Ok(None);+ };++ let entity = EntityType::from_str(&row.event_item_type)+ .map_err(|e| rootcause::report!(e))?+ .with_entity_string(row.event_item_id);++ let sender_id = row+ .sender_id+ .as_deref()+ .map(|s| MacroUserIdStr::parse_from_str(s).map(CowLike::into_owned))+ .transpose()+ .map_err(|e| rootcause::report!(e))?;++ let owner_id = MacroUserIdStr::parse_from_str(&row.owner_id)+ .map(CowLike::into_owned)+ .map_err(|e| rootcause::report!(e))?;++ let notification_metadata = serde_json::from_value::<T>(row.notification_metadata)+ .map_err(|e| rootcause::report!(e))?;++ Ok(Some(UserNotificationRow {+ owner_id,+ notification_id: row.notification_id,+ notification_event_type: row.notification_event_type,+ entity,+ sent: row.sent,+ done: row.done,+ created_at: row.created_at,+ viewed_at: row.viewed_at,+ updated_at: row.updated_at,+ deleted_at: row.deleted_at,+ notification_metadata,+ sender_id,+ }))+ }++ async fn delete_user_notification(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<(), Report> {+ sqlx::query!(+ r#"+ UPDATE user_notification+ SET deleted_at = NOW()+ WHERE user_id = $1 AND notification_id = $2+ "#,+ user_id,+ notification_id,+ )+ .execute(self)+ .await?;++ Ok(())+ }++ async fn bulk_delete_user_notifications(+ &self,+ user_id: &str,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ sqlx::query!(+ r#"+ UPDATE user_notification+ SET deleted_at = NOW()+ WHERE user_id = $1 AND notification_id = ANY($2)+ "#,+ user_id,+ notification_ids,+ )+ .execute(self)+ .await?;++ Ok(())+ }}impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificationRepository<D> {@@ -285,10 +709,10 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificatirequest: &SendNotificationRequestBuilder<'a, T>,notification_id: Uuid,service_name: &str,- recipient_ids: &[MacroUserIdStr<'a>],+ apns_collapse_key: Option<&str>,) -> Result<Option<Uuid>, Report> {self.db- .create_notification(request, notification_id, service_name, recipient_ids)+ .create_notification(request, notification_id, service_name, apns_collapse_key).await}@@ -299,4 +723,83 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati) -> Result<(), Report> {self.db.update_sent_status(notification_id, user_ids).await}++ async fn mark_notifications_seen(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ self.db+ .mark_notifications_seen(user_id, notification_ids)+ .await+ }++ async fn mark_notifications_done(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ done: bool,+ ) -> Result<(), Report> {+ self.db+ .mark_notifications_done(user_id, notification_ids, done)+ .await+ }++ async fn get_basic_notifications(+ &self,+ notification_ids: &[Uuid],+ ) -> Result<Vec<NotificationIdAndCollapseKey>, Report> {+ self.db.get_basic_notifications(notification_ids).await+ }++ async fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ self.db.get_user_notifications(user_id, limit, cursor).await+ }++ async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ event_item_ids: &[Uuid],+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ self.db+ .get_user_notifications_by_event_item_ids(user_id, event_item_ids, limit, cursor)+ .await+ }++ async fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<Option<UserNotificationRow<T>>, Report> {+ self.db+ .get_user_notification_by_id(user_id, notification_id)+ .await+ }++ async fn delete_user_notification(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<(), Report> {+ self.db+ .delete_user_notification(user_id, notification_id)+ .await+ }++ async fn bulk_delete_user_notifications(+ &self,+ user_id: &str,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ self.db+ .bulk_delete_user_notifications(user_id, notification_ids)+ .await+ }}diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rsindex 303091d68a..c92e4dd0e0 100644--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs@@ -2,6 +2,7 @@ use super::*;use macro_db_migrator::MACRO_DB_MIGRATIONS;use model_entity::EntityType;+use models_pagination::CreatedAt;use serde::{Deserialize, Serialize};use sqlx::{Pool, Postgres};@@ -13,14 +14,6 @@ struct TestNotification {impl Notification for TestNotification {const TYPE_NAME: &'static str = "test_notification";- fn title(&self) -> String {- "Test".to_string()- }-- fn body(&self) -> String {- self.message.clone()- }-fn rate_limit_config() -> Option<crate::domain::models::RateLimitConfig> {None}@@ -139,12 +132,7 @@ async fn test_create_notification(pool: Pool<Postgres>) {};let result = pool- .create_notification(- &request,- notification_id,- "test_service",- &[recipient.clone()],- )+ .create_notification(&request, notification_id, "test_service", None).await.unwrap();@@ -190,3 +178,188 @@ async fn test_update_sent_status(pool: Pool<Postgres>) {assert!(row.sent);}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../fixtures",+ scripts("notifications_with_collapse_keys")+ )+)]+async fn test_mark_notifications_seen(pool: Pool<Postgres>) {+ let user = test_user("[email protected]");+ let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();++ pool.mark_notifications_seen(&user, &[notification_id])+ .await+ .unwrap();++ let row = sqlx::query!(+ "SELECT seen_at FROM user_notification WHERE notification_id = $1 AND user_id = $2",+ notification_id,+ user.to_string()+ )+ .fetch_one(&pool)+ .await+ .unwrap();++ assert!(row.seen_at.is_some());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../fixtures",+ scripts("notifications_with_collapse_keys")+ )+)]+async fn test_mark_notifications_seen_does_not_affect_other_users(pool: Pool<Postgres>) {+ let user = test_user("[email protected]");+ let other_user = test_user("[email protected]");+ let notification_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();++ // Insert a user_notification for the other user+ sqlx::query!(+ "INSERT INTO user_notification (user_id, notification_id, created_at) VALUES ($1, $2, '2025-01-01 00:00:00')",+ other_user.to_string(),+ notification_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ // Mark seen only for the first user+ pool.mark_notifications_seen(&user, &[notification_id])+ .await+ .unwrap();++ // Other user's notification should still be unseen+ let row = sqlx::query!(+ "SELECT seen_at FROM user_notification WHERE notification_id = $1 AND user_id = $2",+ notification_id,+ other_user.to_string()+ )+ .fetch_one(&pool)+ .await+ .unwrap();++ assert!(row.seen_at.is_none());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../fixtures",+ scripts("notifications_with_collapse_keys")+ )+)]+async fn test_get_basic_notifications(pool: Pool<Postgres>) {+ let with_key = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();+ let without_key = uuid::Uuid::parse_str("0193b1ea-b642-7589-893b-2b4a509c1e76").unwrap();++ let result = pool+ .get_basic_notifications(&[with_key, without_key])+ .await+ .unwrap();++ // Only the notification with a collapse key should be returned+ assert_eq!(result.len(), 1);+ assert_eq!(result[0].id, with_key);+ assert_eq!(result[0].apns_collapse_key, "collapse-key-1");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_get_basic_notifications_empty(pool: Pool<Postgres>) {+ let id = uuid::Uuid::new_v4();++ let result = pool.get_basic_notifications(&[id]).await.unwrap();++ assert!(result.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("user_notifications"))+)]+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, ()))+ .await+ .unwrap();++ assert_eq!(result.len(), 1);+ let row = &result[0];+ assert_eq!(+ row.owner_id,+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+ );+ assert_eq!(+ row.notification_id,+ uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap()+ );+ assert_eq!(row.entity.entity_type, EntityType::Document);+ assert!(!row.sent);+ assert!(!row.done);+ assert_eq!(row.notification_metadata.message, "hello");+}++#[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, ()))+ .await+ .unwrap();++ assert!(result.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_create_notification_returns_none_on_conflict(pool: Pool<Postgres>) {+ let recipient = test_user("[email protected]");+ let notification_id = uuid::Uuid::new_v4();++ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Document.with_entity_str("doc-1"),+ notification: TestNotification {+ message: "hello".to_string(),+ },+ sender_id: None,+ recipient_ids: std::collections::HashSet::from([recipient.clone()]),+ };++ // First creation should succeed+ let result = pool+ .create_notification(&request, notification_id, "test_service", None)+ .await+ .unwrap();+ assert_eq!(result, Some(notification_id));++ // Second creation with same ID should return None+ let result = pool+ .create_notification(&request, notification_id, "test_service", None)+ .await+ .unwrap();+ assert_eq!(result, None);++ // Verify only one notification exists+ let count: i64 = sqlx::query_scalar!(+ "SELECT COUNT(*) FROM notification WHERE id = $1",+ notification_id+ )+ .fetch_one(&pool)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(count, 1);++ // Verify only one user_notification exists (not duplicated)+ let user_count: i64 = sqlx::query_scalar!(+ "SELECT COUNT(*) FROM user_notification WHERE notification_id = $1",+ notification_id+ )+ .fetch_one(&pool)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(user_count, 1);+}diff --git a/rust/cloud-storage/notification/src/outbound/websocket.rs b/rust/cloud-storage/notification/src/outbound/websocket.rsindex 8541200e16..f1ffe8ce03 100644--- a/rust/cloud-storage/notification/src/outbound/websocket.rs+++ b/rust/cloud-storage/notification/src/outbound/websocket.rs@@ -143,7 +143,9 @@ impl WebSocketGatewayOps for ConnectionGatewayClient {}}-impl<W: WebSocketGatewayOps + Send + Sync> WebSocketSender for WebSocketGatewayAdapter<W> {+impl<W: WebSocketGatewayOps + Send + Sync + 'static> WebSocketSender+ for WebSocketGatewayAdapter<W>+{async fn send_notifications<'a, T: Serialize + Send + Sync>(&self,message_type: &str,diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json b/rust/cloud-storage/notification_db_client/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.jsonnew file mode 100644index 0000000000..e4a18ac5f0--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET done = $3\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82.json b/rust/cloud-storage/notification_db_client/.sqlx/query-351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82.jsonindex 769aafa63a..02b672ba8c 100644--- a/rust/cloud-storage/notification_db_client/.sqlx/query-351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82.json+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82.json@@ -89,7 +89,7 @@null,null,null,- true,+ false,false,true]diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884.json b/rust/cloud-storage/notification_db_client/.sqlx/query-3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884.jsonindex 196eb7a8e4..c60700a18d 100644--- a/rust/cloud-storage/notification_db_client/.sqlx/query-3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884.json+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884.json@@ -86,7 +86,7 @@null,null,null,- true,+ false,false,true]diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-534f8f00f4fd6f56cc5ff2a04aeafcda74e07ba48b68aca8b9c155596229544c.json b/rust/cloud-storage/notification_db_client/.sqlx/query-534f8f00f4fd6f56cc5ff2a04aeafcda74e07ba48b68aca8b9c155596229544c.jsondeleted file mode 100644index c9c8f3ebf1..0000000000--- a/rust/cloud-storage/notification_db_client/.sqlx/query-534f8f00f4fd6f56cc5ff2a04aeafcda74e07ba48b68aca8b9c155596229544c.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM user_notification un\n USING notification n\n WHERE n.id = un.notification_id\n AND n.event_item_id = $2\n AND un.user_id = $1\n AND un.done = false\n RETURNING un.notification_id;\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "notification_id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "534f8f00f4fd6f56cc5ff2a04aeafcda74e07ba48b68aca8b9c155596229544c"-}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.json b/rust/cloud-storage/notification_db_client/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.jsonnew file mode 100644index 0000000000..d0a749ebd2--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id FROM user_mute_notification\n WHERE user_id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.json b/rust/cloud-storage/notification_db_client/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.jsonnew file mode 100644index 0000000000..34382e8725--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, apns_collapse_key as \"apns_collapse_key!: String\"\n FROM notification\n WHERE id = ANY($1) AND apns_collapse_key IS NOT NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "apns_collapse_key!: String",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json b/rust/cloud-storage/notification_db_client/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.jsonnew file mode 100644index 0000000000..a8e7326c35--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id FROM user_notification_item_unsubscribe\n WHERE item_id = $1 AND user_id = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-77308d5c37fea70e815aaf9c099bde9f6967ea4515333e97c4478bdbbf8a36a0.json b/rust/cloud-storage/notification_db_client/.sqlx/query-77308d5c37fea70e815aaf9c099bde9f6967ea4515333e97c4478bdbbf8a36a0.jsondeleted file mode 100644index fac226869a..0000000000--- a/rust/cloud-storage/notification_db_client/.sqlx/query-77308d5c37fea70e815aaf9c099bde9f6967ea4515333e97c4478bdbbf8a36a0.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE user_notification un\n SET seen_at = NOW()\n FROM notification n\n WHERE n.id = un.notification_id\n AND n.event_item_id = $2\n AND un.user_id = $1\n AND un.seen_at IS NULL\n RETURNING un.notification_id;\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "notification_id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "77308d5c37fea70e815aaf9c099bde9f6967ea4515333e97c4478bdbbf8a36a0"-}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.json b/rust/cloud-storage/notification_db_client/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.jsonnew file mode 100644index 0000000000..a166680895--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.json@@ -0,0 +1,21 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id, apns_collapse_key)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Varchar",+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.json b/rust/cloud-storage/notification_db_client/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.jsonnew file mode 100644index 0000000000..215280eac8--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.json@@ -0,0 +1,97 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($3::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($3, $4))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "notification_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "event_item_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "event_item_type",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "sent",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "done",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "viewed_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "notification_metadata: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 11,+ "name": "notification_event_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 12,+ "name": "sender_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Int8",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ null,+ null,+ null,+ null,+ false,+ false,+ true+ ]+ },+ "hash": "7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.json b/rust/cloud-storage/notification_db_client/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.jsonnew file mode 100644index 0000000000..4cb16ae2df--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO user_notification (notification_id, user_id)\n SELECT $1, user_id\n FROM UNNEST($2::text[]) as user_id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.json b/rust/cloud-storage/notification_db_client/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.jsonnew file mode 100644index 0000000000..eab49b91f7--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET sent = true\n WHERE notification_id = $1 AND user_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290.json b/rust/cloud-storage/notification_db_client/.sqlx/query-8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290.jsonindex 7cccc25c20..e995710bfa 100644--- a/rust/cloud-storage/notification_db_client/.sqlx/query-8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290.json+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290.json@@ -88,7 +88,7 @@null,null,null,- true,+ false,false,true]diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json b/rust/cloud-storage/notification_db_client/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.jsonnew file mode 100644index 0000000000..ad14cfedba--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json@@ -0,0 +1,44 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT user_id, device_endpoint, device_type as \"device_type: DbDeviceType\"\n FROM notification_user_device_registration\n WHERE user_id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "device_endpoint",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "device_type: DbDeviceType",+ "type_info": {+ "Custom": {+ "name": "notification_device_type_option",+ "kind": {+ "Enum": [+ "ios",+ "android"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1"+}diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json b/rust/cloud-storage/notification_db_client/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.jsonnew file mode 100644index 0000000000..7626c0a06b--- /dev/null+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE user_notification\n SET seen_at = NOW()\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139"+}diff --git a/rust/cloud-storage/notification_db_client/Cargo.toml b/rust/cloud-storage/notification_db_client/Cargo.tomlindex 370bd853b9..8b16957a89 100644--- a/rust/cloud-storage/notification_db_client/Cargo.toml+++ b/rust/cloud-storage/notification_db_client/Cargo.toml@@ -20,3 +20,4 @@ uuid = { workspace = true }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }+serde_json = { workspace = true }diff --git a/rust/cloud-storage/notification_db_client/fixtures/basic_notification.sql b/rust/cloud-storage/notification_db_client/fixtures/basic_notification.sqlindex f5e5fe0261..41a632b9c1 100644--- a/rust/cloud-storage/notification_db_client/fixtures/basic_notification.sql+++ b/rust/cloud-storage/notification_db_client/fixtures/basic_notification.sql@@ -16,7 +16,7 @@ VALUES'item-123','document','test-service',- NULL,+ '{}','macro|[email protected]',NULL);diff --git a/rust/cloud-storage/notification_db_client/fixtures/should_email.sql b/rust/cloud-storage/notification_db_client/fixtures/should_email.sqlindex 56f9f30829..fd1a6990be 100644--- a/rust/cloud-storage/notification_db_client/fixtures/should_email.sql+++ b/rust/cloud-storage/notification_db_client/fixtures/should_email.sql@@ -14,7 +14,7 @@ VALUES'item_id','item_type','test',- NULL+ '{}');INSERT INTO@@ -33,7 +33,7 @@ VALUES'item_id','item_type','test',- NULL+ '{}');INSERT INTOdiff --git a/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sql b/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sqlindex 4f0aee84c5..e636516190 100644--- a/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sql+++ b/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sql@@ -15,7 +15,7 @@ VALUES'test','document','test',- NULL,+ '{}','macro|[email protected]');@@ -36,7 +36,7 @@ VALUES'test','document','test',- NULL,+ '{}',NULL);@@ -57,7 +57,7 @@ VALUES'test','document','test',- NULL,+ '{}',NULL);@@ -78,7 +78,7 @@ VALUES'test','test','test',- NULL,+ '{}',NULL);diff --git a/rust/cloud-storage/notification_db_client/src/notification/create.rs b/rust/cloud-storage/notification_db_client/src/notification/create.rsindex 8f9bc6d003..17470ef47d 100644--- a/rust/cloud-storage/notification_db_client/src/notification/create.rs+++ b/rust/cloud-storage/notification_db_client/src/notification/create.rs@@ -80,6 +80,7 @@ mod tests {use macro_db_migrator::MACRO_DB_MIGRATIONS;use model_entity::EntityType;use model_notifications::NotificationEventType;+ use serde_json::json;use sqlx::{Pool, Postgres};#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -91,7 +92,7 @@ mod tests {entity: EntityType::Document.with_entity_str("test"),service_sender: "test".to_string(),created_at: None,- metadata: None,+ metadata: Some(json!({})),sender_id: None,};@@ -111,7 +112,7 @@ mod tests {entity: EntityType::Document.with_entity_str("test"),service_sender: "test".to_string(),created_at: None,- metadata: None,+ metadata: Some(json!({})),sender_id: None,};diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rsdeleted file mode 100644index 2a5a5b4724..0000000000--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs+++ /dev/null@@ -1,246 +0,0 @@-use std::str::FromStr;--use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};-use model_entity::EntityType;-use model_notifications::RawUserNotification;-use models_pagination::{CreatedAt, Query};-use sqlx::types::Uuid;--/// Gets all the user notifications in a cursor paginated format.-#[tracing::instrument(skip(db))]-pub async fn get_all_user_notifications(- db: &sqlx::PgPool,- user_id: &str,- limit: u32,- cursor: Query<Uuid, CreatedAt, ()>,-) -> anyhow::Result<Vec<RawUserNotification>> {- let query_limit = limit as i64;- let (cursor_id, cursor_timestamp) = cursor.vals();-- let notifications = sqlx::query!(- r#"- SELECT- un.user_id as owner_id,- un.notification_id,- n.event_item_id,- n.event_item_type,- un.sent,- un.done,- un.created_at::timestamptz,- un.seen_at::timestamptz as viewed_at,- un.created_at::timestamptz as updated_at,- un.deleted_at::timestamptz,- n.metadata as notification_metadata,- n.notification_event_type as notification_event_type,- n.sender_id as sender_id- FROM user_notification un- JOIN notification n ON n.id = un.notification_id- WHERE un.user_id = $1- AND un.deleted_at IS NULL- AND un.done = false- AND (($3::timestamptz IS NULL)- OR (un.created_at, un.notification_id) < ($3, $4))- ORDER BY un.created_at DESC, un.notification_id DESC- LIMIT $2- "#,- user_id,- query_limit,- cursor_timestamp,- cursor_id as _, // have to cast to Option<Uuid> since notification id is a uuid- )- .try_map(|row| {- Ok(RawUserNotification {- owner_id: row.owner_id,- notification_id: row.notification_id,- notification_event_type: row.notification_event_type,- entity: EntityType::from_str(&row.event_item_type)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .with_entity_string(row.event_item_id),- sent: row.sent,- done: row.done,- created_at: row.created_at,- viewed_at: row.viewed_at,- deleted_at: row.deleted_at,- notification_metadata: row.notification_metadata,- sender_id: row- .sender_id- .map(|s| {- Result::<_, ParseErr>::Ok(MacroUserIdStr::parse_from_str(&s)?.into_owned())- })- .transpose()- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,- updated_at: row.updated_at,- })- })- .fetch_all(db)- .await?;-- Ok(notifications)-}--/// Gets all the user notifications for a given entity id in a cursor paginated format.-/// NOTE: This will include "done" notifications but not deleted ones-#[tracing::instrument(skip(db))]-pub async fn get_all_user_notifications_by_event_item_ids(- db: &sqlx::PgPool,- user_id: &str,- event_item_id: &[impl ToString + std::fmt::Debug],- limit: u32,- cursor: Query<Uuid, CreatedAt, ()>,-) -> anyhow::Result<Vec<RawUserNotification>> {- let query_limit = limit as i64;- let (cursor_id, cursor_timestamp) = cursor.vals();-- let event_item_id: Vec<String> = event_item_id.iter().map(|e| e.to_string()).collect();-- let notifications = sqlx::query!(- r#"- SELECT- un.user_id as owner_id,- un.notification_id,- n.event_item_id,- n.event_item_type,- un.sent,- un.done,- un.created_at::timestamptz,- un.seen_at::timestamptz as viewed_at,- un.created_at::timestamptz as updated_at,- un.deleted_at::timestamptz,- n.metadata as notification_metadata,- n.notification_event_type as notification_event_type,- n.sender_id as sender_id- FROM user_notification un- JOIN notification n ON n.id = un.notification_id- WHERE un.user_id = $1- AND n.event_item_id = ANY($2)- AND un.deleted_at IS NULL- AND un.done = false- AND (($4::timestamptz IS NULL)- OR (un.created_at, un.notification_id) < ($4, $5))- ORDER BY un.created_at DESC, un.notification_id DESC- LIMIT $3- "#,- user_id,- &event_item_id,- query_limit,- cursor_timestamp,- cursor_id as _, // have to cast to Option<Uuid> since notification id is a uuid- )- .try_map(|row| {- Ok(RawUserNotification {- owner_id: row.owner_id,- notification_id: row.notification_id,- notification_event_type: row.notification_event_type,- entity: EntityType::from_str(&row.event_item_type)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .with_entity_string(row.event_item_id),- sent: row.sent,- done: row.done,- created_at: row.created_at,- viewed_at: row.viewed_at,- deleted_at: row.deleted_at,- notification_metadata: row.notification_metadata,- sender_id: row- .sender_id- .map(|s| {- Result::<_, ParseErr>::Ok(MacroUserIdStr::parse_from_str(&s)?.into_owned())- })- .transpose()- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,- updated_at: row.updated_at,- })- })- .fetch_all(db)- .await?;-- Ok(notifications)-}--#[cfg(test)]-mod tests {- use super::*;- use chrono::DateTime;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use models_pagination::{Base64Str, Cursor, CursorVal, PaginateOn, TypeEraseCursor};- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("user_notifications"))- )]- async fn test_get_user_notifications(pool: Pool<Postgres>) -> anyhow::Result<()> {- let paginated_result =- get_all_user_notifications(&pool, "macro|[email protected]", 1, Query::Sort(CreatedAt, ()))- .await?;-- assert_eq!(paginated_result.len(), 1);- let paginated = paginated_result- .into_iter()- .paginate_on(1, CreatedAt)- .into_page()- .type_erase();- assert_eq!(- paginated.next_cursor.unwrap(),- Base64Str::encode_json(Cursor {- id: paginated.items.first().unwrap().notification_id,- limit: 1,- filter: (),- val: CursorVal {- sort_type: CreatedAt,- last_val: paginated- .items- .last()- .unwrap()- .created_at- .unwrap_or(DateTime::UNIX_EPOCH),- }- })- .type_erase()- );-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("user_notifications"))- )]- async fn test_get_user_notifications_by_event_item_ids(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- let paginated_result = get_all_user_notifications_by_event_item_ids(- &pool,- "macro|[email protected]",- &["test"],- 1,- Query::Sort(CreatedAt, ()),- )- .await?- .into_iter()- .paginate_on(1, CreatedAt)- .into_page()- .type_erase();-- assert_eq!(paginated_result.items.len(), 1);- assert_eq!(- paginated_result.next_cursor.unwrap(),- Base64Str::encode_json(Cursor {- id: paginated_result.items.last().unwrap().notification_id,- limit: 1,- filter: (),- val: CursorVal {- sort_type: CreatedAt,- last_val: paginated_result- .items- .last()- .unwrap()- .created_at- .unwrap_or(DateTime::UNIX_EPOCH),- },- })- .type_erase()- );-- Ok(())- }-}diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_by_id.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_by_id.rsdeleted file mode 100644index a2d3802be4..0000000000--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_by_id.rs+++ /dev/null@@ -1,150 +0,0 @@-use std::str::FromStr;--use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};-use model_entity::EntityType;-use model_notifications::RawUserNotification;-use sqlx::types::Uuid;--/// Gets a single user notification by its notification id.-#[tracing::instrument(skip(db))]-pub async fn get_user_notification_by_id(- db: &sqlx::PgPool,- user_id: &str,- notification_id: Uuid,-) -> anyhow::Result<Option<RawUserNotification>> {- let row = sqlx::query!(- r#"- SELECT- un.user_id as owner_id,- un.notification_id,- n.event_item_id,- n.event_item_type,- un.sent,- un.done,- un.created_at::timestamptz,- un.seen_at::timestamptz as viewed_at,- un.created_at::timestamptz as updated_at,- un.deleted_at::timestamptz,- n.metadata as notification_metadata,- n.notification_event_type as notification_event_type,- n.sender_id as sender_id- FROM user_notification un- JOIN notification n ON n.id = un.notification_id- WHERE un.user_id = $1- AND un.notification_id = $2- AND un.deleted_at IS NULL- LIMIT 1- "#,- user_id,- notification_id,- )- .fetch_optional(db)- .await?;-- let notification = row- .map(|row| -> Result<RawUserNotification, sqlx::Error> {- Ok(RawUserNotification {- owner_id: row.owner_id,- notification_id: row.notification_id,- notification_event_type: row.notification_event_type,- entity: EntityType::from_str(&row.event_item_type)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .with_entity_string(row.event_item_id),- sent: row.sent,- done: row.done,- created_at: row.created_at,- viewed_at: row.viewed_at,- deleted_at: row.deleted_at,- notification_metadata: row.notification_metadata,- sender_id: row- .sender_id- .map(|s| {- Result::<_, ParseErr>::Ok(MacroUserIdStr::parse_from_str(&s)?.into_owned())- })- .transpose()- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,- updated_at: row.updated_at,- })- })- .transpose()?;-- Ok(notification)-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("user_notifications"))- )]- async fn test_get_user_notification_by_id_found(pool: Pool<Postgres>) -> anyhow::Result<()> {- let notification_id = "0193b1ea-a542-7589-893b-2b4a509c1e76".parse::<Uuid>()?;-- let notification =- get_user_notification_by_id(&pool, "macro|[email protected]", notification_id)- .await?- .expect("expected notification to exist");-- assert_eq!(notification.owner_id, "macro|[email protected]");- assert_eq!(notification.notification_id, notification_id);- assert_eq!(notification.notification_event_type, "test");- assert_eq!(notification.entity.entity_type, EntityType::Document);- assert_eq!(notification.entity.entity_id.as_ref(), "test");- assert!(!notification.sent);- assert!(!notification.done);- assert!(notification.sender_id.is_some());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("user_notifications"))- )]- async fn test_get_user_notification_by_id_wrong_user(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- let notification_id = "0193b1ea-a542-7589-893b-2b4a509c1e76".parse::<Uuid>()?;-- let notification =- get_user_notification_by_id(&pool, "macro|[email protected]", notification_id).await?;-- assert!(notification.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("user_notifications"))- )]- async fn test_get_user_notification_by_id_ignores_deleted(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- let notification_id = "0193b1ea-a542-7589-893b-2b4a509c1e76".parse::<Uuid>()?;-- sqlx::query!(- r#"- UPDATE user_notification- SET deleted_at = NOW()- WHERE user_id = $1- AND notification_id = $2- "#,- "macro|[email protected]",- notification_id,- )- .execute(&pool)- .await?;-- let notification =- get_user_notification_by_id(&pool, "macro|[email protected]", notification_id).await?;-- assert!(notification.is_none());-- Ok(())- }-}diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rsindex 53d5bd1525..ca12a1c4c6 100644--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs+++ b/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs@@ -1,4 +1,2 @@-pub mod get_all;-pub mod get_by_id;pub mod should_email;pub mod unsent;diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.tomlindex 1ad3e8e638..4e7da3a584 100644--- a/rust/cloud-storage/notification_service/Cargo.toml+++ b/rust/cloud-storage/notification_service/Cargo.toml@@ -18,43 +18,27 @@ name = "notification_service_openapi"path = "src/openapi.rs"[features]-connection_gateway = ["notification_worker"]-default = [- "connection_gateway",- "notification_worker",- "push_notification",- "push_notification_event_handler",- "send_email_notifications",-]+default = ["push_notification_event_handler"]local_queue = []-notification_worker = []-push_notification = ["notification_worker"]push_notification_event_handler = []-send_email_notifications = ["notification_worker"][dependencies]anyhow = { workspace = true }-authentication_service_client = { path = "../authentication_service_client" }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sesv2 = { workspace = true }aws-sdk-sns = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true }chrono = { workspace = true }-connection_gateway = { path = "../connection_gateway" }-document_cognition_service_client = { path = "../document_cognition_service_client" }-document_storage_service_client = { path = "../document_storage_service_client" }email_validator = { path = "../email_validator" }futures = { workspace = true }http-body-util = { workspace = true }macro_auth = { path = "../macro_auth" }-macro_cache_client = { path = "../macro_cache_client", default-features = false, features = [- "notification_rate_limit",-] }-macro_cors = { path = "../macro_cors" }macro_aws_config = { path = "../macro_aws_config" }+macro_cors = { path = "../macro_cors" }macro_entrypoint = { path = "../macro_entrypoint" }macro_env = { path = "../macro_env", features = ["frontend_url"] }+macro_env_var = { path = "../macro_env_var" }macro_middleware = { path = "../macro_middleware", default-features = false, features = ["auth",] }@@ -63,11 +47,16 @@ macro_uuid = { path = "../macro_uuid" }mention_utils = { path = "../mention_utils" }model = { path = "../model" }model-entity = { path = "../model-entity" }+model-error-response = { path = "../model-error-response" }model_file_type = { path = "../model_file_type" }model_notifications = { path = "../model_notifications" }+model_user = { path = "../model_user", features = ["axum"] }models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination", features = ["axum"] }+notification = { path = "../notification", features = ["axum"] }notification_db_client = { path = "../notification_db_client" }+paste = "1"+redis = { workspace = true }regex = { workspace = true }secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }@@ -79,9 +68,7 @@ sqs_worker = { path = "../sqs_worker" }thiserror = { workspace = true }tokio = { workspace = true }tower = { workspace = true }-tower-http = { workspace = true, features = [- "compression-gzip",-] }+tower-http = { workspace = true, features = ["compression-gzip"] }tracing = { workspace = true }url = { workspace = true }utoipa = { workspace = true }@@ -90,7 +77,6 @@ uuid = { workspace = true }[dev-dependencies]macro_auth = { path = "../macro_auth", features = ["testing"] }-macro_notify = { path = "../macro_notify" }[package.metadata.cargo-machete]-ignored = ["comms_service", "connection_gateway"]+ignored = ["comms_service"]diff --git a/rust/cloud-storage/notification_service/src/api/mod.rs b/rust/cloud-storage/notification_service/src/api/mod.rsindex 88577800e6..93f22a51e6 100644--- a/rust/cloud-storage/notification_service/src/api/mod.rs+++ b/rust/cloud-storage/notification_service/src/api/mod.rs@@ -1,4 +1,5 @@use crate::api::context::ApiContext;+use ::notification::inbound::http::NotificationRouterState;use anyhow::Context;use axum::Router;use macro_middleware::auth::internal_access::ValidInternalKey;@@ -16,14 +17,17 @@ mod device;mod health;mod notification;mod unsubscribe;-mod user_notification;+pub(crate) mod user_notification;pub(crate) mod swagger;-pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {+pub async fn setup_and_serve<S: ::notification::domain::service::NotificationIngress>(+ state: ApiContext,+ ingress_state: NotificationRouterState<S>,+) -> anyhow::Result<()> {let port = state.config.port;let env = state.config.environment;- let app = api_router(state.clone())+ let app = api_router(state.clone(), ingress_state).with_state(state).merge(health::router()).layer(@@ -54,41 +58,29 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {.context("error starting service")}-fn api_router(state: ApiContext) -> Router<ApiContext> {+fn api_router<S: ::notification::domain::service::NotificationIngress>(+ state: ApiContext,+ ingress_state: NotificationRouterState<S>,+) -> Router<ApiContext> {+ let middleware = {+ ServiceBuilder::new()+ .layer(axum::middleware::from_fn_with_state(+ state.jwt_args.clone(),+ macro_middleware::auth::decode_jwt::handler,+ ))+ .layer(axum::middleware::from_fn(+ macro_middleware::connection_drop_prevention_handler,+ ))+ };+let internal_router = Router::new()- .nest(- "/device",- device::router().layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn_with_state(- state.jwt_args.clone(),- macro_middleware::auth::decode_jwt::handler,- ))- .layer(axum::middleware::from_fn(- macro_middleware::connection_drop_prevention_handler,- )),- ),- )+ .nest("/device", device::router()).nest("/user_notifications",- user_notification::router().layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn_with_state(- state.jwt_args.clone(),- macro_middleware::auth::decode_jwt::handler,- ))- .layer(axum::middleware::from_fn(- macro_middleware::connection_drop_prevention_handler,- )),- ),- )- .nest(- "/unsubscribe",- unsubscribe::router().layer(axum::middleware::from_fn_with_state(- state.jwt_args.clone(),- macro_middleware::auth::decode_jwt::handler,- )),+ user_notification::router(ingress_state),)+ .nest("/unsubscribe", unsubscribe::router())+ .layer(middleware).nest("/notifications",notification::router().layer(diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rsindex 9d2702389f..e8dce0b6df 100644--- a/rust/cloud-storage/notification_service/src/api/swagger.rs+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs@@ -1,3 +1,5 @@+extern crate notification as notification_crate;+use crate::notification::send::push::PushNotificationData;use model::{response::{EmptyResponse, ErrorResponse},@@ -15,12 +17,9 @@ use crate::{api::{device, health, notification,unsubscribe::{self, unsubscribe_item::UnsubscribeItemPathParams},- user_notification::{self, get_user_notification::GetAllUserNotificationsResponse},- },- model::{- device::DeviceRequest, notification::CreateNotification,- user_notification::NotificationBulkRequest,+ user_notification,},+ model::{device::DeviceRequest, notification::CreateNotification},};#[derive(OpenApi)]@@ -40,15 +39,15 @@ use crate::{notification::create_notification::handler,/// /user_notifications- user_notification::get_user_notification::handler,- user_notification::get_user_notification_by_id::handler,- user_notification::delete_user_notification::handler,- user_notification::bulk_delete_user_notification::handler,- user_notification::bulk_mark_user_notification_seen::handler,- user_notification::bulk_mark_user_notification_done::handler,- user_notification::get_user_notifications_by_event_item_id::handler,- user_notification::bulk_get_user_notifications_by_event_item_id::handler,- user_notification::bulk_mark_user_notification_undone::handler,+ user_notification::list_typed_notifications,+ user_notification::bulk_get_typed_notifications_by_event_item_ids,+ user_notification::get_typed_by_event_item_id,+ user_notification::get_typed_notification_by_id,+ notification_crate::inbound::http::delete_notification,+ notification_crate::inbound::http::bulk_delete_notifications,+ notification_crate::inbound::http::bulk_mark_seen,+ notification_crate::inbound::http::bulk_mark_done,+ notification_crate::inbound::http::bulk_mark_undone,/// /unsubscribeunsubscribe::get_unsubscribes::handler,@@ -66,8 +65,6 @@ use crate::{Notification,CreateNotification,UserNotification,- GetAllUserNotificationsResponse,- NotificationBulkRequest,UnsubscribeItemPathParams,UserUnsubscribe,DeviceType,@@ -87,6 +84,12 @@ use crate::{ChannelMentionMetadata,ChannelReplyMetadata,DocumentMentionMetadata,++ // v2 typed notifications+ user_notification::NotifEvent,+ user_notification::ApiUserNotification,+ user_notification::GetAllUserNotificationsResponse,+ notification_crate::inbound::http::BulkGetByEventItemIdsRequest,),),tags(diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rsnew file mode 100644index 0000000000..2d6d7b7030--- /dev/null+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs@@ -0,0 +1,463 @@+use ::notification::domain::models::UserNotificationRow;+use chrono::{DateTime, Utc, serde::ts_seconds_option};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;+use model_error_response::ErrorResponse;+use model_notifications::{+ ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,+ ChannelReplyMetadata, DocumentMentionMetadata, InviteToTeamMetadata, NewEmailMetadata,+ TaskAssignedMetadata,+};+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++#[cfg(test)]+mod test;++/// Defines a notification event enum with compile-time safety guarantees.+///+/// The `tag` field in the database row is the `Notification::TYPE_NAME` of the+/// metadata that was stored. When we deserialize that row back into this enum,+/// serde matches the `tag` value against the `snake_case` of the variant name.+/// If those two strings ever diverge, deserialization fails at runtime.+/// This macro prevents that by asserting the invariant at compile time.+///+/// Accepts a standard enum definition and emits it unchanged, then generates+/// `const` assertions that verify two properties for every `Variant(MetadataType)`:+///+/// 1. `MetadataType` implements [`Notification`](::notification::domain::models::Notification).+/// 2. `MetadataType::TYPE_NAME` equals the variant name converted to `snake_case`+/// (via [`paste`]), which is also the serde tag produced by `rename_all = "snake_case"`.+///+/// Because the enum and the assertions share the same variant list, adding a new+/// variant without a matching `Notification` impl — or with a mismatched+/// `TYPE_NAME` — is a compile error.+macro_rules! define_notif_event {+ (+ $(#[$enum_meta:meta])*+ $vis:vis enum $Name:ident {+ $(+ $(#[$variant_meta:meta])*+ $Variant:ident($(#[$field_meta:meta])* $Ty:ty),+ )++ }+ ) => {+ $(#[$enum_meta])*+ $vis enum $Name {+ $(+ $(#[$variant_meta])*+ $Variant($(#[$field_meta])* $Ty),+ )++ }++ // Compile-time assertions:+ // 1. Every inner type implements Notification.+ // 2. TYPE_NAME matches the snake_case of the variant name.+ paste::paste! {+ const _: () = {+ const fn str_eq(a: &[u8], b: &[u8]) -> bool {+ if a.len() != b.len() { return false; }+ let mut i = 0;+ while i < a.len() {+ if a[i] != b[i] { return false; }+ i += 1;+ }+ true+ }++ $(+ const _: () = assert!(+ str_eq(+ <$Ty as ::notification::domain::models::Notification>::TYPE_NAME.as_bytes(),+ stringify!([< $Variant:snake >]).as_bytes(),+ ),+ concat!(+ stringify!($Name), "::", stringify!($Variant),+ " snake_case does not match Notification::TYPE_NAME for ", stringify!($Ty),+ ),+ );+ )++ };+ }+ };+}++define_notif_event!(+ /// Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`+ /// as the serde adjacently-tagged field names so it can be deserialized from the+ /// shape produced by [`UserNotificationRow::into_tagged`] ++ /// [`UserNotificationRow::into_json`].+ ///+ /// Only includes variants whose metadata types implement the `Notification` trait.+ #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+ #[serde(tag = "tag", content = "content", rename_all = "snake_case")]+ pub enum NotifEvent {+ /// Someone mentioned you in a channel.+ #[schema(value_type = serde_json::Value)]+ ChannelMention(ChannelMentionMetadata),++ /// Someone mentioned you in a document.+ #[schema(value_type = serde_json::Value)]+ DocumentMention(DocumentMentionMetadata),+ /// The user was invited to a channel.+ #[schema(value_type = serde_json::Value)]+ ChannelInvite(ChannelInviteMetadata),++ /// A user sent a message in a channel.+ #[schema(value_type = serde_json::Value)]+ ChannelMessageSend(ChannelMessageSendMetadata),++ /// Someone replied to a thread in a channel that the user is part of.+ #[schema(value_type = serde_json::Value)]+ ChannelMessageReply(ChannelReplyMetadata),++ /// A new email has been sent to the user.+ #[schema(value_type = serde_json::Value)]+ NewEmail(NewEmailMetadata),++ /// A user was invited to a team.+ #[schema(value_type = serde_json::Value)]+ InviteToTeam(InviteToTeamMetadata),++ /// A user was assigned to a task.+ #[schema(value_type = serde_json::Value)]+ TaskAssigned(TaskAssignedMetadata),+ }+);++#[derive(Debug, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ApiUserNotification {+ /// The user who owns this notification.+ #[schema(value_type = String)]+ pub owner_id: MacroUserIdStr<'static>,+ /// The notification ID.+ #[serde(rename = "id")]+ pub notification_id: uuid::Uuid,+ /// The notification event type string (e.g. "channel_mention").+ /// TODO make this a new type+ pub notification_event_type: String,+ /// The entity the notification is about.+ #[serde(flatten)]+ pub entity: Entity<'static>,+ /// Whether the notification has been sent.+ pub sent: bool,+ /// Whether the notification is marked as done.+ pub done: bool,+ /// When the notification was created.+ #[serde(with = "ts_seconds_option")]+ #[schema(value_type = i64, nullable = false)]+ pub created_at: Option<DateTime<Utc>>,+ /// When the notification was viewed/seen.+ #[serde(with = "ts_seconds_option")]+ #[schema(value_type = i64, nullable = true)]+ pub viewed_at: Option<DateTime<Utc>>,+ /// When the notification was last updated.+ #[serde(with = "ts_seconds_option")]+ #[schema(value_type = i64, nullable = true)]+ pub updated_at: Option<DateTime<Utc>>,+ /// When the notification was deleted.+ #[serde(with = "ts_seconds_option")]+ #[schema(value_type = i64, nullable = true)]+ pub deleted_at: Option<DateTime<Utc>>,+ /// Deserialized notification metadata.+ pub notification_metadata: NotifEvent,+ /// The user who triggered the notification.+ #[schema(value_type = Option<String>)]+ pub sender_id: Option<MacroUserIdStr<'static>>,+}++impl ApiUserNotification {+ pub fn from_notification(v: UserNotificationRow<NotifEvent>) -> Self {+ let UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ sender_id,+ } = v;+ ApiUserNotification {+ owner_id,+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ sender_id,+ }+ }+}++/// The strongly typed response for listing user notifications.+#[derive(Debug, Serialize, ToSchema)]+pub struct GetAllUserNotificationsResponse {+ /// The list of items returned.+ pub items: Vec<ApiUserNotification>,+ /// The next page cursor if it exists.+ pub next_cursor: Option<String>,+}++/// Convert a [`UserNotificationRow<serde_json::Value>`] into a+/// [`UserNotificationRow<NotifEvent>`] by tagging and deserializing the metadata.+pub fn to_typed_row(+ row: UserNotificationRow<serde_json::Value>,+) -> Result<UserNotificationRow<NotifEvent>, serde_json::Error> {+ row.into_tagged()+ .into_json()?+ .deserialize_json::<NotifEvent>()+}++/// Build the strongly typed router.+///+/// 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::NotificationIngress,+ O: Clone + Send + Sync + 'static,+>(+ state: ::notification::inbound::http::NotificationRouterState<S>,+) -> axum::Router<O> {+ ::notification::inbound::http::router::<S, serde_json::Value>()+ .route("/", axum::routing::get(list_typed_notifications::<S>))+ .route(+ "/item/bulk",+ axum::routing::post(bulk_get_typed_notifications_by_event_item_ids::<S>),+ )+ .route(+ "/item/:event_item_id",+ axum::routing::get(get_typed_by_event_item_id::<S>),+ )+ .route(+ "/:notification_id",+ 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`,+/// then converts each row to [`UserNotificationRow<NotifEvent>`].+///+/// Rows that fail to deserialize are dropped with a warning log.+#[utoipa::path(+ get,+ operation_id = "list_typed_notifications",+ path = "/v1/user_notifications",+ params(+ ("limit" = Option<u32>, Query, description = "Size limit per page."),+ ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),+ ),+ responses(+ (status = 200, body = GetAllUserNotificationsResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+async fn list_typed_notifications<S: ::notification::domain::service::NotificationIngress>(+ state: axum::extract::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, ()>,+) -> Result<+ axum::Json<GetAllUserNotificationsResponse>,+ (+ axum::http::StatusCode,+ axum::Json<model_error_response::ErrorResponse<'static>>,+ ),+> {+ let axum::Json(response) = ::notification::inbound::http::list_user_notifications::<+ S,+ serde_json::Value,+ >(state, macro_user, query, cursor)+ .await?;++ let items = 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();++ Ok(axum::Json(GetAllUserNotificationsResponse {+ items,+ next_cursor: response.next_cursor,+ }))+}++/// Wrapper handler that calls the inner generic bulk-get handler with `serde_json::Value`,+/// then converts each row to [`UserNotificationRow<NotifEvent>`].+///+/// Rows that fail to deserialize are dropped with a warning log.+#[utoipa::path(+ post,+ operation_id = "bulk_get_typed_notifications_by_event_item_ids",+ path = "/v1/user_notifications/item/bulk",+ params(+ ("limit" = Option<u32>, Query, description = "Size limit per page. Default 20, max 500."),+ ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),+ ),+ request_body = ::notification::inbound::http::BulkGetByEventItemIdsRequest,+ responses(+ (status = 200, body = GetAllUserNotificationsResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+async fn bulk_get_typed_notifications_by_event_item_ids<+ S: ::notification::domain::service::NotificationIngress,+>(+ state: axum::extract::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, ()>,+ body: axum::Json<::notification::inbound::http::BulkGetByEventItemIdsRequest>,+) -> Result<+ axum::Json<GetAllUserNotificationsResponse>,+ (+ axum::http::StatusCode,+ axum::Json<model_error_response::ErrorResponse<'static>>,+ ),+> {+ let axum::Json(response) = ::notification::inbound::http::bulk_get_by_event_item_ids::<+ S,+ serde_json::Value,+ >(state, macro_user, query, cursor, body)+ .await?;++ let items = 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();++ Ok(axum::Json(GetAllUserNotificationsResponse {+ items,+ next_cursor: response.next_cursor,+ }))+}++/// Typed wrapper for getting notifications by a single event item ID.+#[utoipa::path(+ get,+ operation_id = "get_typed_notifications_by_event_item_id",+ path = "/v1/user_notifications/item/{event_item_id}",+ params(+ ("event_item_id" = uuid::Uuid, Path, description = "The event item ID"),+ ("limit" = Option<u32>, Query, description = "Size limit per page."),+ ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),+ ),+ responses(+ (status = 200, body = GetAllUserNotificationsResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+async fn get_typed_by_event_item_id<S: ::notification::domain::service::NotificationIngress>(+ state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,+ macro_user: model_user::axum_extractor::MacroUserExtractor,+ path: axum::extract::Path<::notification::inbound::http::EventItemIdPath>,+ query: axum::extract::Query<::notification::inbound::http::Params>,+ cursor: models_pagination::CursorExtractor<uuid::Uuid, models_pagination::CreatedAt, ()>,+) -> Result<+ axum::Json<GetAllUserNotificationsResponse>,+ (+ axum::http::StatusCode,+ axum::Json<model_error_response::ErrorResponse<'static>>,+ ),+> {+ let axum::Json(response) = ::notification::inbound::http::get_by_event_item_id::<+ S,+ serde_json::Value,+ >(state, macro_user, path, query, cursor)+ .await?;++ let items = 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();++ Ok(axum::Json(GetAllUserNotificationsResponse {+ items,+ next_cursor: response.next_cursor,+ }))+}++/// Typed wrapper for getting a single notification by ID.+#[utoipa::path(+ get,+ operation_id = "get_typed_notification_by_id",+ path = "/v1/user_notifications/{notification_id}",+ params(+ ("notification_id" = uuid::Uuid, Path, description = "ID of the notification"),+ ),+ responses(+ (status = 200, body = ApiUserNotification),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+async fn get_typed_notification_by_id<S: ::notification::domain::service::NotificationIngress>(+ state: axum::extract::State<::notification::inbound::http::NotificationRouterState<S>>,+ macro_user: model_user::axum_extractor::MacroUserExtractor,+ path: axum::extract::Path<::notification::inbound::http::NotificationIdPath>,+) -> Result<+ axum::Json<ApiUserNotification>,+ (+ axum::http::StatusCode,+ axum::Json<model_error_response::ErrorResponse<'static>>,+ ),+> {+ let axum::Json(row) = ::notification::inbound::http::get_notification_by_id::<+ S,+ serde_json::Value,+ >(state, macro_user, path)+ .await?;++ let typed = to_typed_row(row).map_err(|e| {+ tracing::error!(error=?e, "failed to deserialize notification row");+ (+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,+ axum::Json(model_error_response::ErrorResponse {+ message: "failed to convert notification",+ }),+ )+ })?;++ Ok(axum::Json(ApiUserNotification::from_notification(typed)))+}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_delete_user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_delete_user_notification.rsdeleted file mode 100644index 60cb8fd986..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_delete_user_notification.rs+++ /dev/null@@ -1,47 +0,0 @@-use axum::{- Extension, Json,- extract::State,- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::{EmptyResponse, ErrorResponse};--use crate::{api::context::ApiContext, model::user_notification::NotificationBulkRequest};--use model::user::UserContext;--/// Marks the user's notifications as deleted-#[utoipa::path(- delete,- operation_id = "bulk_delete_user_notification",- path = "/user_notifications/bulk",- responses(- (status = 200, body=EmptyResponse),- )- )]-#[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>,- Json(req): Json<NotificationBulkRequest>,-) -> Result<Response, Response> {- let notification_ids = req.notification_ids;- notification_db_client::user_notification::delete::bulk_delete_user_notification(- &ctx.db,- &user_context.user_id,- ¬ification_ids,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to delete user notifications");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to delete user notifications",- }),- )- .into_response()- })?;-- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_get_user_notifications_by_event_item_id.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_get_user_notifications_by_event_item_id.rsdeleted file mode 100644index 281df6fe3b..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_get_user_notifications_by_event_item_id.rs+++ /dev/null@@ -1,101 +0,0 @@-use axum::{- Extension, Json,- extract::{Query, State},- http::StatusCode,-};-use model::response::ErrorResponse;-use model_notifications::UserNotification;-use models_pagination::{- CreatedAt, CursorExtractor, PaginateOn, PaginatedOpaqueCursor, TypeEraseCursor,-};-use sqlx::types::Uuid;--use crate::api::{- context::ApiContext, user_notification::get_user_notification::GetAllUserNotificationsResponse,-};--use model::user::UserContext;--#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct BulkGetUserNotificationsByEventItemIdRequest {- pub event_item_ids: Vec<String>,-}--#[derive(serde::Deserialize)]-pub struct Params {- pub limit: Option<u32>,-}--type BulkResponse = Result<- (StatusCode, Json<PaginatedOpaqueCursor<UserNotification>>),- (StatusCode, Json<ErrorResponse<'static>>),->;--/// Gets the user's notifications for a provided event item ids in a paginated format.-/// This will only return unseen notifications.-#[utoipa::path(- post,- operation_id = "bulk_get_user_notifications_by_event_item_id",- path = "/user_notifications/item/bulk",- params(- ("limit" = u32, Query, description = "Size limit per page. Default 20, max 500."),- ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id, separated by |."),- ),- request_body=BulkGetUserNotificationsByEventItemIdRequest,- responses(- (status = 200, body=GetAllUserNotificationsResponse),- (status = 400, body=ErrorResponse),- (status = 401, 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>,- Query(Params { limit }): Query<Params>,- cursor: CursorExtractor<Uuid, CreatedAt, ()>,- Json(req): Json<BulkGetUserNotificationsByEventItemIdRequest>,-) -> BulkResponse {- tracing::info!("bulk_get_user_notifications_by_event_item_id");-- let limit = limit.unwrap_or(20).min(500);-- let result =- notification_db_client::user_notification::get::get_all::get_all_user_notifications_by_event_item_ids(- &ctx.db,- &user_context.user_id,- &req.event_item_ids,- limit,- cursor.into_query(CreatedAt, ())- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get user notifications");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to get user notifications",- }),- )- })?- .into_iter()- .map(UserNotification::try_from)- .collect::<Result<Vec<_>, _>>()- .map_err(|e| {- tracing::error!(error=?e, "failed to convert notification");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to convert notification",- }),- )- })?- .into_iter()- .paginate_on(limit as usize, CreatedAt)- .into_page()- .type_erase();-- Ok((StatusCode::OK, Json(result)))-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_done.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_done.rsdeleted file mode 100644index 5e6f80ed77..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_done.rs+++ /dev/null@@ -1,76 +0,0 @@-use axum::{- Extension, Json,- extract::State,- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::{EmptyResponse, ErrorResponse};--use crate::{- api::context::ApiContext, model::user_notification::NotificationBulkRequest, notification,-};-use model::user::UserContext;--/// Marks the user's notifications as done-#[utoipa::path(- patch,- operation_id = "bulk_mark_user_notification_done",- path = "/user_notifications/bulk/done",- responses(- (status = 200, body=EmptyResponse),- )- )]-#[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>,- Json(req): Json<NotificationBulkRequest>,-) -> Result<Response, Response> {- tracing::info!("bulk_mark_user_notification_done");-- let notification_ids = req.notification_ids;- notification_db_client::user_notification::patch::done::bulk_patch_done(- &ctx.db,- &user_context.user_id,- ¬ification_ids,- true,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to patch user notifications done");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to patch user notifications done",- }),- )- .into_response()- })?;-- if let Err(e) = notification::send::push::remove::clear_push_notifications(- ctx.clone(),- ¬ification_ids,- &user_context.user_id,- ) {- tracing::error!(error=?e, "failed to remove push notifications");- }-- tokio::spawn({- let db = ctx.db.clone();- let user_id = user_context.user_id.clone();- let notification_ids = notification_ids.clone();- async move {- if let Err(e) = notification_db_client::channel_notification_email_sent::delete::delete_channel_notification_email_sent_by_notification_ids(- &db,- &user_id,- ¬ification_ids,- )- .await- {- tracing::error!(error=?e, "failed to delete channel notification email sent");- }- }- });-- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_seen.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_seen.rsdeleted file mode 100644index 1cf7ca798c..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_seen.rs+++ /dev/null@@ -1,76 +0,0 @@-use axum::{- Extension, Json,- extract::State,- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::{EmptyResponse, ErrorResponse};--use crate::{- api::context::ApiContext, model::user_notification::NotificationBulkRequest, notification,-};--use model::user::UserContext;--/// Marks the user's notifications as seen-#[utoipa::path(- patch,- operation_id = "bulk_mark_user_notification_seen",- path = "/user_notifications/bulk/seen",- responses(- (status = 200, body=EmptyResponse),- )- )]-#[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>,- Json(req): Json<NotificationBulkRequest>,-) -> Result<Response, Response> {- tracing::info!("bulk_mark_user_notification_seen");-- let notification_ids = req.notification_ids;- notification_db_client::user_notification::patch::seen::bulk_patch_seen(- &ctx.db,- &user_context.user_id,- ¬ification_ids,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to patch user notifications seen");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to patch user notifications seen",- }),- )- .into_response()- })?;-- if let Err(e) = notification::send::push::remove::clear_push_notifications(- ctx.clone(),- ¬ification_ids,- &user_context.user_id,- ) {- tracing::error!(error=?e, "failed to remove push notifications");- }-- tokio::spawn({- let db = ctx.db.clone();- let user_id = user_context.user_id.clone();- let notification_ids = notification_ids.clone();- async move {- if let Err(e) = notification_db_client::channel_notification_email_sent::delete::delete_channel_notification_email_sent_by_notification_ids(- &db,- &user_id,- ¬ification_ids,- )- .await- {- tracing::error!(error=?e, "failed to delete channel notification email sent");- }- }- });-- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_undone.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_undone.rsdeleted file mode 100644index 828e8bf89c..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_mark_user_notification_undone.rs+++ /dev/null@@ -1,59 +0,0 @@-use axum::{- Extension, Json,- extract::State,- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::{EmptyResponse, ErrorResponse};--use crate::{api::context::ApiContext, model::user_notification::NotificationBulkRequest};-use model::user::UserContext;--#[derive(Debug, thiserror::Error)]-pub enum BulkMarkUserNotificationUndoneError {- #[error("failed to patch user notifications undone")]- InternalServerError(#[from] anyhow::Error),-}--impl IntoResponse for BulkMarkUserNotificationUndoneError {- fn into_response(self) -> Response {- match self {- BulkMarkUserNotificationUndoneError::InternalServerError(e) => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: &e.to_string(),- }),- )- .into_response(),- }- }-}--/// Marks the user's notifications as undone.-#[utoipa::path(- patch,- operation_id = "bulk_mark_user_notification_undone",- path = "/user_notifications/bulk/undone",- responses(- (status = 200, body=EmptyResponse),- )- )]-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id), err)]-pub async fn handler(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- Json(req): Json<NotificationBulkRequest>,-) -> Result<Json<EmptyResponse>, BulkMarkUserNotificationUndoneError> {- tracing::info!("bulk_mark_user_notification_undone");-- let notification_ids = req.notification_ids;- notification_db_client::user_notification::patch::done::bulk_patch_done(- &ctx.db,- &user_context.user_id,- ¬ification_ids,- false,- )- .await?;-- Ok(Json(EmptyResponse::default()))-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/delete_user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification/delete_user_notification.rsdeleted file mode 100644index 2d632e710f..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/delete_user_notification.rs+++ /dev/null@@ -1,53 +0,0 @@-use axum::{- Extension, Json,- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::{EmptyResponse, ErrorResponse};--use crate::api::context::ApiContext;-use model::user::UserContext;--#[derive(serde::Deserialize)]-pub struct Params {- pub notification_id: String,-}--/// Marks the user's notification as deleted.-#[utoipa::path(- delete,- operation_id = "delete_user_notification",- path = "/user_notifications/{notification_id}",- params(- ("notification_id" = String, Path, description = "ID of the notification")- ),- responses(- (status = 200, body=EmptyResponse),- )- )]-#[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>,- Path(Params { notification_id }): Path<Params>,-) -> Result<Response, Response> {- notification_db_client::user_notification::delete::delete_user_notification(- &ctx.db,- ¬ification_id,- &user_context.user_id,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to delete user notification");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to delete user notification",- }),- )- .into_response()- })?;-- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification.rsdeleted file mode 100644index e4e6155a83..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification.rs+++ /dev/null@@ -1,104 +0,0 @@-use crate::api::context::ApiContext;-use axum::{- Extension, Json,- extract::{Query, State},- http::StatusCode,-};-use model::response::ErrorResponse;-use model::user::UserContext;-use model_notifications::UserNotification;-use models_pagination::{CreatedAt, CursorExtractor, PaginateOn, Paginated, TypeEraseCursor};-use notification_db_client::user_notification::get::get_all::get_all_user_notifications;-use serde::Serialize;-use sqlx::types::Uuid;-use utoipa::ToSchema;--#[derive(serde::Deserialize)]-pub struct Params {- pub limit: Option<u32>,-}--#[derive(Debug, Serialize, ToSchema)]-pub struct GetAllUserNotificationsResponse {- pub items: Vec<UserNotification>,- pub next_cursor: Option<String>,-}--/// Gets the user's unseen notifications in a paginated format.-#[utoipa::path(- get,- operation_id = "get_user_notification",- path = "/user_notifications",- params(- ("limit" = i64, Query, description = "Size limit per page. Default 20, max 500."),- ("cursor" = Option<String>, Query, description = "Base 64 encoded cursor"),- ),- responses(- (status = 200, body=GetAllUserNotificationsResponse),- (status = 400, body=ErrorResponse),- (status = 401, 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>,- Query(Params { limit }): Query<Params>,- cursor: CursorExtractor<Uuid, CreatedAt, ()>,-) -> Result<Json<GetAllUserNotificationsResponse>, (StatusCode, Json<ErrorResponse<'static>>)> {- tracing::info!("get_all_user_notifications");-- let limit = limit.unwrap_or(20).min(500);-- let result = get_all_user_notifications(- &ctx.db,- &user_context.user_id,- limit,- cursor.into_query(CreatedAt, ()),- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get user notifications");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to get user notifications",- }),- )- })?- .into_iter()- .map(UserNotification::try_from)- .collect::<Result<Vec<_>, _>>()- .map_err(|e| {- tracing::error!(error=?e, "failed to convert notification");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to convert notification",- }),- )- })?- .into_iter()- .paginate_on(limit as usize, CreatedAt)- .into_page()- .type_erase();-- // Delete the notification email sent for the user since they are requesting their- // notifications- tokio::spawn(async move {- let _ = notification_db_client::notification_email_sent::delete::delete_notification_email_sent(- &ctx.db,- &user_context.user_id,- )- .await- .inspect_err(|e| {- tracing::error!(error=?e, "failed to delete notification email sent");- });- });-- let Paginated {- items, next_cursor, ..- } = result;- Ok(Json(GetAllUserNotificationsResponse { items, next_cursor }))-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification_by_id.rs b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification_by_id.rsdeleted file mode 100644index 2522437671..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification_by_id.rs+++ /dev/null@@ -1,112 +0,0 @@-use axum::{- Extension, Json,- extract::rejection::PathRejection,- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use model::response::ErrorResponse;-use model::user::UserContext;-use model_notifications::UserNotification;-use uuid::Uuid;--use crate::api::context::ApiContext;--#[derive(Debug, serde::Deserialize)]-pub struct Params {- pub notification_id: Uuid,-}--#[derive(Debug, thiserror::Error)]-pub enum GetNotificationErr {- #[error("invalid notification_id")]- InvalidNotificationId,- #[error("notification not found")]- NotFound,- #[error("failed to get user notification by id")]- Db(#[source] anyhow::Error),- #[error("failed to convert notification")]- Convert(#[source] anyhow::Error),-}--impl IntoResponse for GetNotificationErr {- fn into_response(self) -> Response {- match self {- GetNotificationErr::InvalidNotificationId => (- StatusCode::BAD_REQUEST,- Json(ErrorResponse {- message: "invalid notification_id",- }),- )- .into_response(),- GetNotificationErr::NotFound => (- StatusCode::NOT_FOUND,- Json(ErrorResponse {- message: "notification not found",- }),- )- .into_response(),- GetNotificationErr::Db(_) => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to get user notification by id",- }),- )- .into_response(),- GetNotificationErr::Convert(_) => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to convert notification",- }),- )- .into_response(),- }- }-}--/// Gets a single user notification by id.-#[utoipa::path(- get,- operation_id = "get_user_notification_by_id",- path = "/user_notifications/{notification_id}",- params(- ("notification_id" = String, Path, description = "ID of the notification")- ),- responses(- (status = 200, body=UserNotification),- (status = 400, body=ErrorResponse),- (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), err)]-pub async fn handler(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- path: Result<Path<Params>, PathRejection>,-) -> Result<Json<UserNotification>, GetNotificationErr> {- let Path(Params { notification_id }) =- path.map_err(|_| GetNotificationErr::InvalidNotificationId)?;-- let raw =- notification_db_client::user_notification::get::get_by_id::get_user_notification_by_id(- &ctx.db,- &user_context.user_id,- notification_id,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get user notification by id");- GetNotificationErr::Db(e)- })?;-- let raw = raw.ok_or(GetNotificationErr::NotFound)?;-- let notification = UserNotification::try_from(raw).map_err(|e| {- tracing::error!(error=?e, "failed to convert notification");- GetNotificationErr::Convert(e)- })?;-- Ok(Json(notification))-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notifications_by_event_item_id.rs b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notifications_by_event_item_id.rsdeleted file mode 100644index 1a5b53c310..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notifications_by_event_item_id.rs+++ /dev/null@@ -1,93 +0,0 @@-use crate::api::{- context::ApiContext, user_notification::get_user_notification::GetAllUserNotificationsResponse,-};-use axum::{- Extension, Json,- extract::{Path, Query, State},- http::StatusCode,-};-use model::response::ErrorResponse;-use model::user::UserContext;-use model_notifications::UserNotification;-use models_pagination::{CreatedAt, CursorExtractor, PaginateOn, Paginated, TypeEraseCursor};-use sqlx::types::Uuid;--#[derive(serde::Deserialize)]-pub struct PathParams {- pub event_item_id: String,-}--#[derive(serde::Deserialize)]-pub struct Params {- pub limit: Option<u32>,-}--/// Gets the user's notifications for a given event item id in a paginated format.-#[utoipa::path(- get,- operation_id = "get_user_notifications_by_event_item_id",- path = "/user_notifications/item/{event_item_id}",- params(- ("event_item_id" = String, Path, description = "The event item id"),- ("limit" = i64, Query, description = "Size limit per page. Default 20, max 500."),- ("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id, separated by |."),- ),- responses(- (status = 200, body=GetAllUserNotificationsResponse),- (status = 400, body=ErrorResponse),- (status = 401, 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>,- Path(PathParams { event_item_id }): Path<PathParams>,- Query(Params { limit }): Query<Params>,- cursor: CursorExtractor<Uuid, CreatedAt, ()>,-) -> Result<Json<GetAllUserNotificationsResponse>, (StatusCode, Json<ErrorResponse<'static>>)> {- tracing::info!("get_user_notifications_by_event_item_id");-- let limit = limit.unwrap_or(20).min(500);-- let result =- notification_db_client::user_notification::get::get_all::get_all_user_notifications_by_event_item_ids(- &ctx.db,- &user_context.user_id,- &[&event_item_id],- limit,- cursor.into_query(CreatedAt, ())- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get user notifications");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to get user notifications",- }),- )- })?- .into_iter()- .map(UserNotification::try_from)- .collect::<Result<Vec<_>, _>>()- .map_err(|e| {- tracing::error!(error=?e, "failed to convert notification");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "failed to convert notification",- }),- )- })?- .into_iter()- .paginate_on(limit as usize, CreatedAt)- .into_page()- .type_erase();-- let Paginated {- items, next_cursor, ..- } = result;- Ok(Json(GetAllUserNotificationsResponse { items, next_cursor }))-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/mod.rs b/rust/cloud-storage/notification_service/src/api/user_notification/mod.rsdeleted file mode 100644index a821fe0986..0000000000--- a/rust/cloud-storage/notification_service/src/api/user_notification/mod.rs+++ /dev/null@@ -1,45 +0,0 @@-use crate::api::context::ApiContext;-use axum::{- Router,- routing::{delete, get, patch, post},-};--pub(in crate::api) mod bulk_delete_user_notification;-pub(in crate::api) mod bulk_get_user_notifications_by_event_item_id;-pub(in crate::api) mod bulk_mark_user_notification_done;-pub(in crate::api) mod bulk_mark_user_notification_seen;-pub(in crate::api) mod bulk_mark_user_notification_undone;-pub(in crate::api) mod delete_user_notification;-pub(in crate::api) mod get_user_notification;-pub(in crate::api) mod get_user_notification_by_id;-pub(in crate::api) mod get_user_notifications_by_event_item_id;--pub fn router() -> Router<ApiContext> {- Router::new()- .route("/", get(get_user_notification::handler))- .route(- "/item/bulk",- post(bulk_get_user_notifications_by_event_item_id::handler),- )- .route(- "/item/:event_item_id",- get(get_user_notifications_by_event_item_id::handler),- )- .route(- "/:notification_id",- get(get_user_notification_by_id::handler).delete(delete_user_notification::handler),- )- .route("/bulk", delete(bulk_delete_user_notification::handler))- .route(- "/bulk/seen",- patch(bulk_mark_user_notification_seen::handler),- )- .route(- "/bulk/done",- patch(bulk_mark_user_notification_done::handler),- )- .route(- "/bulk/undone",- patch(bulk_mark_user_notification_undone::handler),- )-}diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/test.rs b/rust/cloud-storage/notification_service/src/api/user_notification/test.rsnew file mode 100644index 0000000000..b8747e7dec--- /dev/null+++ b/rust/cloud-storage/notification_service/src/api/user_notification/test.rs@@ -0,0 +1,194 @@+use super::*;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use notification::domain::models::UserNotificationRow;++/// Build a [`UserNotificationRow<serde_json::Value>`] with the given event type+/// and raw JSON metadata, suitable for passing through [`to_typed_row`].+fn make_row(+ event_type: &str,+ metadata: serde_json::Value,+) -> UserNotificationRow<serde_json::Value> {+ UserNotificationRow {+ owner_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ notification_id: uuid::Uuid::nil(),+ notification_event_type: event_type.to_string(),+ entity: EntityType::Document.with_entity_string("entity-1".to_string()),+ sent: true,+ done: false,+ created_at: None,+ viewed_at: None,+ updated_at: None,+ deleted_at: None,+ notification_metadata: metadata,+ sender_id: Some(+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ ),+ }+}++#[test]+fn to_typed_row_channel_mention() {+ let metadata = serde_json::json!({+ "messageId": "msg-1",+ "messageContent": "hello @user",+ "channelType": "Public",+ "channelName": "general"+ });+ let row = make_row("channel_mention", metadata);+ let typed = to_typed_row(row).expect("should deserialize channel_mention");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::ChannelMention(_)+ ));+}++#[test]+fn to_typed_row_document_mention() {+ let metadata = serde_json::json!({+ "documentName": "doc.pdf",+ "owner": "macro|[email protected]"+ });+ let row = make_row("document_mention", metadata);+ let typed = to_typed_row(row).expect("should deserialize document_mention");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::DocumentMention(_)+ ));+}++#[test]+fn to_typed_row_channel_invite() {+ let metadata = serde_json::json!({+ "invitedBy": "macro|[email protected]",+ "channelType": "Private",+ "channelName": "secret"+ });+ let row = make_row("channel_invite", metadata);+ let typed = to_typed_row(row).expect("should deserialize channel_invite");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::ChannelInvite(_)+ ));+}++#[test]+fn to_typed_row_channel_message_send() {+ let metadata = serde_json::json!({+ "sender": "macro|[email protected]",+ "messageContent": "hi",+ "messageId": "msg-2",+ "channelType": "DirectMessage",+ "channelName": "dm"+ });+ let row = make_row("channel_message_send", metadata);+ let typed = to_typed_row(row).expect("should deserialize channel_message_send");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::ChannelMessageSend(_)+ ));+}++#[test]+fn to_typed_row_channel_message_reply() {+ let metadata = serde_json::json!({+ "threadId": "thread-1",+ "messageId": "msg-3",+ "userId": "macro|[email protected]",+ "messageContent": "reply",+ "channelType": "Public",+ "channelName": "general"+ });+ let row = make_row("channel_message_reply", metadata);+ let typed = to_typed_row(row).expect("should deserialize channel_message_reply");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::ChannelMessageReply(_)+ ));+}++#[test]+fn to_typed_row_new_email() {+ let metadata = serde_json::json!({+ "sender": "[email protected]",+ "toEmail": "[email protected]",+ "threadId": "thread-2",+ "subject": "Hello",+ "snippet": "Hi there"+ });+ let row = make_row("new_email", metadata);+ let typed = to_typed_row(row).expect("should deserialize new_email");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::NewEmail(_)+ ));+}++#[test]+fn to_typed_row_invite_to_team() {+ let metadata = serde_json::json!({+ "teamName": "Engineering",+ "teamId": "team-1",+ "invitedBy": "macro|[email protected]",+ "role": null+ });+ let row = make_row("invite_to_team", metadata);+ let typed = to_typed_row(row).expect("should deserialize invite_to_team");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::InviteToTeam(_)+ ));+}++#[test]+fn to_typed_row_task_assigned() {+ let metadata = serde_json::json!({+ "taskId": "task-1",+ "taskName": "Fix bug",+ "assignedBy": "macro|[email protected]"+ });+ let row = make_row("task_assigned", metadata);+ let typed = to_typed_row(row).expect("should deserialize task_assigned");+ assert!(matches!(+ typed.notification_metadata,+ NotifEvent::TaskAssigned(_)+ ));+}++#[test]+fn to_typed_row_unknown_event_type_fails() {+ let metadata = serde_json::json!({"foo": "bar"});+ let row = make_row("unknown_event", metadata);+ assert!(to_typed_row(row).is_err());+}++#[test]+fn to_typed_row_preserves_row_fields() {+ let metadata = serde_json::json!({+ "taskId": "task-1",+ "taskName": "My Task",+ "assignedBy": "macro|[email protected]"+ });+ let row = make_row("task_assigned", metadata);+ let typed = to_typed_row(row).expect("should deserialize");++ assert_eq!(+ typed.owner_id,+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+ );+ assert_eq!(typed.notification_id, uuid::Uuid::nil());+ assert_eq!(typed.notification_event_type, "task_assigned");+ assert!(typed.sent);+ assert!(!typed.done);++ match typed.notification_metadata {+ NotifEvent::TaskAssigned(ref meta) => {+ assert_eq!(meta.task_id, "task-1");+ assert_eq!(meta.task_name.as_deref(), Some("My Task"));+ }+ _ => panic!("expected TaskAssigned variant"),+ }+}diff --git a/rust/cloud-storage/notification_service/src/config.rs b/rust/cloud-storage/notification_service/src/config.rsindex 23480641b1..2d787e8521 100644--- a/rust/cloud-storage/notification_service/src/config.rs+++ b/rust/cloud-storage/notification_service/src/config.rs@@ -1,19 +1,23 @@use anyhow::Context;use macro_env::Environment;+use macro_env_var::env_var;use std::sync::LazyLock;// We have a check for this env var in the config creation so we can safely unwrap herepub static BASE_URL: LazyLock<String> = LazyLock::new(|| std::env::var("BASE_URL").unwrap());-/// The apple bundle id-pub static APPLE_BUNDLE_ID: LazyLock<String> = LazyLock::new(|| {- std::env::var("APPLE_BUNDLE_ID").unwrap_or_else(|_| "com.macro.app.prod".to_string())-});+env_var!(+ pub(super) struct Vars {+ pub(crate) NotificationQueue,+ pub(crate) ConnectionGatewayUrl,+ pub(crate) RedisUri,+ pub(crate) AppleBundleId+ }+);#[derive(Debug)]pub struct Config {/// The services base url including the scheme.- #[allow(dead_code)]pub base_url: String,/// The connection URL for the Postgres database this application should use.@@ -28,19 +32,11 @@ pub struct Config {/// The environment we are inpub environment: Environment,- /// The notification queue- pub notification_queue: String,/// The notification queue max messages per pollpub notification_queue_max_messages: i32,/// The notification queue wait time secondspub notification_queue_wait_time_seconds: i32,- /// The document cognition service url- pub document_cognition_service_url: String,-- /// The connection gateway url- pub connection_gateway_url: String,-/// The sns ios platform arnpub sns_apns_platform_arn: String,@@ -48,25 +44,11 @@ pub struct Config {pub sns_fcm_platform_arn: String,/// The sender base address- #[allow(dead_code)]// Explicitly allowed as it's used to ensure we have a correct sender base address in the lazy env var abovepub sender_base_address: String,- /// The apple bundle id- #[allow(dead_code)]- pub apple_bundle_id: String,-/// The push notification event handler queuepub push_notification_event_handler_queue: String,-- /// The redis uri for macro cache- pub redis_uri: String,-- /// Auth service secret key, used for internal access- pub auth_service_secret_key: String,-- /// URL for auth service- pub auth_service_url: String,}impl Config {@@ -86,9 +68,6 @@ impl Config {let environment = Environment::new_or_prod();- let notification_queue =- std::env::var("NOTIFICATION_QUEUE").context("NOTIFICATION_QUEUE must be provided")?;-let notification_queue_max_messages: i32 = std::env::var("NOTIFICATION_QUEUE_MAX_MESSAGES").unwrap_or("9".to_string()).parse::<i32>()@@ -100,12 +79,6 @@ impl Config {.parse::<i32>().unwrap();- let document_cognition_service_url = std::env::var("DOCUMENT_COGNITION_SERVICE_URL")- .context("DOCUMENT_COGNITION_SERVICE_URL must be provided")?;-- let connection_gateway_url = std::env::var("CONNECTION_GATEWAY_URL")- .context("CONNECTION_GATEWAY_URL must be provided")?;-let sns_apns_platform_arn = std::env::var("SNS_APNS_PLATFORM_ARN").context("SNS_APNS_PLATFORM_ARN must be provided")?;@@ -115,9 +88,6 @@ impl Config {let sender_base_address =std::env::var("SENDER_BASE_ADDRESS").context("SENDER_BASE_ADDRESS must be provided")?;- let apple_bundle_id =- std::env::var("APPLE_BUNDLE_ID").context("APPLE_BUNDLE_ID must be provided")?;-let push_notification_event_handler_queue =std::env::var("PUSH_NOTIFICATION_EVENT_HANDLER_QUEUE").context("PUSH_NOTIFICATION_EVENT_HANDLER_QUEUE must be provided")?;@@ -127,33 +97,18 @@ impl Config {push_notification_event_handler_queue);- let redis_uri = std::env::var("REDIS_URI").context("REDIS_URI must be provided")?;-- let auth_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")- .context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;-- let auth_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")- .context("AUTHENTICATION_SERVICE_URL must be provided")?;-Ok(Config {base_url,database_url,internal_api_secret_key,port,environment,- notification_queue,notification_queue_max_messages,notification_queue_wait_time_seconds,- document_cognition_service_url,- connection_gateway_url,sns_apns_platform_arn,sns_fcm_platform_arn,sender_base_address,- apple_bundle_id,push_notification_event_handler_queue,- redis_uri,- auth_service_secret_key,- auth_service_url,})}}diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rsindex 20fa7bab0f..32c59649a3 100644--- a/rust/cloud-storage/notification_service/src/main.rs+++ b/rust/cloud-storage/notification_service/src/main.rs@@ -1,8 +1,12 @@use crate::api::context::ApiContext;+use ::notification::domain::service::NotificationEgressService;+use ::notification::inbound::worker::NotificationWorker;+use ::notification::outbound::email::EmailAdapter;+use ::notification::outbound::mobile::MobilePushAdapter;+use ::notification::outbound::rate_limit::RedisRateLimitAdapter;+use ::notification::outbound::websocket::{ConnectionGatewayClient, WebSocketGatewayAdapter};use anyhow::Context;use config::Config;-use connection_gateway_client::client::ConnectionGatewayClient;-use document_cognition_service_client::DocumentCognitionServiceClient;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_env::Environment;@@ -13,10 +17,12 @@ use std::sync::Arc;mod api;mod config;+#[allow(dead_code)]mod env;mod model;mod notification;mod push_notification_event;+#[allow(dead_code)]mod templates;#[tokio::main]@@ -57,23 +63,6 @@ pub async fn main() -> anyhow::Result<()> {.get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?).await?;- let _dcs_client = DocumentCognitionServiceClient::new(- internal_secret_key.as_ref().to_string(),- config.document_cognition_service_url.clone(),- );-- let conn_gateway_client = ConnectionGatewayClient::new(- internal_secret_key.as_ref().to_string(),- config.connection_gateway_url.clone(),- );-- let notification_worker = sqs_worker::SQSWorker::new(- aws_sdk_sqs::Client::new(&aws_config),- config.notification_queue.clone(),- config.notification_queue_max_messages,- config.notification_queue_wait_time_seconds,- );-let push_notification_event_handler_worker = sqs_worker::SQSWorker::new(aws_sdk_sqs::Client::new(&aws_config),config.push_notification_event_handler_queue.clone(),@@ -81,48 +70,8 @@ pub async fn main() -> anyhow::Result<()> {config.notification_queue_wait_time_seconds,);- let ses_client = ses_client::Ses::new(- aws_sdk_sesv2::Client::new(&aws_config),- &config.environment.to_string(),- );let sns_client = sns_client::SNS::new(aws_sdk_sns::Client::new(&aws_config));- let macro_cache_client = macro_cache_client::MacroCache::new(config.redis_uri.as_str());-- #[cfg(feature = "notification_worker")]- {- use std::sync::Arc;-- let auth_service_internal_key = match config.environment {- Environment::Local => config.auth_service_secret_key.clone(),- _ => secretsmanager_client- .get_secret_value(config.auth_service_secret_key.clone())- .await- .context("unable to get secret")?- .to_string(),- };-- let auth_service_client = authentication_service_client::AuthServiceClient::new(- auth_service_internal_key,- config.auth_service_url.clone(),- );-- let queue_worker_context = notification::context::QueueWorkerContext {- db: db.clone(),- worker: Arc::new(notification_worker),- conn_gateway_client: Arc::new(conn_gateway_client),- ses_client: Arc::new(ses_client),- sns_client: Arc::new(sns_client.clone()),- macro_cache_client: Arc::new(macro_cache_client),- auth_service_client: Arc::new(auth_service_client),- };-- // Spawn the runner in a task of it's own so we don't block the main thread- tokio::spawn(- async move { notification::run_notification_worker(queue_worker_context).await },- );- }-#[cfg(feature = "push_notification_event_handler")]{let db = db.clone();@@ -143,13 +92,68 @@ pub async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;- api::setup_and_serve(ApiContext {- db,- sns_client: Arc::new(sns_client),- config: Arc::new(config),- jwt_args,- internal_secret_key,- })+ let vars = config::Vars::new()?;+ let notification_repository =+ ::notification::outbound::repository::DbNotificationRepository::new(db.clone());++ let notification_queue = ::notification::outbound::queue::SqsNotificationQueue::new(+ aws_sdk_sqs::Client::new(&aws_config),+ vars.notification_queue.as_ref().to_string(),+ );+ let ingress_service = ::notification::domain::service::NotificationIngressService::new(+ notification_repository,+ notification_queue.clone(),+ );+ let ingress_state =+ ::notification::inbound::http::NotificationRouterState::new(ingress_service);++ // Set up egress worker for delivering notifications from the queue+ let egress_repository =+ ::notification::outbound::repository::DbNotificationRepository::new(db.clone());++ let websocket_adapter = WebSocketGatewayAdapter::new(ConnectionGatewayClient::new(+ internal_secret_key.as_ref().to_string(),+ vars.connection_gateway_url.as_ref().to_string(),+ ));++ let mobile_adapter = MobilePushAdapter::new(+ aws_sdk_sns::Client::new(&aws_config),+ vars.apple_bundle_id.as_ref().to_string(),+ );++ let ses_client = aws_sdk_sesv2::Client::new(&aws_config);+ let email_adapter = EmailAdapter::new(ses_client, config.sender_base_address.clone());++ let redis_client =+ redis::Client::open(vars.redis_uri.as_ref()).expect("failed to create redis client");+ let rate_limit_adapter = RedisRateLimitAdapter::new(redis_client);++ let egress_service = NotificationEgressService::new(+ notification_queue,+ egress_repository,+ websocket_adapter,+ mobile_adapter,+ email_adapter,+ rate_limit_adapter,+ );++ let worker = NotificationWorker::new(egress_service);++ tokio::spawn(async move {+ tracing::info!("starting notification egress worker");+ worker.run().await+ });++ api::setup_and_serve(+ ApiContext {+ db,+ sns_client: Arc::new(sns_client),+ config: Arc::new(config),+ jwt_args,+ internal_secret_key,+ },+ ingress_state,+ ).await?;Ok(())diff --git a/rust/cloud-storage/notification_service/src/model/mod.rs b/rust/cloud-storage/notification_service/src/model/mod.rsindex eee4c41629..b96df937d9 100644--- a/rust/cloud-storage/notification_service/src/model/mod.rs+++ b/rust/cloud-storage/notification_service/src/model/mod.rs@@ -1,3 +1,2 @@pub mod device;pub mod notification;-pub mod user_notification;diff --git a/rust/cloud-storage/notification_service/src/model/user_notification.rs b/rust/cloud-storage/notification_service/src/model/user_notification.rsdeleted file mode 100644index 2a8dca85b8..0000000000--- a/rust/cloud-storage/notification_service/src/model/user_notification.rs+++ /dev/null@@ -1,9 +0,0 @@-use serde::{Deserialize, Serialize};-use utoipa::ToSchema;--#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct NotificationBulkRequest {- /// The ids of the notifications to handle- pub notification_ids: Vec<uuid::Uuid>,-}diff --git a/rust/cloud-storage/notification_service/src/notification/comms_utils.rs b/rust/cloud-storage/notification_service/src/notification/comms_utils.rsdeleted file mode 100644index 8fdd10e38e..0000000000--- a/rust/cloud-storage/notification_service/src/notification/comms_utils.rs+++ /dev/null@@ -1,47 +0,0 @@-use anyhow::Context;-use std::collections::HashSet;--/// Returns a list of user ids that should be emailed.-pub(in crate::notification) async fn should_email_channel_notification(- auth_service_client: &authentication_service_client::AuthServiceClient,- db: &sqlx::Pool<sqlx::Postgres>,- channel_id: &str,- user_ids: &[String],-) -> anyhow::Result<HashSet<String>> {- // We only want to send channel notification emails to **non-macro** users.- let existing_users: HashSet<String> = auth_service_client.get_existing_users(user_ids).await?;-- // Filter out the list of user ids to only include users that are not macro users- let filtered_user_ids: Vec<String> = user_ids- .iter()- .filter_map(|user_id| {- if existing_users.contains(user_id) {- None- } else {- Some(user_id.to_string())- }- })- .collect();-- let channel_notification_email_sent = notification_db_client::channel_notification_email_sent::get::get_channel_notification_email_sent_bulk(- db,- channel_id,- filtered_user_ids.as_slice(),- )- .await.context("unable to get channel notification email sent")?;-- tracing::debug!(channel_notification_email_sent=?channel_notification_email_sent, "got channel notification email sent");-- let mut should_email = HashSet::new();-- // If the user does not have a channel_notificaiton_email_sent record, we should email them.- for user_id in user_ids {- // If the user has not received an email notification for this channel, we should email them.- if !channel_notification_email_sent.contains_key(user_id) {- should_email.insert(user_id.clone());- continue;- }- }-- Ok(should_email)-}diff --git a/rust/cloud-storage/notification_service/src/notification/context.rs b/rust/cloud-storage/notification_service/src/notification/context.rsdeleted file mode 100644index af24a0a9ee..0000000000--- a/rust/cloud-storage/notification_service/src/notification/context.rs+++ /dev/null@@ -1,14 +0,0 @@-use connection_gateway_client::client::ConnectionGatewayClient;-use sqlx::PgPool;-use std::sync::Arc;--#[derive(Clone)]-pub struct QueueWorkerContext {- pub db: PgPool,- pub worker: Arc<sqs_worker::SQSWorker>,- pub conn_gateway_client: Arc<ConnectionGatewayClient>,- pub ses_client: Arc<ses_client::Ses>,- pub sns_client: Arc<sns_client::SNS>,- pub macro_cache_client: Arc<macro_cache_client::MacroCache>,- pub auth_service_client: Arc<authentication_service_client::AuthServiceClient>,-}diff --git a/rust/cloud-storage/notification_service/src/notification/create.rs b/rust/cloud-storage/notification_service/src/notification/create.rsdeleted file mode 100644index df70bcc922..0000000000--- a/rust/cloud-storage/notification_service/src/notification/create.rs+++ /dev/null@@ -1,55 +0,0 @@-use anyhow::Context;-use model_notifications::{Notification, RawNotification};--/// Creates the notification and all user_notifications-/// Returns the notification if the creation is successful-/// Returns None if the notification already exists-/// Returns an error if the creation fails-pub async fn create_notification(- db: &sqlx::Pool<sqlx::Postgres>,- notification: Notification,- user_ids: &[String],-) -> anyhow::Result<Option<Notification>> {- let mut notification_transaction = db- .begin()- .await- .context("unable to begin notification_transaction")?;-- let notification =- match notification_db_client::notification::create::create_notification_transaction(- &mut notification_transaction,- RawNotification::from(notification),- )- .await- {- Ok(notification) => notification,- Err(e) => {- // If the notification already exists, we can assume the message was processed- if e.to_string().contains(- "duplicate key value violates unique constraint \"notification_pkey\"",- ) {- return Ok(None);- }-- anyhow::bail!(e)- }- };-- tracing::trace!(notification=?notification, "created notification");-- // There are no users to notify, we can skip the notification- notification_db_client::user_notification::create::create_bulk_user_notifications(- &mut notification_transaction,- ¬ification.id,- user_ids,- )- .await?;-- tracing::trace!(notification=?notification, "created user notifications");-- notification_transaction.commit().await.inspect_err(|e| {- tracing::error!(error=?e, "failed to commit notification_transaction");- })?;-- Ok(Some(Notification::try_from(notification)?))-}diff --git a/rust/cloud-storage/notification_service/src/notification/mod.rs b/rust/cloud-storage/notification_service/src/notification/mod.rsindex b42fb15f70..25d19fd955 100644--- a/rust/cloud-storage/notification_service/src/notification/mod.rs+++ b/rust/cloud-storage/notification_service/src/notification/mod.rs@@ -1,49 +1,4 @@-use std::time::Duration;--use tokio::time::error::Elapsed;--mod comms_utils;-pub mod context;-mod create;-mod metadata_utils;-mod process;-mod rate_limit;+#[allow(dead_code)]+pub mod metadata_utils;+#[allow(dead_code)]pub mod send;-mod user_data;-mod user_ids;--/// Runs the notification worker in a loop to handle restarting should it fail.-pub async fn run_notification_worker(queue_worker_context: context::QueueWorkerContext) {- use futures::StreamExt;- tracing::info!("notification worker started");- loop {- match queue_worker_context.worker.receive_messages().await {- Ok(messages) => {- if messages.is_empty() {- continue;- }-- futures::stream::iter(messages)- .map(|message| {- let ctx = queue_worker_context.clone();- async move {- let processing_future = process::process_message(ctx, &message);- let _ = with_timeout(Duration::from_secs(30), processing_future).await;- Ok::<(), anyhow::Error>(())- }- })- .buffer_unordered(10)- .collect::<Vec<anyhow::Result<()>>>()- .await;- }- Err(e) => {- tracing::error!(error=?e, "error receiving messages");- }- }- }-}--#[tracing::instrument(err, skip(fut))]-async fn with_timeout<F: Future>(duration: Duration, fut: F) -> Result<F::Output, Elapsed> {- tokio::time::timeout(duration, fut).await-}diff --git a/rust/cloud-storage/notification_service/src/notification/process.rs b/rust/cloud-storage/notification_service/src/notification/process.rsdeleted file mode 100644index d900138602..0000000000--- a/rust/cloud-storage/notification_service/src/notification/process.rs+++ /dev/null@@ -1,307 +0,0 @@-use std::collections::HashSet;--use super::context::QueueWorkerContext;-use crate::notification::create::create_notification;-use crate::notification::user_data::populate_user_data;-use crate::notification::user_ids::utils::filter_sender_id_from_recipient_ids;-use crate::notification::{rate_limit, send};-use anyhow::Context;-use futures::StreamExt;-use macro_user_id::cowlike::CowLike;-use macro_user_id::user_id::MacroUserIdStr;-use model_notifications::{Notification, NotificationEventType, NotificationQueueMessage};--/// Processes a message from the notification queue.-/// If the processing is successful, the message is deleted.-#[tracing::instrument(err, skip(ctx, message), fields(message_id=message.message_id))]-pub(crate) async fn process_message(- ctx: QueueWorkerContext,- message: &aws_sdk_sqs::types::Message,-) -> anyhow::Result<()> {- let original_start_time = std::time::Instant::now();-- let (notification_id, notification_event_type, service_sender) = if let Some(attributes) =- message.message_attributes.as_ref()- {- // Make Notification from message- let notification_id = attributes.get("notification_id").map(|notification_id| {- tracing::trace!(notification_id=?notification_id, "found notification_id in message attributes");- notification_id.string_value().unwrap_or_default()- }).context("notification_id should be a message attribute")?;-- let notification_event_type = attributes.get("notification_event_type").map(|notification_event_type| {- tracing::trace!(notification_event_type=?notification_event_type, "found notification_event_type in message attributes");- notification_event_type.string_value().unwrap_or_default()- }).context("notification_event_type should be a message attribute")?;-- let service_sender = attributes.get("service_sender").map(|service_sender| {- tracing::trace!(service_sender=?service_sender, "found service_sender in message attributes");- service_sender.string_value().unwrap_or_default()- }).context("service_sender should be a message attribute")?;-- (- macro_uuid::string_to_uuid(notification_id),- notification_event_type.to_string(),- service_sender.to_string(),- )- } else {- ctx.worker.cleanup_message(message).await?;- anyhow::bail!("message attributes not found")- };-- let notification_id = notification_id?;-- tracing::info!(- notification_id=?notification_id,- notification_event_type=?notification_event_type,- service_sender=?service_sender,- "message attributes"- );-- let message_body = if let Some(body) = message.body.as_ref() {- tracing::trace!(notification_id=%notification_id, notification_event_type=%notification_event_type, service_sender=%service_sender, body=?body, "found body in message");- serde_json::from_str::<NotificationQueueMessage>(body)?- } else {- ctx.worker.cleanup_message(message).await?;- anyhow::bail!("message body not found")- };-- tracing::info!(message_body=?message_body, "message body");-- let sender_id = message_body.sender_id.as_ref();- let recipient_ids = message_body.recipient_ids.as_ref();-- let notification = Notification {- id: notification_id,- notification_entity: message_body.notification_entity,- service_sender,- sender_id: sender_id.cloned(),- temporal: Default::default(), // Created at is set by the database- notification_event: message_body.notification_event,- };-- // perform basic rate limiting check- if rate_limit::rate_limit(&ctx.macro_cache_client, ¬ification)- .await- .context("unable to rate limit notification")?- {- tracing::info!(- notification_id=%notification_id,- notification_event_type=?notification.notification_event.event_type(),- sender_id=?sender_id,- event_item=?notification.notification_entity,- "rate limited notification"- );- ctx.worker.cleanup_message(message).await?;- return Ok(());- }-- tracing::info!(- notification_id=%notification_id,- notification_event_type=%notification.notification_event.event_type(),- sender_id=?sender_id,- event_item=?notification.notification_entity,- "processing message"- );-- let user_ids =- filter_sender_id_from_recipient_ids(sender_id.map(|r| r.as_ref()), recipient_ids)- .unwrap_or_default();-- // If there are no users to notify, we can skip the notification- if user_ids.is_empty() {- tracing::trace!("no users to notify");- ctx.worker.cleanup_message(message).await?;- return Ok(());- }-- // Filter out all user ids that have this type of notification muted or all notifications muted- let user_ids = filter_user_ids(- &ctx.db,- ¬ification.notification_entity.entity_id,- user_ids,- )- .await?;-- let macro_user_ids: Vec<_> = user_ids- .iter()- .filter_map(|id| {- Some(- MacroUserIdStr::parse_from_str(id.as_ref())- .ok()?- .into_owned(),- )- })- .collect();-- // Handle cleanup- if notification.notification_event.event_type() == NotificationEventType::RejectTeamInvite {- notification_db_client::notification::delete::delete_notification_by_event_item(- &ctx.db,- ¬ification.notification_entity.entity_id,- ¬ification.notification_entity.entity_type.to_string(),- )- .await?;- }-- // Second check to see if user ids is now empty after filtering- // If there are no users to notify, we can skip the notification- if user_ids.is_empty() {- tracing::trace!("no users to notify");- ctx.worker.cleanup_message(message).await?;- return Ok(());- }-- tracing::trace!(user_ids=?user_ids, "got user ids to notify");-- // Create notification/user_notification(s)- let notification = create_notification(&ctx.db, notification, &user_ids).await?;-- // If there is no notification returned, it means the notification already exists- let notification = match notification {- Some(notification) => notification,- None => {- tracing::trace!("notification already exists, deleting message");- ctx.worker.cleanup_message(message).await?;- return Ok(());- }- };-- let notification_id = notification.id;-- let notifications_with_user_data = populate_user_data(notification, ¯o_user_ids);-- let list_user_notifications: Vec<_> = notifications_with_user_data- .values()- .flatten()- .cloned()- .collect();-- let users_sent_connection_gateway = send::connection_gateway::send_connection_gateway(- &ctx.conn_gateway_client,- list_user_notifications.as_slice(),- )- .await- .context("unable to process connection gateway")?;-- tracing::trace!(users_sent_connection_gateway=?users_sent_connection_gateway, "users sent via connection gateway");-- // Get the user ids to attempt sending push notifications to- let users_to_push = macro_user_ids- .iter()- .filter(|user_id| !users_sent_connection_gateway.contains(*user_id))- .collect::<HashSet<_>>();-- tracing::trace!(users_to_push=?users_to_push, "users to push");-- // Send push notifications- let users_sent_push = {- #[cfg(feature = "push_notification")]- {- send::push::process::process_push_notifications(- ctx.db.clone(),- ctx.sns_client.clone(),- ¬ifications_with_user_data,- )- .await?- }- #[cfg(not(feature = "push_notification"))]- {- tracing::info!("bypassing push notifications");- HashSet::new()- }- };-- let users_to_email = users_to_push- .iter()- .filter_map(|user_id| {- if !users_sent_connection_gateway.contains(*user_id) {- Some(*user_id)- } else {- None- }- })- .collect::<HashSet<_>>();- tracing::trace!(users_to_email=?users_to_email, "users to email");-- tracing::trace!(users_sent_push=?users_sent_push, "users sent push notification");-- let users_sent_notification = users_sent_connection_gateway- .union(&users_sent_push)- .map(|x| x.as_ref().to_string())- .collect::<Vec<_>>();-- tracing::trace!("updating notifications sent status");- if let Err(e) = notification_db_client::user_notification::patch::sent::bulk_patch_sent(- &ctx.db,- notification_id,- &users_sent_notification,- )- .await- {- tracing::error!(error=?e, "failed to update notifications sent status");- }-- #[cfg(feature = "send_email_notifications")]- {- // TODO: update email processing logic to handle NotificationsWithUserData instead of calling concurrently- // Process email notifications concurrently for each notification- let email_results: Vec<anyhow::Result<()>> =- futures::stream::iter(notifications_with_user_data.values().flatten())- .then(|notification| {- let ctx_clone = ctx.clone();- async move {- send::email::process_email_notifications(&ctx_clone, notification)- .await- .context("unable to process email notification")- }- })- .collect()- .await;-- for (idx, result) in email_results.iter().enumerate() {- if let Err(e) = result {- tracing::error!(- error=?e,- notification_idx=idx,- "failed to process email notification"- );- }- }-- if email_results.iter().any(|r| r.is_err()) {- anyhow::bail!("one or more email notifications failed to process");- }- }- // Remove the message from the queue.- ctx.worker.cleanup_message(message).await?;-- tracing::trace!(time_elapsed=?original_start_time.elapsed(), "message processed");- Ok(())-}--/// Filters the user ids to only include users that are not unsubscribed from the given item/event-async fn filter_user_ids(- db: &sqlx::Pool<sqlx::Postgres>,- item_id: &str,- user_ids: Vec<String>,-) -> anyhow::Result<Vec<String>> {- let mut unsubscribed_users =- notification_db_client::user_mute_notification::get_user_mute_notification_bulk(- db,- user_ids.as_slice(),- )- .await- .context("unable to get user mute notifications")?;-- unsubscribed_users.extend(- notification_db_client::unsubscribe::item::get_unsubscribed_item_users(db, item_id)- .await- .context("unable to get unsubscribed item users")?,- );-- Ok(user_ids- .into_iter()- .filter(|user_id| !unsubscribed_users.contains(user_id))- .collect())-}diff --git a/rust/cloud-storage/notification_service/src/notification/rate_limit.rs b/rust/cloud-storage/notification_service/src/notification/rate_limit.rsdeleted file mode 100644index 284501396b..0000000000--- a/rust/cloud-storage/notification_service/src/notification/rate_limit.rs+++ /dev/null@@ -1,76 +0,0 @@-use anyhow::Context;-use macro_cache_client::MacroCache;-use macro_user_id::email::ReadEmailParts;-use model_notifications::{Notification, NotificationEventType};--/// Performs a basic rate limit check on the notification-/// If this returns false, the notification can proceed-/// If this returns true, the notification should be skipped.-#[tracing::instrument(skip(macro_cache_client, notification), fields(notification_id=?notification.id, notification_event_type=?notification.notification_event.event_type(), event_id=?notification.notification_entity, sender_id=?notification.sender_id))]-pub async fn rate_limit(- macro_cache_client: &MacroCache,- notification: &Notification,-) -> anyhow::Result<bool> {- match notification.notification_event.event_type() {- NotificationEventType::ChannelInvite => {- tracing::trace!("rate limit channel invite");- let sender_id = notification- .sender_id- .as_ref()- .context("expected sender id to be present in channel invite notification")?;-- let email = sender_id.email_part();-- let channel_invite_rate_limit = macro_cache_client- .get_channel_invite_rate_limit(email.email_str())- .await- .context("unable to get channel invite rate limit")?;-- if let Some(channel_invite_rate_limit) = channel_invite_rate_limit- && channel_invite_rate_limit >= 10- {- tracing::error!(email=%email.email_str(), "rate limit channel invite exceeded");- return Ok(true);- }-- tracing::trace!("incrementing channel invite rate limit");- macro_cache_client- .increment_channel_invite_rate_limit(email.email_str(), 3600) // 1 hour- .await- .context("unable to increment channel invite rate limit")?;-- // Return false so we do not silently kill the notification- Ok(false)- }- NotificationEventType::InviteToTeam => {- tracing::trace!("rate limit invite to team");- let sender_id = notification- .sender_id- .as_ref()- .context("expected sender id to be present in invite to team notification")?;-- let email = sender_id.email_part();-- let invite_to_team_rate_limit = macro_cache_client- .get_invite_to_team_rate_limit(email.email_str())- .await- .context("unable to get invite to team rate limit")?;-- if let Some(invite_to_team_rate_limit) = invite_to_team_rate_limit- && invite_to_team_rate_limit >= 5- {- tracing::error!(email=%email.email_str(), "rate limit invite to team exceeded");- return Ok(true);- }-- tracing::trace!("incrementing invite to team rate limit");- macro_cache_client- .increment_invite_to_team_rate_limit(email.email_str(), 3600) // 1 hour- .await- .context("unable to increment invite to team rate limit")?;-- Ok(false)- }- _ => return Ok(false), // No rate limit by default- }-}diff --git a/rust/cloud-storage/notification_service/src/notification/send/connection_gateway.rs b/rust/cloud-storage/notification_service/src/notification/send/connection_gateway.rsdeleted file mode 100644index e9c9e19cf1..0000000000--- a/rust/cloud-storage/notification_service/src/notification/send/connection_gateway.rs+++ /dev/null@@ -1,74 +0,0 @@-use connection_gateway_client::model::sender::MessageReceipt;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use model_notifications::NotificationWithRecipient;-use std::collections::HashSet;--/// Sends the notification to all users via connection gateway-/// Returns a list of users who received the notification successfully-pub async fn send_connection_gateway(- conn_gateway_client: &connection_gateway_client::client::ConnectionGatewayClient,- notifications: &[NotificationWithRecipient],-) -> anyhow::Result<HashSet<MacroUserIdStr<'static>>> {- let start_time = std::time::Instant::now();- let batch_send_results: Vec<MessageReceipt> = {- #[cfg(not(feature = "connection_gateway"))]- {- tracing::info!("bypassing connection gateway");- user_ids- .iter()- .map(|user_id| connection_gateway_client::MessageReceipt {- user_id: user_id.to_string(),- delivery_count: 0,- active: false,- })- .collect()- }- #[cfg(feature = "connection_gateway")]- {- use anyhow::Context;- let messages = notifications- .iter()- .filter_map(|notif| {- use connection_gateway_client::model::message::UniqueMessage;- use model_entity::EntityType;-- let message_content = serde_json::to_value(notif)- .context("unable to serialize notification")- .ok()?;-- Some(UniqueMessage {- message_content,- message_type: "notification".to_string(),- entity: EntityType::User.with_entity_string(notif.recipient_id.to_string()),- })- })- .collect();- conn_gateway_client- .batch_send_unique_messages(messages)- .await- .map_err(|e| {- tracing::error!(error=?e, "batch_send_message failed to send notifications");- anyhow::anyhow!("unable to send notification to connection gateway")- })?- }- };- tracing::debug!(time_elapsed=?start_time.elapsed(), batch_send_results=?batch_send_results, "batch_send_message results");-- // Users that were sent the notification via connection gateway- // A user is considered sent if they have received a delivery count > 0 and they are shown as- // active.- let users_sent_connection_gateway = batch_send_results- .iter()- .filter_map(|r| {- if r.delivery_count != 0 && r.active {- MacroUserIdStr::parse_from_str(&r.user_id)- .ok()- .map(CowLike::into_owned)- } else {- None- }- })- .collect::<HashSet<_>>();-- Ok(users_sent_connection_gateway)-}diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs b/rust/cloud-storage/notification_service/src/notification/send/email/filter.rsdeleted file mode 100644index c8dc3b46f3..0000000000--- a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs+++ /dev/null@@ -1,163 +0,0 @@-use std::collections::HashSet;--use anyhow::Context;-use authentication_service_client::AuthServiceClient;-use macro_user_id::email::ReadEmailParts;-use model_notifications::{NotificationEventType, NotificationWithRecipient};-use notification_db_client::user_notification::get::should_email::should_email_based_on_user_notification_bulk;--use crate::notification::{comms_utils, context::QueueWorkerContext};--pub async fn filter_emails(- queue_worker_context: &QueueWorkerContext,- notification: &NotificationWithRecipient,- user_ids: &[String],-) -> anyhow::Result<Vec<String>> {- // Filter out users that have already received an email for this event- // This is done to prevent spam- // Contains a list of user ids that should receive an email- let filtered_user_ids: HashSet<String> = should_email(- &queue_worker_context.auth_service_client,- &queue_worker_context.db,- notification,- user_ids,- )- .await- .context("unable to get should email")?;-- tracing::debug!(filtered_user_ids=?filtered_user_ids, filter_method="should_email", "filtered user ids");-- let emails: Vec<String> = filtered_user_ids- .iter()- .map(|user_id| user_id.replace("macro|", ""))- .collect::<Vec<String>>();- tracing::debug!(emails=?emails, "got emails to send emails to");-- // Filter only valid emails- let emails: Vec<String> = emails- .into_iter()- .filter(|email| email_validator::is_valid_email(email))- .collect();- tracing::debug!(emails=?emails, "filtered valid emails");-- // Get unsubscribed status for emails- let email_unsubscribed =- notification_db_client::unsubscribe::email::is_email_unsubscribed_batch(- &queue_worker_context.db,- &emails,- )- .await- .context("unable to check if emails are unsubscribed")?;- tracing::debug!(email_unsubscribed=?email_unsubscribed, "got email unsubscribed");-- // Get a list of all matching emails that are subscribed- let email: Vec<String> = email_unsubscribed- .iter()- .filter_map(|(email, is_unsubscribed)| {- if *is_unsubscribed {- None- } else {- Some(email.clone())- }- })- .collect();- tracing::debug!(emails=?emails, "filtered unsubscribed emails");-- let emails = filter_by_rate_limit(queue_worker_context, notification, &email).await?;- tracing::debug!(emails=?emails, "filtered by rate limit");-- Ok(emails)-}--/// Given the notification and list of user ids to potentially send an email to, this will return-/// a map of each user id and whether or not they should receive an email.-async fn should_email(- auth_service_client: &AuthServiceClient,- db: &sqlx::Pool<sqlx::Postgres>,- notification: &NotificationWithRecipient,- user_ids: &[String],-) -> anyhow::Result<HashSet<String>> {- match notification.inner.notification_event.event_type() {- NotificationEventType::ItemSharedUser => {- let result = should_email_based_on_user_notification_bulk(- db,- ¬ification.inner.notification_event.event_type(),- ¬ification.inner.notification_entity.entity_id,- ¬ification- .inner- .notification_entity- .entity_type- .to_string(),- user_ids,- )- .await?;-- let result: HashSet<String> = result- .into_iter()- .filter_map(|(user_id, should_email)| {- if should_email {- Some(user_id.to_string())- } else {- None- }- })- .collect();-- Ok(result)- }- NotificationEventType::ChannelInvite => comms_utils::should_email_channel_notification(- auth_service_client,- db,- ¬ification.inner.notification_entity.entity_id,- user_ids,- )- .await- .context("unable to get should email channel notification"),- _ => anyhow::bail!("unsupported notification event type"),- }-}--/// Filters out emails by rate limit-/// We only allow 1 email per user per hour from another user-async fn filter_by_rate_limit(- queue_worker_context: &QueueWorkerContext,- notification: &NotificationWithRecipient,- emails: &[String],-) -> anyhow::Result<Vec<String>> {- match notification.inner.notification_event.event_type() {- NotificationEventType::ChannelInvite => {- let sender_id = notification- .inner- .sender_id- .as_ref()- .context("unable to get sender id")?;-- let invited_by_email = sender_id.email_part();-- let channel_invited_rate_limit = queue_worker_context- .macro_cache_client- .get_channel_invited_rate_limit_bulk(emails, invited_by_email.email_str())- .await- .context("unable to get channel invited rate limit")?;-- let valid_emails = emails- .iter()- .filter_map(|email| {- if let Some(email_rate_limit) = channel_invited_rate_limit.get(email) {- if let Some(rate_limit) = email_rate_limit- && *rate_limit >= 1- {- return None;- }- Some(email.to_string())- } else {- None- }- })- .collect();-- Ok(valid_emails)- }- _ => Ok(emails.to_vec()), // default to no filtering by rate limit- }-}diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs b/rust/cloud-storage/notification_service/src/notification/send/email/mod.rsindex 6ce2be94d7..612b5b95f1 100644--- a/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs@@ -1,127 +1 @@-mod filter;-mod template;--use anyhow::Context;-use filter::filter_emails;-use futures::StreamExt;-use macro_env::Environment;-use macro_user_id::email::ReadEmailParts;-use model_notifications::{NotificationEventType, NotificationWithRecipient};--use crate::{env::SENDER_ADDRESS, notification::context::QueueWorkerContext};--/// Given a notification and list of user ids, this will send any necessary emails to the user.-/// This is used for *immediate* notifications, such as when a user is added to a channel.-/// This is not meant to be used for notifications that are polled such as when a user is sent-/// messages.-pub async fn process_email_notifications(- queue_worker_context: &QueueWorkerContext,- notification: &NotificationWithRecipient,-) -> anyhow::Result<()> {- // Only include valid events we want to send emails for- match notification.inner.notification_event.event_type() {- // NotificationEventType::CloudStorageItemSharedUser => {}- NotificationEventType::ChannelInvite => {}- // NotificationEventType::ChannelMessageSend => {}- _ => return Ok(()),- }- tracing::trace!("sending email notifications");-- // For NON-PROD: Only send emails if the sender is a macro employee- match Environment::new_or_prod() {- Environment::Develop | Environment::Local => {- let sender_id = notification.inner.sender_id.clone();-- if sender_id.is_none() {- tracing::info!("not sending notification emails for anonymous users");- return Ok(());- }-- if sender_id.unwrap().email_part().domain_part() != "macro.com" {- tracing::info!(- "not sending notification emails for non-macro users in non-prod environment"- );- return Ok(());- }- }- Environment::Production => (),- }-- let sender_address = &*SENDER_ADDRESS;-- let emails = filter_emails(- queue_worker_context,- notification,- &[notification.recipient_id.as_ref().to_string()],- )- .await?;-- if emails.is_empty() {- tracing::info!("no valid emails to send emails to");- return Ok(());- }-- let channel_invite_sent_user_ids = emails- .iter()- .map(|e| format!("macro|{}", e))- .collect::<Vec<String>>();-- // For channel invites we want to make sure we set the email sent status for the channel ASAP- if notification.inner.notification_event.event_type() == NotificationEventType::ChannelInvite {- tracing::trace!("upserting channel notification email sent");- let sender_email = notification- .inner- .sender_id- .as_ref()- .map(|s| s.email_part().email_str().to_string())- .context("sender id should exist")?;-- notification_db_client::channel_notification_email_sent::upsert::upsert_channel_notification_email_sent_bulk(- &queue_worker_context.db,- ¬ification.inner.notification_entity.entity_id,- &channel_invite_sent_user_ids,- )- .await.context("unable to upsert channel notification email sent")?;-- queue_worker_context- .macro_cache_client- .increment_channel_invited_rate_limit_bulk(- &emails,- &sender_email,- 3600, // 1 hour- )- .await- .context("unable to increment channel invited rate limit")?;- }-- let (email_content, subject) =- crate::notification::send::email::template::fill_email_template(notification)- .context("unable to fill email template")?;-- tracing::info!(num_email=%emails.len(), emails=?emails, "notification_service_email_send");-- let result = futures::stream::iter(emails.iter())- .then(|email| {- let ses_client = queue_worker_context.ses_client.clone();- let email_content = email_content.clone();- let subject = subject.clone();- async move {- tracing::debug!(email=?email, "sending email");-- ses_client- .send_email(sender_address, email, &subject, &email_content)- .await- .context("unable to send email")?;-- Ok(())- }- })- .collect::<Vec<anyhow::Result<()>>>()- .await;-- result.iter().filter(|r| r.is_err()).for_each(|r| {- tracing::error!(error=?r, "unable to send email");- });-- Ok(())-}+pub mod template;diff --git a/rust/cloud-storage/notification_service/src/notification/send/mod.rs b/rust/cloud-storage/notification_service/src/notification/send/mod.rsindex 1d99f74dca..6263162d0e 100644--- a/rust/cloud-storage/notification_service/src/notification/send/mod.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/mod.rs@@ -1,3 +1,2 @@-pub mod connection_gateway;pub mod email;pub mod push;diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rsdeleted file mode 100644index 5ef1234633..0000000000--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs+++ /dev/null@@ -1,369 +0,0 @@-use crate::notification::send::push::PushNotificationData;-use macro_user_id::email::ReadEmailParts;-use macro_user_id::user_id::MacroUserIdStr;-use mention_utils::parse::{ParsedXmlText, XmlFormatter};-use model::document::{FileType, FileTypeExt};-use model_notifications::NotificationWithRecipient;-use model_notifications::{- ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,- ChannelReplyMetadata, DocumentMentionMetadata, TaskAssignedMetadata,-};-use sns_client::{APNSPushNotification, Aps};-use std::str::FromStr;-use thiserror::Error;--#[derive(Debug, Error)]-pub enum NotificationErr {- #[error("The sender_id field was None for a notification which must have a sender")]- SenderDoesntExist,- #[error("File type did not exist for a notification expecting a file type")]- FileTypeDoesntExist,- #[error(transparent)]- InvalidFileType(#[from] model_file_type::ValueError<FileType>),- #[error(transparent)]- UserId(#[from] macro_user_id::error::ParseErr),- #[error(transparent)]- XmlErr(#[from] mention_utils::parse::ParseErr),-}--pub struct PlainTextFormatter;--impl XmlFormatter for PlainTextFormatter {- fn format_plain_text(s: &str, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(f, "{}", s)- }-- fn format_link(- link: &mention_utils::parse::ParsedLink<'_>,- f: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- write!(f, "{}", link.text)- }-- fn format_doc(- doc: &mention_utils::parse::ParsedDocumentMention<'_>,- f: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- write!(f, "{}", doc.document_name)- }-- fn format_user(- user: &mention_utils::parse::ParsedUserMention<'_>,- f: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- write!(f, "{}", user.user_id.0.email_part().email_str())- }-- fn format_contact(- contact: &mention_utils::parse::ParsedContactMention<'_>,- f: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- write!(f, "{}", contact.name)- }-- fn format_date(- date: &mention_utils::parse::ParsedDateMention<'_>,- f: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- write!(f, "{}", date.display_format)- }-- fn format_group(- group: &mention_utils::parse::ParsedGroupMention<'_>,- f: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- write!(f, "@{}", group.group_alias)- }-}--#[tracing::instrument(err)]-pub fn generate_apns_notification<T: XmlFormatter>(- notif: &NotificationWithRecipient,-) -> Result<Option<APNSPushNotification<PushNotificationData>>, NotificationErr> {- let create_push_data = |route: Route| PushNotificationData {- notification_id: notif.inner.id,- notification_entity: notif.inner.notification_entity.clone(),- sender_id: notif.inner.sender_id.as_ref().map(|x| x.to_string()),- open_route: route.0,- };-- let parse_user = || -> Result<MacroUserIdStr<'_>, NotificationErr> {- notif- .inner- .sender_id- .clone()- .ok_or(NotificationErr::SenderDoesntExist)- };-- Ok(match ¬if.inner.notification_event {- model_notifications::NotificationEvent::ItemSharedUser(_) => None,- model_notifications::NotificationEvent::ItemSharedOrganization(_) => None,- model_notifications::NotificationEvent::ChannelMention(channel_mention_metadata) => Some(- channel_mention_metadata- .build_apns_notification::<T>(parse_user()?)?- .map(|()| {- create_push_data(Route(format!(- "/channel/{}?channel_message_id={}{}",- notif.inner.notification_entity.entity_id,- channel_mention_metadata.message_id,- format_args!(- "{}{}",- if channel_mention_metadata.thread_id.is_some() {- "&channel_thread_id="- } else {- ""- },- channel_mention_metadata.thread_id.as_deref().unwrap_or("")- )- )))- }),- ),- model_notifications::NotificationEvent::DocumentMention(document_mention_metadata) => {- let file_type_str = document_mention_metadata- .file_type- .as_ref()- .ok_or(NotificationErr::FileTypeDoesntExist)?;- let file_type = FileType::from_str(file_type_str)?;-- let block_route = match file_type {- x if x.is_image() => "image",- FileType::Pdf => "pdf",- FileType::Docx => "write",- FileType::Md => "md",- _ => "code",- };-- let open_route = format!(- "/{}/{}",- block_route, notif.inner.notification_entity.entity_id- );-- Some(- document_mention_metadata- .build_apns_notification::<T>(parse_user()?)?- .map(|()| create_push_data(Route(open_route))),- )- }- model_notifications::NotificationEvent::ChannelInvite(channel_invite_metadata) => Some(- channel_invite_metadata- .build_apns_notification::<T>(())?- .map(|()| {- create_push_data(Route(format!(- "/channel/{}",- notif.inner.notification_entity.entity_id- )))- }),- ),- model_notifications::NotificationEvent::ChannelMessageSend(- channel_message_send_metadata,- ) => Some(- channel_message_send_metadata- .build_apns_notification::<T>(())?- .map(|()| {- create_push_data(Route(format!(- "/channel/{}?channel_message_id={}",- notif.inner.notification_entity.entity_id,- channel_message_send_metadata.message_id- )))- }),- ),- model_notifications::NotificationEvent::ChannelMessageReply(channel_reply_metadata) => {- Some(- channel_reply_metadata- .build_apns_notification::<T>(parse_user()?)?- .map(|()| {- create_push_data(Route(format!(- "/channel/{}?channel_message_id={}&channel_thread_id={}",- notif.inner.notification_entity.entity_id,- channel_reply_metadata.message_id,- channel_reply_metadata.thread_id- )))- }),- )- }- model_notifications::NotificationEvent::ChannelMessageDocument(- _document_mention_metadata,- ) => None,- model_notifications::NotificationEvent::NewEmail(_new_email_metadata) => None,- model_notifications::NotificationEvent::InviteToTeam(_invite_to_team_metadata) => None,- model_notifications::NotificationEvent::RejectTeamInvite => None,- model_notifications::NotificationEvent::TaskAssigned(task_assigned_metadata) => Some(- task_assigned_metadata- .build_apns_notification::<T>(parse_user()?)?- .map(|()| {- create_push_data(Route(format!("/task/{}", task_assigned_metadata.task_id)))- }),- ),- })-}--trait BuildNotification {- type Ctx<'a>;- fn build_apns_notification<T: XmlFormatter>(- &self,- ctx: Self::Ctx<'_>,- ) -> Result<APNSPushNotification<()>, NotificationErr>;-}--/// the route the notification should navigate to on click-struct Route(String);--impl BuildNotification for ChannelMessageSendMetadata {- type Ctx<'a> = ();- fn build_apns_notification<T: XmlFormatter>(- &self,- _ctx: Self::Ctx<'_>,- ) -> Result<APNSPushNotification<()>, NotificationErr> {- Ok(APNSPushNotification {- aps: Aps {- alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {- title: Some(match self.common.channel_type {- model_notifications::ChannelType::DirectMessage => {- self.sender.email_part().local_part().to_string()- }- _ => format!(- "{} <{}>",- self.sender.email_part().local_part(),- self.common.channel_name- ),- }),- body: Some(T::format_xml_text(ParsedXmlText::parse(&self.message_content)?).0),- ..Default::default()- })),- ..Default::default()- },- push_notification_data: (),- })- }-}--impl BuildNotification for ChannelMentionMetadata {- type Ctx<'a> = MacroUserIdStr<'a>;- fn build_apns_notification<T: XmlFormatter>(- &self,- ctx: Self::Ctx<'_>,- ) -> Result<APNSPushNotification<()>, NotificationErr> {- let title = match self.common.channel_type {- model_notifications::ChannelType::DirectMessage => {- format!("{} mentioned you", ctx.email_part().local_part())- }- _ => format!(- "{} mentioned you in #{}",- ctx.email_part().local_part(),- &self.common.channel_name- ),- };- Ok(APNSPushNotification {- aps: Aps {- alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {- title: Some(title),- body: Some(T::format_xml_text(ParsedXmlText::parse(&self.message_content)?).0),- ..Default::default()- })),- ..Default::default()- },- push_notification_data: (),- })- }-}--impl BuildNotification for DocumentMentionMetadata {- type Ctx<'a> = MacroUserIdStr<'a>;- fn build_apns_notification<T: XmlFormatter>(- &self,- ctx: Self::Ctx<'_>,- ) -> Result<APNSPushNotification<()>, NotificationErr> {- Ok(APNSPushNotification {- aps: Aps {- alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {- title: Some(ctx.0.email_part().email_str().to_string()),- body: Some(format!(- "You were mentioned in {}.{}",- self.document_name,- self.file_type- .as_ref()- .ok_or(NotificationErr::FileTypeDoesntExist)?- )),- ..Default::default()- })),- ..Default::default()- },- push_notification_data: (),- })- }-}--impl BuildNotification for ChannelReplyMetadata {- type Ctx<'a> = MacroUserIdStr<'a>;-- fn build_apns_notification<T: XmlFormatter>(- &self,- ctx: Self::Ctx<'_>,- ) -> Result<APNSPushNotification<()>, NotificationErr> {- Ok(APNSPushNotification {- aps: Aps {- alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {- title: Some(format!("{} Replied", ctx.0.email_part().email_str())),- body: Some(T::format_xml_text(ParsedXmlText::parse(&self.message_content)?).0),- ..Default::default()- })),- ..Default::default()- },- push_notification_data: (),- })- }-}--impl BuildNotification for ChannelInviteMetadata {- type Ctx<'a> = ();-- fn build_apns_notification<T: XmlFormatter>(- &self,- _ctx: Self::Ctx<'_>,- ) -> Result<APNSPushNotification<()>, NotificationErr> {- Ok(APNSPushNotification {- aps: Aps {- alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {- title: Some(format!("{} Invite", self.common.channel_name)),- body: Some(format!(- "{} invited you to join the channel",- self.invited_by- )),- ..Default::default()- })),- ..Default::default()- },- push_notification_data: (),- })- }-}--impl BuildNotification for TaskAssignedMetadata {- type Ctx<'a> = MacroUserIdStr<'a>;-- fn build_apns_notification<T: XmlFormatter>(- &self,- ctx: Self::Ctx<'_>,- ) -> Result<APNSPushNotification<()>, NotificationErr> {- let assigner_email = ctx.email_part().email_str().to_string();- let title = assigner_email;-- let body = if let Some(ref task_name) = self.task_name {- format!("assigned you to {}", task_name)- } else {- "assigned you a task".to_string()- };-- Ok(APNSPushNotification {- aps: Aps {- alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {- title: Some(title),- body: Some(body.to_string()),- ..Default::default()- })),- ..Default::default()- },- push_notification_data: (),- })- }-}diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs b/rust/cloud-storage/notification_service/src/notification/send/push/mod.rsindex 1f9a249fe9..a90d8752d1 100644--- a/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs@@ -2,10 +2,6 @@ use serde::{Deserialize, Serialize};use utoipa::ToSchema;use uuid::Uuid;-pub mod generate;-pub mod process;-pub mod remove;-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]pub struct PushNotificationData {diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/process.rs b/rust/cloud-storage/notification_service/src/notification/send/push/process.rsdeleted file mode 100644index 6e16fae0d1..0000000000--- a/rust/cloud-storage/notification_service/src/notification/send/push/process.rs+++ /dev/null@@ -1,200 +0,0 @@-use crate::{- config::APPLE_BUNDLE_ID,- notification::send::push::{- PushNotificationData,- generate::{PlainTextFormatter, generate_apns_notification},- },-};-use futures::StreamExt;-use macro_user_id::user_id::MacroUserIdStr;-use model_notifications::{- DeviceEndpoint, DeviceType, HashedCollapseKey, NotificationWithRecipient,-};-use notification_db_client::notification::get::{BasicNotifRepoImpl, BasicNotificationRepo};-use sns_client::{MessageAttributes, NotificationSender, SnsTarget};-use std::{- collections::{HashMap, HashSet},- sync::Arc,-};-use tokio::sync::mpsc::error::SendError;-use uuid::Uuid;--#[cfg(test)]-mod tests;--pub type NotificationsForDevices<'a> = HashMap<&'a NotificationWithRecipient, Vec<DeviceEndpoint>>;--async fn stream_push_notifs_to_user<'a>(- worker: PushNotifWorker,- notifs: NotificationsForDevices<'a>,-) {- futures::stream::iter(- notifs- .into_iter()- .flat_map(|(notif, devices)| devices.into_iter().map(move |d| (notif, d))),- )- .for_each_concurrent(10, move |(notif, endpoint)| {- let worker = worker.clone();- async move {- let payload = match endpoint {- DeviceEndpoint::Android(_) => {- tracing::warn!("android not implemented");- return;- }- DeviceEndpoint::Ios(_) => {- match generate_apns_notification::<PlainTextFormatter>(notif).transpose() {- Some(Ok(n)) => SnsTarget::Ios(Box::new(n)),- _ => return,- }- }- };- let collapse_key = notif.inner.build_key().into_hashed();- let _ = worker- .enqueue(PushNotifMsg::Notify(NotifyData {- notification_id: notif.inner.id,- endpoint: endpoint.clone(),- payload,- attrs: sns_client::MessageAttributes {- push_type: sns_client::PushType::Alert,- apns_bundle_id: &APPLE_BUNDLE_ID,- collapse_key: collapse_key.clone().into_inner(),- },- notif_collapse_key: collapse_key,- recipient: notif.recipient_id.clone(),- }))- .await;- }- })- .await;-}--#[derive(Clone)]-struct PushNotifWorker {- inner: tokio::sync::mpsc::Sender<PushNotifMsg>,-}--impl PushNotifWorker {- pub fn new<T: BasicNotificationRepo, U: NotificationSender>(- sns_client: Arc<U>,- repo: T,- ) -> (- Self,- tokio::task::JoinHandle<HashSet<MacroUserIdStr<'static>>>,- ) {- let (tx, mut rx) = tokio::sync::mpsc::channel(100);- let task = tokio::task::spawn(async move {- let mut users_sent_push = HashSet::new();-- while let Some(msg) = rx.recv().await {- match msg {- PushNotifMsg::Notify(NotifyData {- notification_id,- endpoint,- payload,- attrs,- notif_collapse_key,- recipient,- }) => {- let Ok(_) = repo- .update_collapse_key(¬ification_id, notif_collapse_key.as_ref())- .await- else {- continue;- };- let Ok(_) = sns_client- .push_notification(endpoint.arn(), &payload, attrs)- .await- else {- continue;- };- users_sent_push.insert(recipient);- }- }- }- users_sent_push- });-- (PushNotifWorker { inner: tx }, task)- }-- #[tracing::instrument(err, skip(self))]- async fn enqueue(&self, msg: PushNotifMsg) -> Result<(), SendError<PushNotifMsg>> {- self.inner.send(msg).await- }-}--#[derive(Debug)]-enum PushNotifMsg {- Notify(NotifyData),-}--#[derive(Debug)]-struct NotifyData {- notification_id: Uuid,- endpoint: DeviceEndpoint,- payload: SnsTarget<PushNotificationData>,- attrs: MessageAttributes,- notif_collapse_key: HashedCollapseKey,- recipient: MacroUserIdStr<'static>,-}--/// Attempts to send push notifications to provided users-/// Returns a list of users who were sent push notifications.-#[tracing::instrument(skip(db, sns_client))]-pub async fn process_push_notifications(- db: sqlx::Pool<sqlx::Postgres>,- sns_client: Arc<sns_client::SNS>,- notifications: &HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>>,-) -> Result<HashSet<MacroUserIdStr<'static>>, anyhow::Error> {- let user_ids: Vec<_> = notifications.keys().cloned().collect();-- let user_device_endpoints =- notification_db_client::device::get_users_device_endpoints(&db, user_ids.as_slice())- .await?;-- process_push_notifications_inner(- user_device_endpoints,- notifications,- sns_client,- BasicNotifRepoImpl(db),- )- .await-}--async fn process_push_notifications_inner<U: NotificationSender, T: BasicNotificationRepo>(- mut user_device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>>,- notifications: &HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>>,- sns_client: Arc<U>,- notif_repo: T,-) -> Result<HashSet<MacroUserIdStr<'static>>, anyhow::Error> {- let to_send: HashMap<_, _> = notifications- .iter()- .flat_map(|(user_id, notifs)| {- notifs- .iter()- .filter_map(|notif| {- let endpoints = user_device_endpoints.remove(user_id).map(|endpoints| {- endpoints- .into_iter()- .map(|(arn, device)| match device {- model_notifications::DeviceType::Ios => DeviceEndpoint::Ios(arn),- model_notifications::DeviceType::Android => {- DeviceEndpoint::Android(arn)- }- })- .collect::<Vec<_>>()- })?;- Some((notif, endpoints))- })- .collect::<Vec<_>>()- })- .collect();-- let (worker, handle) = PushNotifWorker::new(sns_client, notif_repo);-- stream_push_notifs_to_user(worker, to_send).await;-- let users_sent_push = handle.await.unwrap_or_default();-- Ok(users_sent_push)-}diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/process/tests.rs b/rust/cloud-storage/notification_service/src/notification/send/push/process/tests.rsdeleted file mode 100644index 638158d108..0000000000--- a/rust/cloud-storage/notification_service/src/notification/send/push/process/tests.rs+++ /dev/null@@ -1,384 +0,0 @@-use super::*;-use model_entity::EntityType;-use model_notifications::{- ChannelMessageSendMetadata, ChannelType, CommonChannelMetadata, NotificationEvent,- NotificationTemporalData, NotificationWithRecipient, UserNotification,-};-use notification_db_client::notification::get::DbBasicNotification;-use std::sync::atomic::{AtomicUsize, Ordering};--struct MockNotifRepo {- update_count: AtomicUsize,-}--impl MockNotifRepo {- fn new() -> Self {- Self {- update_count: AtomicUsize::new(0),- }- }-}--impl BasicNotificationRepo for MockNotifRepo {- async fn update_collapse_key(- &self,- _notification_id: &Uuid,- collapse_key: &str,- ) -> anyhow::Result<DbBasicNotification<String>> {- self.update_count.fetch_add(1, Ordering::SeqCst);- Ok(DbBasicNotification {- event_item_id: "test_entity_id".to_string(),- event_item_type: "channel".to_string(),- notification_event_type: "channel_message_send".to_string(),- apns_collapse_key: collapse_key.to_string(),- })- }-- async fn get_basic_notification(- &self,- _notification_id: &Uuid,- ) -> anyhow::Result<DbBasicNotification<Option<String>>> {- Ok(DbBasicNotification {- event_item_id: "test_entity_id".to_string(),- event_item_type: "channel".to_string(),- notification_event_type: "channel_message_send".to_string(),- apns_collapse_key: None,- })- }-}--struct MockSnsClient {- push_count: AtomicUsize,- should_fail: bool,-}--impl MockSnsClient {- fn new() -> Self {- Self {- push_count: AtomicUsize::new(0),- should_fail: false,- }- }-- fn failing() -> Self {- Self {- push_count: AtomicUsize::new(0),- should_fail: true,- }- }-}--impl NotificationSender for MockSnsClient {- async fn push_notification<T>(- &self,- _endpoint_arn: &str,- _message_json: &SnsTarget<T>,- _message_attributes: MessageAttributes,- ) -> anyhow::Result<aws_sdk_sns::operation::publish::PublishOutput>- where- T: serde::Serialize + std::fmt::Debug + Sync,- {- if self.should_fail {- return Err(anyhow::anyhow!("mock sns failure"));- }- self.push_count.fetch_add(1, Ordering::SeqCst);- Ok(aws_sdk_sns::operation::publish::PublishOutput::builder()- .message_id("mock_message_id")- .build())- }-}--fn make_user_id(email: &str) -> MacroUserIdStr<'static> {- MacroUserIdStr::try_from_email(email).expect("valid test email")-}--fn create_test_notification(- id: Uuid,- recipient_email: &str,- message_id: &str,-) -> NotificationWithRecipient {- let sender = make_user_id("[email protected]");- NotificationWithRecipient {- inner: UserNotification {- id,- notification_entity: EntityType::Channel- .with_entity_string("test_channel_id".to_string()),- sent: false,- done: false,- sender_id: Some(sender.clone()),- temporal: NotificationTemporalData::default(),- notification_event: NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {- sender,- message_content: "Hello, world!".to_string(),- message_id: message_id.to_string(),- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "general".to_string(),- },- }),- },- recipient_id: make_user_id(recipient_email),- }-}--#[tokio::test]-async fn test_process_push_notifications_inner_no_devices() {- let user_id = make_user_id("[email protected]");- let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");-- let mut notifications = HashMap::new();- notifications.insert(user_id, vec![notif]);-- // Empty device endpoints - no devices registered- let user_device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>> =- HashMap::new();-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- Arc::new(MockSnsClient::new()),- MockNotifRepo::new(),- )- .await;-- assert!(result.is_ok());- let users_sent = result.unwrap();- // No users should have been sent push notifications since no devices registered- assert!(users_sent.is_empty());-}--#[tokio::test]-async fn test_process_push_notifications_inner_with_ios_device() {- let user_id = make_user_id("[email protected]");- let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");-- let mut notifications = HashMap::new();- notifications.insert(user_id.clone(), vec![notif]);-- let mut user_device_endpoints = HashMap::new();- user_device_endpoints.insert(- user_id.clone(),- vec![(- "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device".to_string(),- DeviceType::Ios,- )],- );-- let sns_client = Arc::new(MockSnsClient::new());- let notif_repo = MockNotifRepo::new();-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- sns_client.clone(),- notif_repo,- )- .await;-- assert!(result.is_ok());- let users_sent = result.unwrap();- assert_eq!(users_sent.len(), 1);- assert!(users_sent.contains(&make_user_id("[email protected]")));-}--#[tokio::test]-async fn test_process_push_notifications_inner_android_not_implemented() {- let user_id = make_user_id("[email protected]");- let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");-- let mut notifications = HashMap::new();- notifications.insert(user_id.clone(), vec![notif]);-- let mut user_device_endpoints = HashMap::new();- user_device_endpoints.insert(- user_id.clone(),- vec![(- "arn:aws:sns:us-east-1:123:endpoint/GCM/app/device".to_string(),- DeviceType::Android,- )],- );-- let sns_client = Arc::new(MockSnsClient::new());-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- sns_client.clone(),- MockNotifRepo::new(),- )- .await;-- assert!(result.is_ok());- let users_sent = result.unwrap();- // Android is not implemented, so no push should be sent- assert!(users_sent.is_empty());-}--#[tokio::test]-async fn test_process_push_notifications_inner_multiple_users() {- let user_1 = make_user_id("[email protected]");- let user_2 = make_user_id("[email protected]");- let notif_1 = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");- let notif_2 = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_2");-- let mut notifications = HashMap::new();- notifications.insert(user_1.clone(), vec![notif_1]);- notifications.insert(user_2.clone(), vec![notif_2]);-- let mut user_device_endpoints = HashMap::new();- user_device_endpoints.insert(- user_1.clone(),- vec![(- "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device1".to_string(),- DeviceType::Ios,- )],- );- user_device_endpoints.insert(- user_2.clone(),- vec![(- "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device2".to_string(),- DeviceType::Ios,- )],- );-- let sns_client = Arc::new(MockSnsClient::new());-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- sns_client.clone(),- MockNotifRepo::new(),- )- .await;-- assert!(result.is_ok());- let users_sent = result.unwrap();- assert_eq!(users_sent.len(), 2);- assert!(users_sent.contains(&user_1));- assert!(users_sent.contains(&user_2));-}--#[tokio::test]-async fn test_process_push_notifications_inner_user_with_multiple_devices() {- let user_id = make_user_id("[email protected]");- let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");-- let mut notifications = HashMap::new();- notifications.insert(user_id.clone(), vec![notif]);-- let mut user_device_endpoints = HashMap::new();- user_device_endpoints.insert(- user_id.clone(),- vec![- (- "arn:aws:sns:us-east-1:123:endpoint/APNS/app/iphone".to_string(),- DeviceType::Ios,- ),- (- "arn:aws:sns:us-east-1:123:endpoint/APNS/app/ipad".to_string(),- DeviceType::Ios,- ),- ],- );-- let sns_client = Arc::new(MockSnsClient::new());-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- sns_client.clone(),- MockNotifRepo::new(),- )- .await;-- assert!(result.is_ok());- let users_sent = result.unwrap();- // User should still only appear once in the result set- assert_eq!(users_sent.len(), 1);- assert!(users_sent.contains(&user_id));-}--#[tokio::test]-async fn test_process_push_notifications_inner_sns_failure_skips_user() {- let user_id = make_user_id("[email protected]");- let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");-- let mut notifications = HashMap::new();- notifications.insert(user_id.clone(), vec![notif]);-- let mut user_device_endpoints = HashMap::new();- user_device_endpoints.insert(- user_id.clone(),- vec![(- "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device".to_string(),- DeviceType::Ios,- )],- );-- let sns_client = Arc::new(MockSnsClient::failing());-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- sns_client,- MockNotifRepo::new(),- )- .await;-- assert!(result.is_ok());- let users_sent = result.unwrap();- // SNS failed, so user should not be in the sent set- assert!(users_sent.is_empty());-}--#[tokio::test]-async fn test_process_push_notifications_inner_empty_notifications() {- let notifications: HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>> =- HashMap::new();- let user_device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>> =- HashMap::new();-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- Arc::new(MockSnsClient::new()),- MockNotifRepo::new(),- )- .await;-- assert!(result.is_ok());- assert!(result.unwrap().is_empty());-}--#[tokio::test]-async fn test_process_push_notifications_inner_notification_without_matching_device() {- let user_1 = make_user_id("[email protected]");- let user_2 = make_user_id("[email protected]");- let notif = create_test_notification(Uuid::new_v4(), "[email protected]", "msg_1");-- let mut notifications = HashMap::new();- notifications.insert(user_1.clone(), vec![notif]);-- // Device endpoints only for user_2, not user_1- let mut user_device_endpoints = HashMap::new();- user_device_endpoints.insert(- user_2.clone(),- vec![(- "arn:aws:sns:us-east-1:123:endpoint/APNS/app/device".to_string(),- DeviceType::Ios,- )],- );-- let result = process_push_notifications_inner(- user_device_endpoints,- ¬ifications,- Arc::new(MockSnsClient::new()),- MockNotifRepo::new(),- )- .await;-- assert!(result.is_ok());- let users_sent = result.unwrap();- // user_1 has notification but no device, user_2 has device but no notification- assert!(users_sent.is_empty());-}diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs b/rust/cloud-storage/notification_service/src/notification/send/push/remove.rsdeleted file mode 100644index cf57193e01..0000000000--- a/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs+++ /dev/null@@ -1,114 +0,0 @@-use crate::{api::context::ApiContext, config::APPLE_BUNDLE_ID};-use anyhow::Context;-use futures::StreamExt;-use notification_db_client::notification::get::DbBasicNotification;-use serde::Serialize;-use sns_client::{APNSPushNotification, MessageAttributes, PushType, SnsTarget};--/// Clears out push notifications for a user in bulk-#[tracing::instrument(skip(ctx))]-pub fn clear_push_notifications(- ctx: ApiContext,- notification_ids: &[uuid::Uuid],- user_id: &str,-) -> anyhow::Result<()> {- tracing::trace!("clearing potential push notifications");- tokio::spawn({- let notification_ids = notification_ids.to_vec();- let user_id = user_id.to_string();- async move {- let db = ctx.db;- let sns_client = ctx.sns_client;- tracing::trace!(notification_ids=?notification_ids, user_id=user_id, "removing push notifications");-- let device_endpoints = notification_db_client::device::get_user_device_endpoints(- &db, &user_id,- )- .await- .inspect_err(|e| {- tracing::error!(error=?e, user_id=user_id, "failed to get device endpoints");- })- .unwrap_or(Vec::new());-- if device_endpoints.is_empty() {- tracing::trace!(- "user has no device endpoints, skipping push notification clearing"- );- return;- }-- let _ = futures::stream::iter(notification_ids.iter())- .then(|notification_id| {- let sns_client = sns_client.clone();- let db = db.clone();- let device_endpoints = device_endpoints.clone();- async move {- let notif =- notification_db_client::notification::get::get_basic_notification(- &db,- notification_id,- )- .await?- .transpose()- .context("Cannot clear a notification without an apns collapse key")?;-- clear_push_notification(&sns_client, &device_endpoints, notif).await- }- })- .collect::<Vec<anyhow::Result<()>>>()- .await;-- tracing::trace!(notification_ids=?notification_ids, user_id=user_id, "removing push notifications complete");- }- });-- Ok(())-}--/// When a notification is marked as "done" or "seen" for a user, we need to potentially send a-/// remove notification sns notification to the user to clear it from their device.-#[tracing::instrument(err, skip(sns_client))]-pub async fn clear_push_notification(- sns_client: &sns_client::SNS,- device_endpoints: &[String],- basic_notification: DbBasicNotification<String>,-) -> anyhow::Result<()> {- // As of right now, we can only do this for APNS notifications since android requires a- // custom push notification handler in order to clear the notification on the mobile application side- let collapse_key = basic_notification.apns_collapse_key;-- #[derive(Debug, Serialize, Clone)]- struct CustomData {- identifier: String,- }-- let apns = SnsTarget::Ios(Box::new(APNSPushNotification {- aps: sns_client::Aps {- content_available: Some(1),- ..Default::default()- },- push_notification_data: CustomData {- identifier: collapse_key.clone(),- },- }));- let attributes = MessageAttributes {- push_type: PushType::Background,- apns_bundle_id: &APPLE_BUNDLE_ID,- collapse_key,- };-- futures::stream::iter(device_endpoints.iter())- .then(|endpoint| async {- if !endpoint.contains("APNS") {- tracing::trace!("skipping non-apns endpoint");- return;- }- let _ = sns_client- .push_notification(endpoint, &apns, attributes.clone())- .await;- })- .collect::<Vec<_>>()- .await;-- Ok(())-}diff --git a/rust/cloud-storage/notification_service/src/notification/user_data.rs b/rust/cloud-storage/notification_service/src/notification/user_data.rsdeleted file mode 100644index 9f1e211a64..0000000000--- a/rust/cloud-storage/notification_service/src/notification/user_data.rs+++ /dev/null@@ -1,28 +0,0 @@-use macro_user_id::user_id::MacroUserIdStr;-use model_notifications::{Notification, NotificationWithRecipient, UserNotification};-use std::collections::HashMap;--// convert the Notification object from a single generic notification to a list of user-specific-// notifications that may have different values depending on the user.-pub fn populate_user_data(- notification: Notification,- user_ids: &[MacroUserIdStr<'static>],-) -> HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>> {- // Determine importance and create new notification object- user_ids- .iter()- .map(|user_id| {- (- user_id.clone(),- vec![NotificationWithRecipient {- inner: UserNotification::from_new_notification(- notification.clone(),- false,- false,- ),- recipient_id: user_id.clone(),- }],- )- })- .collect()-}diff --git a/rust/cloud-storage/notification_service/src/notification/user_ids/mod.rs b/rust/cloud-storage/notification_service/src/notification/user_ids/mod.rsdeleted file mode 100644index b5614dd823..0000000000--- a/rust/cloud-storage/notification_service/src/notification/user_ids/mod.rs+++ /dev/null@@ -1 +0,0 @@-pub mod utils;diff --git a/rust/cloud-storage/notification_service/src/notification/user_ids/utils.rs b/rust/cloud-storage/notification_service/src/notification/user_ids/utils.rsdeleted file mode 100644index 7730f478d9..0000000000--- a/rust/cloud-storage/notification_service/src/notification/user_ids/utils.rs+++ /dev/null@@ -1,84 +0,0 @@-use anyhow::{Result, anyhow};--pub fn filter_sender_id_from_recipient_ids(- sender_id: Option<&str>,- recipient_ids: Option<&Vec<String>>,-) -> Result<Vec<String>> {- let user_id = sender_id.ok_or(anyhow!("no sender id provided"))?;- let mut recipient_ids = recipient_ids- .ok_or(anyhow!("no recipient ids provided"))?- .clone();- recipient_ids.sort();- recipient_ids.dedup();-- let filtered_user_ids = recipient_ids- .iter()- .filter(|id| user_id != *id)- .cloned()- .collect();-- Ok(filtered_user_ids)-}--#[cfg(test)]-mod tests {- use macro_user_id::user_id::MacroUserIdStr;-- use super::*;-- #[test]- fn test_filter_sender_id_success() -> Result<()> {- let sender_id = Some("user1".to_string());- let recipient_ids = Some(vec![- "user1".to_string(),- "user2".to_string(),- "user3".to_string(),- ]);- let filtered = filter_sender_id_from_recipient_ids(- sender_id.as_ref().map(|x| x.as_str()),- recipient_ids.as_ref(),- )?;- assert_eq!(filtered, vec!["user2".to_string(), "user3".to_string()]);- Ok(())- }-- #[test]- fn test_filter_sender_id_no_sender() {- let recipient_ids = Some(vec!["user1".to_string(), "user2".to_string()]);- let result = filter_sender_id_from_recipient_ids(None, recipient_ids.as_ref());- assert!(result.is_err());- if let Err(err) = result {- assert_eq!(err.to_string(), "no sender id provided");- }- }-- #[test]- fn test_filter_sender_id_no_recipients() {- let sender_id = Some(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());- let recipient_ids: Option<&Vec<String>> = None;- let result = filter_sender_id_from_recipient_ids(- sender_id.as_ref().map(|x| x.as_ref()),- recipient_ids,- );- assert!(result.is_err());- if let Err(err) = result {- assert_eq!(err.to_string(), "no recipient ids provided");- }- }-- #[test]- fn test_filter_duplicate_recipients() -> Result<()> {- let sender_id = Some(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());- let recipient_ids = Some(vec![- "user2".to_string(),- "user2".to_string(),- "user2".to_string(),- ]);- let filtered = filter_sender_id_from_recipient_ids(- sender_id.as_ref().map(|x| x.as_ref()),- recipient_ids.as_ref(),- )?;- assert_eq!(filtered, vec!["user2".to_string()]);- Ok(())- }-}diff --git a/rust/cloud-storage/properties/Cargo.toml b/rust/cloud-storage/properties/Cargo.tomlindex 8703085556..db9072670f 100644--- a/rust/cloud-storage/properties/Cargo.toml+++ b/rust/cloud-storage/properties/Cargo.toml@@ -10,13 +10,14 @@ futures = { workspace = true }email_db_client = { path = "../email_db_client" }macro_db_client = { path = "../macro_db_client" }macro_middleware = { path = "../macro_middleware", default-features = false, features = ["cloud_storage", "user_permissions"] }-macro_notify = { path = "../macro_notify" }+notification = { path = "../notification" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model_notifications = { path = "../model_notifications" }model-entity = { path = "../model-entity" }models_permissions = { path = "../models_permissions" }models_properties = { path = "../models_properties" }+serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }system_properties = { path = "../system_properties" }diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsindex 06c2875208..06aefb0b40 100644--- a/rust/cloud-storage/properties/src/domain/ports.rs+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -4,9 +4,11 @@//! Implementations live in the outbound module.use macro_user_id::user_id::MacroUserIdStr;+use model_notifications::TaskAssignedMetadata;use models_properties::EntityType;use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_value::PropertyValue;+use notification::domain::models::SendNotificationRequest;use uuid::Uuid;/// Repository trait for property operations.@@ -133,15 +135,15 @@ pub trait PermissionService: Send + Sync + 'static {/// Notification service trait for sending notifications.////// This trait abstracts notification operations, allowing for different implementations-/// (e.g., macro_notify-backed, mock for testing).+/// (e.g., notification-service-backed, mock for testing).#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]pub trait NotificationService: Send + Sync + 'static {type Err;/// Send a notification message./// Returns the notification ID if successful.- fn send_notification(+ fn send_notification<'a>(&self,- message: model_notifications::NotificationQueueMessage,+ message: SendNotificationRequest<'a, TaskAssignedMetadata, ()>,) -> impl Future<Output = Result<uuid::Uuid, Self::Err>> + Send;}diff --git a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rsindex ed970d6ba4..2e23af1767 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs@@ -8,6 +8,7 @@ use macro_user_id::user_id::MacroUserIdStr;use models_properties::EntityType;use models_properties::api::requests::SetPropertyValue;use models_properties::service::property_value::PropertyValue;+use notification::domain::models::SendNotificationRequestBuilder;use system_properties::SystemPropertyKey;use uuid::Uuid;@@ -189,30 +190,31 @@ where.map_err(|e| PropertiesErr::Validation(format!("Invalid user ID format: {}", e)))?.into_owned();- let metadata = model_notifications::TaskAssignedMetadata {- task_id: task_id.to_string(),- task_name: task_name.clone(),- assigned_by: assigned_by.clone(),- };-- let notification_event = model_notifications::NotificationEvent::TaskAssigned(metadata);-let notification_entity =model_entity::EntityType::Document.with_entity_string(task_id.to_string());let notification_futures: Vec<_> = recipient_ids.iter().map(|recipient_id| {- let message = model_notifications::NotificationQueueMessage {+ let metadata = model_notifications::TaskAssignedMetadata {+ task_id: task_id.to_string(),+ task_name: task_name.clone(),+ assigned_by: assigned_by.clone(),+ };++ let request = SendNotificationRequestBuilder {notification_entity: notification_entity.clone(),- notification_event: notification_event.clone(),+ notification: metadata,sender_id: Some(assigned_by.clone()),- recipient_ids: Some(vec![recipient_id.to_string()]),- };+ recipient_ids: HashSet::from([recipient_id.copied()]),+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();let recipient_id_for_log = recipient_id.clone();async move {- let send_result = notification_service.send_notification(message).await;+ let send_result = notification_service.send_notification(request).await;match send_result {Ok(notification_id) => {tracing::debug!(diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rsindex 6a1940cc30..4d647b8d36 100644--- a/rust/cloud-storage/properties/src/domain/test.rs+++ b/rust/cloud-storage/properties/src/domain/test.rs@@ -541,24 +541,6 @@ async fn check_notifications(test_case: NotificationTestCase) {notif_service.expect_send_notification().times(expected_count)- .withf(move |message| {- let event_type_correct = message.notification_event.event_type()- == model_notifications::NotificationEventType::TaskAssigned;- let recipient_correct = if let Some(expected) = &expected_recipients {- message- .recipient_ids- .as_ref()- .map(|ids| ids.len() == 1 && expected.contains(&ids[0]))- .unwrap_or(false)- } else {- message- .recipient_ids- .as_ref()- .map(|ids| ids.len() == 1)- .unwrap_or(false)- };- event_type_correct && recipient_correct- }).returning(|_| Box::pin(async { Ok(Uuid::new_v4()) }));}diff --git a/rust/cloud-storage/properties/src/outbound/notification_service.rs b/rust/cloud-storage/properties/src/outbound/notification_service.rsindex ae794b999b..bf14fb7f30 100644--- a/rust/cloud-storage/properties/src/outbound/notification_service.rs+++ b/rust/cloud-storage/properties/src/outbound/notification_service.rs@@ -1,30 +1,47 @@//! Notification service implementation for properties.-use uuid::Uuid;-use crate::domain::ports::NotificationService;+use model_notifications::TaskAssignedMetadata;+use notification::domain::models::SendNotificationRequest;+use notification::domain::service::NotificationIngress;+use uuid::Uuid;-/// Notification service implementation using macro_notify client.-pub struct NotificationServiceImpl {- notification_client: std::sync::Arc<macro_notify::MacroNotifyClient>,+/// Notification service implementation using the new notification client.+pub struct NotificationServiceImpl<T> {+ notification_client: T,}-impl NotificationServiceImpl {- pub fn new(notification_client: std::sync::Arc<macro_notify::MacroNotifyClient>) -> Self {+impl<T> NotificationServiceImpl<T>+where+ T: NotificationIngress,+{+ /// Create a new notification service with the notification client.+ pub fn new(notification_client: T) -> Self {Self {notification_client,}}}-impl NotificationService for NotificationServiceImpl {+impl<T> NotificationService for NotificationServiceImpl<T>+where+ T: NotificationIngress,+{type Err = anyhow::Error;- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, message), err)]async fn send_notification(&self,- message: model_notifications::NotificationQueueMessage,+ message: SendNotificationRequest<'_, TaskAssignedMetadata, ()>,) -> Result<Uuid, Self::Err> {- self.notification_client.send_notification(message).await+ let result = self+ .notification_client+ .send_notification(message)+ .await+ .map_err(|e| anyhow::anyhow!("failed to send notification: {}", e))?;++ Ok(result+ .map(|r| r.notification_id)+ .unwrap_or_else(Uuid::now_v7))}}diff --git a/rust/cloud-storage/properties_service/Cargo.toml b/rust/cloud-storage/properties_service/Cargo.tomlindex 5669e06aae..e2f5a19ff6 100644--- a/rust/cloud-storage/properties_service/Cargo.toml+++ b/rust/cloud-storage/properties_service/Cargo.toml@@ -29,7 +29,8 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"auth","cloud_storage",] }-macro_notify = { path = "../macro_notify" }+notification = { path = "../notification" }+aws-sdk-sqs = { workspace = true }macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }models_permissions = { path = "../models_permissions" }diff --git a/rust/cloud-storage/properties_service/src/api/context.rs b/rust/cloud-storage/properties_service/src/api/context.rsindex 49f4c63795..df1a4b34f1 100644--- a/rust/cloud-storage/properties_service/src/api/context.rs+++ b/rust/cloud-storage/properties_service/src/api/context.rs@@ -1,14 +1,21 @@use axum::extract::FromRef;+use notification::domain::service::NotificationIngressService;+use notification::outbound::queue::SqsNotificationQueue;+use notification::outbound::repository::DbNotificationRepository;use sqlx::PgPool;use std::sync::Arc;use properties::PropertiesServiceImpl;+/// The concrete notification ingress service type.+type NotificationIngressType =+ NotificationIngressService<DbNotificationRepository<PgPool>, SqsNotificationQueue>;+/// Type alias for the properties service implementation used throughout the service.pub type PropertiesService = PropertiesServiceImpl<properties::PropertiesPgRepo,properties::PermissionServiceImpl,- properties::NotificationServiceImpl,+ properties::NotificationServiceImpl<NotificationIngressType>,>;/// Minimal state required by properties handlers.