Skip to content

armgit / macro

Public Imported from GitHub
0

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

Seanaye/feat/ignore notification typenames (#2214)

Sean Aye2ac27b6d3780
diff --git a/.github/workflows/code-check-infra.yml b/.github/workflows/code-check-infra.yml
index 0eec8c5b78..b50082ed39 100644
--- a/.github/workflows/code-check-infra.yml
+++ b/.github/workflows/code-check-infra.yml
@@ -36,7 +36,7 @@ jobs:
- name: Setup Biome
uses: biomejs/setup-biome@v2
with:
- version: 2.2.6
+ version: 2.4.7
- name: Run Biome
working-directory: infra
run: biome ci --changed --no-errors-on-unmatched --error-on-warnings
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index 6b74812547..c15d888f3a 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -47,7 +47,7 @@ jobs:
- name: Setup Biome
uses: biomejs/setup-biome@v2
with:
- version: 2.2.6
+ version: 2.4.7
- name: Generate API Types
if: needs.path-check.outputs.api_changed == 'true'
working-directory: js/app
@@ -70,7 +70,7 @@ jobs:
- name: Setup Biome
uses: biomejs/setup-biome@v2
with:
- version: 2.2.6
+ version: 2.4.7
- name: Run Biome
working-directory: js/app
run: biome ci --changed --no-errors-on-unmatched --error-on-warnings
@@ -121,10 +121,10 @@ jobs:
- name: Setup Biome
uses: biomejs/setup-biome@v2
with:
- version: 2.2.6
+ version: 2.4.7
- name: Cycles Import Check
working-directory: js/app
- run: biome lint --changed --no-errors-on-unmatched --only=nursery/noImportCycles
+ run: biome lint --changed --no-errors-on-unmatched --only=suspicious/noImportCycles
build:
needs: path-check
diff --git a/infra/biome.jsonc b/infra/biome.jsonc
index e91eb46ead..3847cea2ce 100644
--- a/infra/biome.jsonc
+++ b/infra/biome.jsonc
@@ -1,5 +1,5 @@
{
- "$schema": "https://biomejs.dev/schemas/2.2.6/schema.json",
+ "$schema": "https://biomejs.dev/schemas/2.4.7/schema.json",
"vcs": {
"clientKind": "git",
"enabled": true,
diff --git a/js/app/biome.jsonc b/js/app/biome.jsonc
index 7846073a20..3eed8492dd 100644
--- a/js/app/biome.jsonc
+++ b/js/app/biome.jsonc
@@ -1,5 +1,5 @@
{
- "$schema": "https://biomejs.dev/schemas/2.2.6/schema.json",
+ "$schema": "https://biomejs.dev/schemas/2.4.7/schema.json",
"vcs": {
"clientKind": "git",
"enabled": true,
diff --git a/js/app/packages/core/service.ts b/js/app/packages/core/service.ts
index a783d0b74e..ec7af90de6 100644
--- a/js/app/packages/core/service.ts
+++ b/js/app/packages/core/service.ts
@@ -245,29 +245,21 @@ export class Svc<
type ZodShapeToType<T extends z.ZodRawShape | undefined> =
T extends z.ZodRawShape ? z.infer<z.ZodObject<T>> : undefined;
-type ClientFunctionArgs<T> = T extends FunctionDefinition<
- any,
- infer Args,
- any,
- any
->
- ? ZodShapeToType<Args>
- : never;
-
-type ClientFunctionResult<T> = T extends FunctionDefinition<
- any,
- any,
- infer Result,
- infer Throws
->
- ? Result extends z.ZodRawShape
- ? Throws extends string[]
- ? MaybeResult<Throws[number], ZodShapeToType<Result>>
- : ZodShapeToType<Result>
- : Throws extends string[]
- ? MaybeError<Throws[number]>
- : void
- : never;
+type ClientFunctionArgs<T> =
+ T extends FunctionDefinition<any, infer Args, any, any>
+ ? ZodShapeToType<Args>
+ : never;
+
+type ClientFunctionResult<T> =
+ T extends FunctionDefinition<any, any, infer Result, infer Throws>
+ ? Result extends z.ZodRawShape
+ ? Throws extends string[]
+ ? MaybeResult<Throws[number], ZodShapeToType<Result>>
+ : ZodShapeToType<Result>
+ : Throws extends string[]
+ ? MaybeError<Throws[number]>
+ : void
+ : never;
export type ClientFunction<T extends FunctionDefinition<any, any, any, any>> =
ClientFunctionArgs<T> extends undefined
@@ -287,13 +279,10 @@ type OmitEmptyObjects<T> = {
[K in keyof T as T[K] extends Record<string, never> ? never : K]: T[K];
};
-export type ServiceClient<T extends Svc<any, any, any>> = T extends Svc<
- any,
- infer F,
- infer S
->
- ? FlattenObject<ClientFunctions<F> & OmitEmptyObjects<ClientServices<S>>>
- : never;
+export type ServiceClient<T extends Svc<any, any, any>> =
+ T extends Svc<any, infer F, infer S>
+ ? FlattenObject<ClientFunctions<F> & OmitEmptyObjects<ClientServices<S>>>
+ : never;
/**
* Defines common fetch errors that can occur during API requests.
@@ -328,7 +317,6 @@ export function withFetchErrors<const T extends string>(
type NonNullableShape<T extends z.ZodTypeAny> = T extends
| z.ZodOptional<infer U>
- // biome-ignore lint/suspicious/noRedeclare: type reduction
| z.ZodNullable<infer U>
? NonNullableShape<U>
: T extends z.ZodObject<infer Shape>
diff --git a/js/app/packages/core/util/maybeResult.ts b/js/app/packages/core/util/maybeResult.ts
index 0252f6780e..e8edf4473a 100644
--- a/js/app/packages/core/util/maybeResult.ts
+++ b/js/app/packages/core/util/maybeResult.ts
@@ -306,12 +306,8 @@ export function onErr<
return false;
}
-export type ResultType<T extends MaybeResult<any, any>> = T extends MaybeResult<
- any,
- infer R
->
- ? NonNullable<R>
- : never;
+export type ResultType<T extends MaybeResult<any, any>> =
+ T extends MaybeResult<any, infer R> ? NonNullable<R> : never;
/**
* Error class that preserves MaybeResult errors when thrown.
diff --git a/js/app/packages/queries/soup/normalized-cache/operations.test.ts b/js/app/packages/queries/soup/normalized-cache/operations.test.ts
index 35da190d95..6dc8e24cdd 100644
--- a/js/app/packages/queries/soup/normalized-cache/operations.test.ts
+++ b/js/app/packages/queries/soup/normalized-cache/operations.test.ts
@@ -215,30 +215,31 @@ describe('buildSingleEntityFilter', () => {
filterKey: 'project_filters',
idKey: 'project_ids',
},
- ])(
- 'unblocks only $entityType filter with the real entityId',
- ({ entityType, filterKey, idKey }) => {
- const filter = buildSingleEntityFilter(entityType, 'entity-1')!;
- expect(filter).not.toBeNull();
- expect(filter.limit).toBe(1);
-
- // The target filter uses the real entityId
- expect((filter as any)[filterKey][idKey]).toEqual(['entity-1']);
-
- // All other ID-based filters use NIL_ID
- const otherFilters = [
- 'document_filters',
- 'chat_filters',
- 'channel_filters',
- 'project_filters',
- ].filter((k) => k !== filterKey);
-
- for (const key of otherFilters) {
- const ids = Object.values((filter as any)[key])[0];
- expect(ids).toEqual([NIL_ID]);
- }
+ ])('unblocks only $entityType filter with the real entityId', ({
+ entityType,
+ filterKey,
+ idKey,
+ }) => {
+ const filter = buildSingleEntityFilter(entityType, 'entity-1')!;
+ expect(filter).not.toBeNull();
+ expect(filter.limit).toBe(1);
+
+ // The target filter uses the real entityId
+ expect((filter as any)[filterKey][idKey]).toEqual(['entity-1']);
+
+ // All other ID-based filters use NIL_ID
+ const otherFilters = [
+ 'document_filters',
+ 'chat_filters',
+ 'channel_filters',
+ 'project_filters',
+ ].filter((k) => k !== filterKey);
+
+ for (const key of otherFilters) {
+ const ids = Object.values((filter as any)[key])[0];
+ expect(ids).toEqual([NIL_ID]);
}
- );
+ });
});
describe('insertSoupEntity', () => {
diff --git a/js/app/packages/service-clients/service-notification/generated/client.ts b/js/app/packages/service-clients/service-notification/generated/client.ts
index 09e74a1af6..a14680d8b0 100644
--- a/js/app/packages/service-clients/service-notification/generated/client.ts
+++ b/js/app/packages/service-clients/service-notification/generated/client.ts
@@ -11,6 +11,7 @@ import type {
EmptyResponse,
ErrorResponse,
GetAllUserNotificationsResponse,
+ GetNotificationTypePreferencesResponse,
GetTypedNotificationsByEventItemIdParams,
ListTypedNotificationsParams,
NotificationBulkRequest,
@@ -640,6 +641,190 @@ export const getTypedNotificationsByEventItemId = async (
} as getTypedNotificationsByEventItemIdResponse;
};
+/**
+ * @summary Get the notification types that the user has disabled.
+ */
+export type getNotificationTypePreferencesResponse200 = {
+ data: GetNotificationTypePreferencesResponse;
+ status: 200;
+};
+
+export type getNotificationTypePreferencesResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type getNotificationTypePreferencesResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type getNotificationTypePreferencesResponseSuccess =
+ getNotificationTypePreferencesResponse200 & {
+ headers: Headers;
+ };
+export type getNotificationTypePreferencesResponseError = (
+ | getNotificationTypePreferencesResponse401
+ | getNotificationTypePreferencesResponse500
+) & {
+ headers: Headers;
+};
+
+export type getNotificationTypePreferencesResponse =
+ | getNotificationTypePreferencesResponseSuccess
+ | getNotificationTypePreferencesResponseError;
+
+export const getGetNotificationTypePreferencesUrl = () => {
+ return `/v1/user_notifications/preferences`;
+};
+
+export const getNotificationTypePreferences = async (
+ options?: RequestInit
+): Promise<getNotificationTypePreferencesResponse> => {
+ const res = await fetch(getGetNotificationTypePreferencesUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getNotificationTypePreferencesResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getNotificationTypePreferencesResponse;
+};
+
+/**
+ * @summary Disable a notification type for the authenticated user.
+ */
+export type disableNotificationTypeResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type disableNotificationTypeResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type disableNotificationTypeResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type disableNotificationTypeResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type disableNotificationTypeResponseSuccess =
+ disableNotificationTypeResponse200 & {
+ headers: Headers;
+ };
+export type disableNotificationTypeResponseError = (
+ | disableNotificationTypeResponse400
+ | disableNotificationTypeResponse401
+ | disableNotificationTypeResponse500
+) & {
+ headers: Headers;
+};
+
+export type disableNotificationTypeResponse =
+ | disableNotificationTypeResponseSuccess
+ | disableNotificationTypeResponseError;
+
+export const getDisableNotificationTypeUrl = (
+ notificationEventType: string
+) => {
+ return `/v1/user_notifications/preferences/${notificationEventType}/disable`;
+};
+
+export const disableNotificationType = async (
+ notificationEventType: string,
+ options?: RequestInit
+): Promise<disableNotificationTypeResponse> => {
+ const res = await fetch(
+ getDisableNotificationTypeUrl(notificationEventType),
+ {
+ ...options,
+ method: 'PUT',
+ }
+ );
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: disableNotificationTypeResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as disableNotificationTypeResponse;
+};
+
+/**
+ * @summary Re-enable a notification type for the authenticated user.
+ */
+export type enableNotificationTypeResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type enableNotificationTypeResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type enableNotificationTypeResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type enableNotificationTypeResponseSuccess =
+ enableNotificationTypeResponse200 & {
+ headers: Headers;
+ };
+export type enableNotificationTypeResponseError = (
+ | enableNotificationTypeResponse401
+ | enableNotificationTypeResponse500
+) & {
+ headers: Headers;
+};
+
+export type enableNotificationTypeResponse =
+ | enableNotificationTypeResponseSuccess
+ | enableNotificationTypeResponseError;
+
+export const getEnableNotificationTypeUrl = (notificationEventType: string) => {
+ return `/v1/user_notifications/preferences/${notificationEventType}/enable`;
+};
+
+export const enableNotificationType = async (
+ notificationEventType: string,
+ options?: RequestInit
+): Promise<enableNotificationTypeResponse> => {
+ const res = await fetch(getEnableNotificationTypeUrl(notificationEventType), {
+ ...options,
+ method: 'PUT',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: enableNotificationTypeResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as enableNotificationTypeResponse;
+};
+
/**
* @summary Typed wrapper for getting a single notification by ID.
*/
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/getNotificationTypePreferencesResponse.ts b/js/app/packages/service-clients/service-notification/generated/schemas/getNotificationTypePreferencesResponse.ts
new file mode 100644
index 0000000000..1a97fcbebf
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/getNotificationTypePreferencesResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response for listing disabled notification types.
+ */
+export interface GetNotificationTypePreferencesResponse {
+ /** The notification types that the user has disabled. */
+ disabled_types: 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.ts
index deb99c540e..118f6acd38 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
@@ -47,6 +47,7 @@ export * from './entityType';
export * from './errorResponse';
export * from './getAllUserNotificationsResponse';
export * from './getAllUserNotificationsResponseNextCursor';
+export * from './getNotificationTypePreferencesResponse';
export * from './getTypedNotificationsByEventItemIdParams';
export * from './inviteToTeamMetadata';
export * from './inviteToTeamMetadataRole';
diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.json
index 18e87c950e..0195a34089 100644
--- a/js/app/packages/service-clients/service-notification/openapi.json
+++ b/js/app/packages/service-clients/service-notification/openapi.json
@@ -533,6 +533,141 @@
}
}
},
+ "/v1/user_notifications/preferences": {
+ "get": {
+ "tags": ["user_notification"],
+ "summary": "Get the notification types that the user has disabled.",
+ "operationId": "get_notification_type_preferences",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetNotificationTypePreferencesResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/v1/user_notifications/preferences/{notification_event_type}/disable": {
+ "put": {
+ "tags": ["user_notification"],
+ "summary": "Disable a notification type for the authenticated user.",
+ "operationId": "disable_notification_type",
+ "parameters": [
+ {
+ "name": "notification_event_type",
+ "in": "path",
+ "description": "The notification event type to disable",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "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"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/v1/user_notifications/preferences/{notification_event_type}/enable": {
+ "put": {
+ "tags": ["user_notification"],
+ "summary": "Re-enable a notification type for the authenticated user.",
+ "operationId": "enable_notification_type",
+ "parameters": [
+ {
+ "name": "notification_event_type",
+ "in": "path",
+ "description": "The notification event type to enable",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/v1/user_notifications/{notification_id}": {
"get": {
"tags": ["user_notification"],
@@ -1258,6 +1393,20 @@
}
}
},
+ "GetNotificationTypePreferencesResponse": {
+ "type": "object",
+ "description": "Response for listing disabled notification types.",
+ "required": ["disabled_types"],
+ "properties": {
+ "disabled_types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "The notification types that the user has disabled."
+ }
+ }
+ },
"InviteToTeamMetadata": {
"type": "object",
"required": ["teamName", "teamId", "invitedBy"],
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260325181013_user_notification_type_preference.sql b/rust/cloud-storage/macro_db_client/migrations/20260325181013_user_notification_type_preference.sql
new file mode 100644
index 0000000000..aa1d0680fd
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260325181013_user_notification_type_preference.sql
@@ -0,0 +1,11 @@
+-- User notification type preferences
+-- A row means the user has disabled that notification type.
+-- Absence of a row means the user receives that notification type (default).
+
+CREATE TABLE user_notification_type_preference (
+ user_id TEXT NOT NULL,
+ notification_event_type VARCHAR(255) NOT NULL,
+ PRIMARY KEY (user_id, notification_event_type)
+);
+
+CREATE INDEX idx_user_notif_type_pref_user ON user_notification_type_preference (user_id);
diff --git a/rust/cloud-storage/notification/.sqlx/query-36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1.json b/rust/cloud-storage/notification/.sqlx/query-36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1.json
new file mode 100644
index 0000000000..c07ec0acbe
--- /dev/null
+++ b/rust/cloud-storage/notification/.sqlx/query-36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO user_notification_type_preference (user_id, notification_event_type)\n VALUES ($1, $2)\n ON CONFLICT (user_id, notification_event_type) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Varchar"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1"
+}
diff --git a/rust/cloud-storage/notification/.sqlx/query-625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674.json b/rust/cloud-storage/notification/.sqlx/query-625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674.json
new file mode 100644
index 0000000000..d374c2f79f
--- /dev/null
+++ b/rust/cloud-storage/notification/.sqlx/query-625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM user_notification_type_preference\n WHERE user_id = $1 AND notification_event_type = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674"
+}
diff --git a/rust/cloud-storage/notification/.sqlx/query-7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198.json b/rust/cloud-storage/notification/.sqlx/query-7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198.json
new file mode 100644
index 0000000000..721b0038f2
--- /dev/null
+++ b/rust/cloud-storage/notification/.sqlx/query-7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, notification_event_type\n FROM user_notification_type_preference\n WHERE user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "notification_event_type",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198"
+}
diff --git a/rust/cloud-storage/notification/.sqlx/query-db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73.json b/rust/cloud-storage/notification/.sqlx/query-db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73.json
new file mode 100644
index 0000000000..d197caf563
--- /dev/null
+++ b/rust/cloud-storage/notification/.sqlx/query-db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id FROM user_notification_type_preference\n WHERE notification_event_type = $1 AND user_id = ANY($2)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73"
+}
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index 3b187bc56b..ac2782f299 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -245,6 +245,17 @@ impl<T> SortOn<CreatedAt> for UserNotificationRow<T> {
}
}
+/// A notification type that a user has disabled.
+///
+/// Presence of a row means the user has opted out of this type.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DisabledNotificationType {
+ /// The user who disabled this type.
+ pub user_id: MacroUserIdStr<'static>,
+ /// The notification event type (e.g. "channel_message_send").
+ pub notification_event_type: String,
+}
+
/// Trait that all notification types must implement.
pub trait Notification: Serialize + DeserializeOwned + Send + Sync + 'static {
/// The type name of this notification.
diff --git a/rust/cloud-storage/notification/src/domain/models/recipient.rs b/rust/cloud-storage/notification/src/domain/models/recipient.rs
index c77aa7701e..eaf65cd08b 100644
--- a/rust/cloud-storage/notification/src/domain/models/recipient.rs
+++ b/rust/cloud-storage/notification/src/domain/models/recipient.rs
@@ -28,6 +28,8 @@ pub enum ExclusionReason {
MutedNotifications,
/// The recipient has unsubscribed from notifications for this item.
UnsubscribedFromItem,
+ /// The recipient has disabled this notification type.
+ DisabledNotificationType,
}
impl ExclusionReason {
@@ -37,6 +39,7 @@ impl ExclusionReason {
ExclusionReason::IsSender => "User is the sender",
ExclusionReason::MutedNotifications => "User has muted notifications",
ExclusionReason::UnsubscribedFromItem => "User has unsubscribed from this item",
+ ExclusionReason::DisabledNotificationType => "User has disabled this notification type",
}
}
}
diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rs
index 7270a7b201..c22b60e9a7 100644
--- a/rust/cloud-storage/notification/src/domain/models/request.rs
+++ b/rust/cloud-storage/notification/src/domain/models/request.rs
@@ -145,6 +145,7 @@ impl<'a, T, U> SendNotificationRequest<'a, T, U> {
mut self,
muted_users: HashSet<MacroUserIdStr<'a>>,
unsubscribed_users: HashSet<MacroUserIdStr<'a>>,
+ type_disabled_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))
@@ -182,6 +183,18 @@ impl<'a, T, U> SendNotificationRequest<'a, T, U> {
x => x,
};
+ let user_disabled_type = |id: FilteredRecipient<'a>| match id {
+ FilteredRecipient::Allowed(macro_user_id_str)
+ if type_disabled_users.contains(&macro_user_id_str) =>
+ {
+ FilteredRecipient::Excluded(RecipientExclusion {
+ user_id: macro_user_id_str,
+ reason: ExclusionReason::DisabledNotificationType,
+ })
+ }
+ x => x,
+ };
+
let recipients = std::mem::take(&mut self.req.recipient_ids);
let (allowed, excluded): (HashSet<_>, Vec<_>) = recipients
@@ -190,6 +203,7 @@ impl<'a, T, U> SendNotificationRequest<'a, T, U> {
.map(recipient_is_sender)
.map(user_muted_notifs)
.map(notif_type_is_ignored)
+ .map(user_disabled_type)
.partition_map(|r| match r {
FilteredRecipient::Allowed(a) => itertools::Either::Left(a),
FilteredRecipient::Excluded(b) => itertools::Either::Right(b),
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index 408d6b65a0..595de4b186 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -20,7 +20,7 @@ use crate::domain::models::device::DeviceType;
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};
use crate::domain::models::{
- DeviceEndpoint, NotificationExtEmail, NotificationIdAndCollapseKey,
+ DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,
SendNotificationRequestBuilder, UserNotificationRow, android::FCMMessage,
apple::APNSPushNotification, mobile::MessageAttributes,
};
@@ -194,6 +194,33 @@ pub trait NotificationRepository: Send + Sync + 'static {
&self,
endpoint_arn: &str,
) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Get users (from the given set) who have disabled the specified notification type.
+ fn get_users_with_type_disabled<'a>(
+ &self,
+ notification_event_type: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+
+ /// Get all disabled notification types for a user.
+ fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<DisabledNotificationType>, Report>> + Send;
+
+ /// Disable a notification type for a user (insert).
+ fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Re-enable a notification type for a user (delete).
+ fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
}
/// Port for WebSocket delivery via connection gateway.
diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rs
index 840bbc00a9..c51eea3c64 100644
--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs
@@ -193,6 +193,34 @@ impl NotificationRepository for MockNotifRepo {
) -> Result<(), Report> {
unimplemented!()
}
+ async fn get_users_with_type_disabled<'a>(
+ &self,
+ _: &str,
+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],
+ ) -> Result<std::collections::HashSet<macro_user_id::user_id::MacroUserIdStr<'static>>, Report>
+ {
+ unimplemented!()
+ }
+ async fn get_disabled_notification_types(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Vec<crate::domain::models::DisabledNotificationType>, Report> {
+ unimplemented!()
+ }
+ async fn disable_notification_type(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &str,
+ ) -> Result<(), Report> {
+ unimplemented!()
+ }
+ async fn enable_notification_type(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &str,
+ ) -> Result<(), Report> {
+ unimplemented!()
+ }
}
struct MockSnsManager {
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
index 160d0cd79f..63a37e6e50 100644
--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -17,7 +17,8 @@ use crate::domain::models::request::{
SendNotificationRequest, UpdateNotificationsRequest,
};
use crate::domain::models::{
- DeviceEndpoint, Notification, NotificationResult, NotificationTypeName, UserNotificationRow,
+ DeviceEndpoint, DisabledNotificationType, Notification, NotificationResult,
+ NotificationTypeName, UserNotificationRow,
};
use crate::domain::ports::{
NotificationIngressQueue, NotificationQueue, NotificationRepository, SnsEndpointManager,
@@ -116,6 +117,26 @@ pub trait NotificationReader: Send + Sync + 'static {
device_token: &str,
device_type: &DeviceType,
) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+
+ /// Get all disabled notification types for a user.
+ fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Vec<DisabledNotificationType>, Report>> + Send;
+
+ /// Disable a notification type for a user.
+ fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ type_name: &str,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Re-enable a notification type for a user.
+ fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ type_name: &str,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
}
/// Service for sending notifications (ingress side).
@@ -238,15 +259,19 @@ where
req: SendNotificationRequest<'a, T, U>,
) -> Result<SendNotificationRequest<'a, T, U>, Report> {
let recipient_ids: Vec<_> = req.req.recipient_ids.iter().map(CowLike::copied).collect();
+ let notification_type = req.req.notification.tag.as_ref();
// Fetch all filter data upfront
- let (muted_users, unsubscribed_users) = tokio::try_join!(
+ let (muted_users, unsubscribed_users, type_disabled_users) = tokio::try_join!(
self.repository.get_muted_users(&recipient_ids),
self.repository
.get_unsubscribed_users(&req.req.notification_entity.entity_id, &recipient_ids),
+ self.repository
+ .get_users_with_type_disabled(notification_type, &recipient_ids),
)?;
- let (out, _excluded) = req.update_recipients(muted_users, unsubscribed_users);
+ let (out, _excluded) =
+ req.update_recipients(muted_users, unsubscribed_users, type_disabled_users);
Ok(out)
}
@@ -707,4 +732,36 @@ where
Ok(())
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<DisabledNotificationType>, Report> {
+ self.repository
+ .get_disabled_notification_types(user_id)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ type_name: &str,
+ ) -> Result<(), Report> {
+ self.repository
+ .disable_notification_type(user_id, type_name)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ type_name: &str,
+ ) -> Result<(), Report> {
+ self.repository
+ .enable_notification_type(user_id, type_name)
+ .await
+ }
}
diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
index 918c3a84bb..e6c2a27925 100644
--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
@@ -179,6 +179,34 @@ impl NotificationRepository for MockNotifRepo {
) -> Result<String, Report> {
unimplemented!()
}
+ async fn get_users_with_type_disabled<'a>(
+ &self,
+ _: &str,
+ _: &[macro_user_id::user_id::MacroUserIdStr<'a>],
+ ) -> Result<std::collections::HashSet<macro_user_id::user_id::MacroUserIdStr<'static>>, Report>
+ {
+ unimplemented!()
+ }
+ async fn get_disabled_notification_types(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Vec<crate::domain::models::DisabledNotificationType>, Report> {
+ unimplemented!()
+ }
+ async fn disable_notification_type(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &str,
+ ) -> Result<(), Report> {
+ unimplemented!()
+ }
+ async fn enable_notification_type(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &str,
+ ) -> Result<(), Report> {
+ unimplemented!()
+ }
}
/// Mock SNS endpoint manager that only implements delete_endpoint.
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index 430ef0ea8e..609e917f0f 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -96,6 +96,7 @@ fn test_user_id(email: &str) -> MacroUserIdStr<'static> {
struct MockRepository {
muted_users: HashSet<MacroUserIdStr<'static>>,
unsubscribed_users: HashSet<MacroUserIdStr<'static>>,
+ type_disabled_users: HashSet<MacroUserIdStr<'static>>,
device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>,
created_notifications: Mutex<Vec<Uuid>>,
stored_collapse_keys: Mutex<Vec<(Uuid, Option<String>)>>,
@@ -109,6 +110,7 @@ impl MockRepository {
Self {
muted_users: HashSet::new(),
unsubscribed_users: HashSet::new(),
+ type_disabled_users: HashSet::new(),
device_endpoints: HashMap::new(),
created_notifications: Mutex::new(Vec::new()),
stored_collapse_keys: Mutex::new(Vec::new()),
@@ -136,6 +138,11 @@ impl MockRepository {
self
}
+ fn with_type_disabled_user(mut self, user_id: MacroUserIdStr<'static>) -> Self {
+ self.type_disabled_users.insert(user_id);
+ self
+ }
+
fn with_device_endpoint(
mut self,
user_id: MacroUserIdStr<'static>,
@@ -339,6 +346,37 @@ impl NotificationRepository for MockRepository {
async fn delete_device_by_endpoint(&self, _endpoint_arn: &str) -> Result<(), Report> {
Ok(())
}
+
+ async fn get_users_with_type_disabled<'a>(
+ &self,
+ _notification_event_type: &str,
+ _user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ Ok(self.type_disabled_users.clone())
+ }
+
+ async fn get_disabled_notification_types(
+ &self,
+ _user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<crate::domain::models::DisabledNotificationType>, Report> {
+ Ok(vec![])
+ }
+
+ async fn disable_notification_type(
+ &self,
+ _user_id: MacroUserIdStr<'_>,
+ _notification_event_type: &str,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+
+ async fn enable_notification_type(
+ &self,
+ _user_id: MacroUserIdStr<'_>,
+ _notification_event_type: &str,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
}
impl NotificationRepository for std::sync::Arc<MockRepository> {
@@ -501,6 +539,43 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {
(**self).delete_device_by_endpoint(endpoint_arn).await
}
+
+ async fn get_users_with_type_disabled<'a>(
+ &self,
+ notification_event_type: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ (**self)
+ .get_users_with_type_disabled(notification_event_type, user_ids)
+ .await
+ }
+
+ async fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<crate::domain::models::DisabledNotificationType>, Report> {
+ (**self).get_disabled_notification_types(user_id).await
+ }
+
+ async fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ (**self)
+ .disable_notification_type(user_id, notification_event_type)
+ .await
+ }
+
+ async fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ (**self)
+ .enable_notification_type(user_id, notification_event_type)
+ .await
+ }
}
/// Mock queue that tracks published messages.
@@ -708,6 +783,31 @@ async fn test_unsubscribed_user_excluded() {
assert!(result.is_none());
}
+#[tokio::test]
+async fn test_type_disabled_user_excluded() {
+ let disabled_user = test_user_id("[email protected]");
+ let service = NotificationIngressService::new(
+ MockRepository::new().with_type_disabled_user(disabled_user.clone()),
+ MockQueue::new(),
+ MockStateMachine,
+ );
+
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("entity_1"),
+ notification: TestNotification {
+ message: "Hello".to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([disabled_user]),
+ }
+ .into_request();
+
+ let result = service.send_notification(request).await.unwrap();
+
+ // User with type disabled should be excluded, no valid recipients remain
+ assert!(result.is_none());
+}
+
#[tokio::test]
async fn test_queue_message_conn_gateway_only() {
use std::sync::Arc;
diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rs
index 08158fa169..bcd2920a67 100644
--- a/rust/cloud-storage/notification/src/outbound/repository.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository.rs
@@ -5,8 +5,8 @@ mod test;
use crate::domain::models::device::DeviceType;
use crate::domain::models::{
- DeviceEndpoint, NotificationIdAndCollapseKey, SendNotificationRequestBuilder, TaggedContent,
- UserNotificationRow,
+ DeviceEndpoint, DisabledNotificationType, NotificationIdAndCollapseKey,
+ SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,
};
use crate::domain::ports::NotificationRepository;
use crate::outbound::device_registration::DeviceRegistrationDbOps;
@@ -160,6 +160,33 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
&self,
user_id: MacroUserIdStr<'_>,
) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+
+ /// Get users (from the given set) who have disabled the specified notification type.
+ fn get_users_with_type_disabled<'a>(
+ &self,
+ notification_event_type: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> impl std::future::Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
+
+ /// Get all disabled notification types for a user.
+ fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> impl std::future::Future<Output = Result<Vec<DisabledNotificationType>, Report>> + Send;
+
+ /// Disable a notification type for a user (insert).
+ fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;
+
+ /// Re-enable a notification type for a user (delete).
+ fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> impl std::future::Future<Output = Result<(), Report>> + Send;
}
impl NotificationDbOps for PgPool {
@@ -757,6 +784,106 @@ impl NotificationDbOps for PgPool {
Ok(())
}
+
+ async fn get_users_with_type_disabled<'a>(
+ &self,
+ notification_event_type: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ let ids: Vec<String> = user_ids.iter().map(|id| id.to_string()).collect();
+
+ let disabled: Vec<String> = sqlx::query_scalar!(
+ r#"
+ SELECT user_id FROM user_notification_type_preference
+ WHERE notification_event_type = $1 AND user_id = ANY($2)
+ "#,
+ notification_event_type,
+ &ids
+ )
+ .fetch_all(self)
+ .await?;
+
+ let result = disabled
+ .into_iter()
+ .filter_map(|id| {
+ MacroUserIdStr::parse_from_str(&id)
+ .map(CowLike::into_owned)
+ .ok()
+ })
+ .map(|id| id.into_owned())
+ .collect();
+
+ Ok(result)
+ }
+
+ async fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<DisabledNotificationType>, Report> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT user_id, notification_event_type
+ FROM user_notification_type_preference
+ WHERE user_id = $1
+ "#,
+ user_id.as_ref()
+ )
+ .fetch_all(self)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| {
+ let user_id = MacroUserIdStr::parse_from_str(&row.user_id)
+ .map(CowLike::into_owned)
+ .ok()?
+ .into_owned();
+ Some(DisabledNotificationType {
+ user_id,
+ notification_event_type: row.notification_event_type,
+ })
+ })
+ .collect())
+ }
+
+ async fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ sqlx::query!(
+ r#"
+ INSERT INTO user_notification_type_preference (user_id, notification_event_type)
+ VALUES ($1, $2)
+ ON CONFLICT (user_id, notification_event_type) DO NOTHING
+ "#,
+ user_id.as_ref(),
+ notification_event_type
+ )
+ .execute(self)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ sqlx::query!(
+ r#"
+ DELETE FROM user_notification_type_preference
+ WHERE user_id = $1 AND notification_event_type = $2
+ "#,
+ user_id.as_ref(),
+ notification_event_type
+ )
+ .execute(self)
+ .await?;
+
+ Ok(())
+ }
}
impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificationRepository<D> {
@@ -915,4 +1042,41 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {
self.db.delete_by_endpoint(endpoint_arn).await
}
+
+ async fn get_users_with_type_disabled<'a>(
+ &self,
+ notification_event_type: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ self.db
+ .get_users_with_type_disabled(notification_event_type, user_ids)
+ .await
+ }
+
+ async fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<DisabledNotificationType>, Report> {
+ self.db.get_disabled_notification_types(user_id).await
+ }
+
+ async fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ self.db
+ .disable_notification_type(user_id, notification_event_type)
+ .await
+ }
+
+ async fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ self.db
+ .enable_notification_type(user_id, notification_event_type)
+ .await
+ }
}
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
index 3150d1c151..a93ea3b5cf 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -201,4 +201,41 @@ impl NotificationRepository for SandboxNotificationRepository {
async fn delete_device_by_endpoint(&self, endpoint_arn: &str) -> Result<(), Report> {
self.inner.delete_device_by_endpoint(endpoint_arn).await
}
+
+ async fn get_users_with_type_disabled<'a>(
+ &self,
+ notification_event_type: &str,
+ user_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ self.inner
+ .get_users_with_type_disabled(notification_event_type, user_ids)
+ .await
+ }
+
+ async fn get_disabled_notification_types(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ ) -> Result<Vec<notification::domain::models::DisabledNotificationType>, Report> {
+ self.inner.get_disabled_notification_types(user_id).await
+ }
+
+ async fn disable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ self.inner
+ .disable_notification_type(user_id, notification_event_type)
+ .await
+ }
+
+ async fn enable_notification_type(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_event_type: &str,
+ ) -> Result<(), Report> {
+ self.inner
+ .enable_notification_type(user_id, notification_event_type)
+ .await
+ }
}
diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rs
index 8689dd7b21..67f2436de1 100644
--- a/rust/cloud-storage/notification_service/src/api/swagger.rs
+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs
@@ -43,6 +43,11 @@ use crate::{
notification_crate::inbound::http::bulk_mark_done,
notification_crate::inbound::http::bulk_mark_undone,
+ /// /user_notifications/preferences
+ user_notification::get_notification_type_preferences,
+ user_notification::disable_notification_type,
+ user_notification::enable_notification_type,
+
/// /unsubscribe
unsubscribe::get_unsubscribes::handler,
unsubscribe::unsubscribe_item::handler,
@@ -82,6 +87,7 @@ use crate::{
user_notification::ApiUserNotification,
user_notification::GetAllUserNotificationsResponse,
notification_crate::inbound::http::BulkGetByEventItemIdsRequest,
+ user_notification::GetNotificationTypePreferencesResponse,
),
),
tags(
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rs
index f218a45c8c..a136e802ac 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs
@@ -1,13 +1,27 @@
+use std::{collections::HashSet, sync::LazyLock};
+
use ::notification::domain::models::UserNotificationRow;
-use axum::extract::State;
+use axum::{
+ Json,
+ extract::{Path, State},
+ http::StatusCode,
+};
use chrono::{DateTime, Utc};
+use email_formatting::EmailDigestNotification;
use itertools::{Either, Itertools};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use model_error_response::ErrorResponse;
-use model_notifications::NotifEvent;
-use notification::{domain::service::NotificationReader, inbound::http::NotificationRouterState};
-use serde::Serialize;
+use model_notifications::{
+ AiResponseMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata,
+ CommentedOnDocumentMetadata, DocumentMentionMetadata, MentionedInDocumentCommentMetadata,
+ NewEmailMetadata, NotifEvent, RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata,
+};
+use notification::{
+ domain::{models::Notification, service::NotificationReader},
+ inbound::http::NotificationRouterState,
+};
+use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
@@ -119,6 +133,18 @@ pub fn router<S: ::notification::domain::service::NotificationReader>()
axum::routing::get(get_typed_notification_by_id::<S>)
.delete(::notification::inbound::http::delete_notification::<S>),
)
+ .route(
+ "/preferences",
+ axum::routing::get(get_notification_type_preferences::<S>),
+ )
+ .route(
+ "/preferences/{notification_event_type}/disable",
+ axum::routing::put(disable_notification_type::<S>),
+ )
+ .route(
+ "/preferences/{notification_event_type}/enable",
+ axum::routing::put(enable_notification_type::<S>),
+ )
}
/// Wrapper handler that calls the inner generic list handler with `serde_json::Value`,
@@ -379,3 +405,164 @@ async fn get_typed_notification_by_id<S: ::notification::domain::service::Notifi
Ok(axum::Json(ApiUserNotification::from_notification(typed)))
}
+
+/// Path parameter for a notification event type.
+#[derive(Deserialize)]
+pub struct NotificationEventTypePath {
+ /// The notification event type (e.g. "channel_message_send").
+ pub notification_event_type: String,
+}
+
+/// Response for listing disabled notification types.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct GetNotificationTypePreferencesResponse {
+ /// The notification types that the user has disabled.
+ pub disabled_types: Vec<String>,
+}
+
+/// Get the notification types that the user has disabled.
+#[utoipa::path(
+ get,
+ operation_id = "get_notification_type_preferences",
+ path = "/v1/user_notifications/preferences",
+ responses(
+ (status = 200, body = GetNotificationTypePreferencesResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+pub async fn get_notification_type_preferences<S: NotificationReader>(
+ State(state): State<NotificationRouterState<S>>,
+ macro_user: model_user::axum_extractor::MacroUserExtractor,
+) -> Result<
+ axum::Json<GetNotificationTypePreferencesResponse>,
+ (axum::http::StatusCode, axum::Json<ErrorResponse<'static>>),
+> {
+ let disabled = state
+ .inner
+ .get_disabled_notification_types(macro_user.macro_user_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to get notification type preferences");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ axum::Json(ErrorResponse {
+ message: "failed to get notification type preferences".into(),
+ }),
+ )
+ })?;
+
+ Ok(axum::Json(GetNotificationTypePreferencesResponse {
+ disabled_types: disabled
+ .into_iter()
+ .map(|d| d.notification_event_type)
+ .collect(),
+ }))
+}
+
+/// The types of notifications that are blockable
+static BLOCKABLE_NOTIFICATIONS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
+ HashSet::from([
+ EmailDigestNotification::TYPE_NAME,
+ NewEmailMetadata::TYPE_NAME,
+ AiResponseMetadata::TYPE_NAME,
+ ChannelMessageSendMetadata::TYPE_NAME,
+ ChannelMentionMetadata::TYPE_NAME,
+ ChannelReplyMetadata::TYPE_NAME,
+ DocumentMentionMetadata::TYPE_NAME,
+ TaskAssignedMetadata::TYPE_NAME,
+ MentionedInDocumentCommentMetadata::TYPE_NAME,
+ RepliedToDocumentCommentThreadMetadata::TYPE_NAME,
+ CommentedOnDocumentMetadata::TYPE_NAME,
+ ])
+});
+
+/// Disable a notification type for the authenticated user.
+#[utoipa::path(
+ put,
+ operation_id = "disable_notification_type",
+ path = "/v1/user_notifications/preferences/{notification_event_type}/disable",
+ params(
+ ("notification_event_type" = String, Path, description = "The notification event type to disable"),
+ ),
+ responses(
+ (status = 200),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+pub async fn disable_notification_type<S: NotificationReader>(
+ State(state): State<NotificationRouterState<S>>,
+ macro_user: model_user::axum_extractor::MacroUserExtractor,
+ Path(NotificationEventTypePath {
+ notification_event_type,
+ }): Path<NotificationEventTypePath>,
+) -> Result<axum::Json<()>, (axum::http::StatusCode, axum::Json<ErrorResponse<'static>>)> {
+ // make sure the notification to block is one that matches the list
+ let true = BLOCKABLE_NOTIFICATIONS.contains(notification_event_type.as_str()) else {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: format!(
+ "Cannot block notification type {notification_event_type}. Expected one of {:?}",
+ &*BLOCKABLE_NOTIFICATIONS
+ ).into(),
+ }),
+ ));
+ };
+
+ state
+ .inner
+ .disable_notification_type(macro_user.macro_user_id, &notification_event_type)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to disable notification type");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ axum::Json(ErrorResponse {
+ message: "failed to disable notification type".into(),
+ }),
+ )
+ })?;
+
+ Ok(axum::Json(()))
+}
+
+/// Re-enable a notification type for the authenticated user.
+#[utoipa::path(
+ put,
+ operation_id = "enable_notification_type",
+ path = "/v1/user_notifications/preferences/{notification_event_type}/enable",
+ params(
+ ("notification_event_type" = String, Path, description = "The notification event type to enable"),
+ ),
+ responses(
+ (status = 200),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+pub async fn enable_notification_type<S: NotificationReader>(
+ State(state): State<NotificationRouterState<S>>,
+ macro_user: model_user::axum_extractor::MacroUserExtractor,
+ Path(NotificationEventTypePath {
+ notification_event_type,
+ }): Path<NotificationEventTypePath>,
+) -> Result<axum::Json<()>, (axum::http::StatusCode, axum::Json<ErrorResponse<'static>>)> {
+ state
+ .inner
+ .enable_notification_type(macro_user.macro_user_id, &notification_event_type)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to enable notification type");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ axum::Json(ErrorResponse {
+ message: "failed to enable notification type".into(),
+ }),
+ )
+ })?;
+
+ Ok(axum::Json(()))
+}